temporarily revert to previous version for seeds data collection
Browse files1 unmodified line2345678910111213141516175 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421 unmodified lineimport paho.mqtt.client as mqttimport jsonimport timeimport osimport requestsimport tracebackfrom PIL import Imageimport ioimport threadingprint("Starting MQTT Print Control...")# Environment variablesBAMBU_HOST = os.environ.get("BAMBU_HOST", "default_host")BAMBU_PORT = int(os.environ.get("BAMBU_PORT", 1883))BAMBU_USERNAME = os.environ.get("BAMBU_USERNAME", "default_user")5 unmodified linesRPI_USERNAME = os.environ.get("RPI_USERNAME", "default_user")RPI_PASSWORD = os.environ.get("RPI_PASSWORD", "default_pass")latest_data = {}# Centralized MQTT client setupdef setup_mqtt_client(host, port, username, password, on_message):client = mqtt.Client()client.username_pw_set(username, password)client.on_message = on_messageclient.connect(host, port)client.loop_start()return client# Single callback responsibilitydef bambu_on_message(client, userdata, message):global latest_datalatest_data.update(json.loads(message.payload))latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())def rpi_on_message(client, userdata, message):global latest_datalatest_data.update(json.loads(message.payload))latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())# Centralized error handlingdef main_logic():global bambu_client, rpi_clienttry:bambu_client = setup_mqtt_client(BAMBU_HOST, BAMBU_PORT, BAMBU_USERNAME, BAMBU_PASSWORD, bambu_on_message)rpi_client = setup_mqtt_client(RPI_HOST, RPI_PORT, RPI_USERNAME, RPI_PASSWORD, rpi_on_message)bambu_client.subscribe(f"bambu_a1_mini/response/{DEFAULT_SERIAL}")rpi_client.subscribe(f"bambu_a1_mini/response/{DEFAULT_SERIAL}")except Exception:print("MQTT setup failed:")traceback.print_exc()# Sending print parameters functionalitydef send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):try:params = {"nozzle_temp": nozzle_temp,"bed_temp": bed_temp,"print_speed": print_speed,"fan_speed": fan_speed,"command": "generate_gcode",}topic = f"bambu_a1_mini/request/{DEFAULT_SERIAL}"rpi_client.publish(topic, json.dumps(params))return "Parameters sent successfully."except Exception:print("Failed to send parameters:")traceback.print_exc()return "Failed to send parameters."# Simple Gradio interfacedef get_status():return (latest_data.get("status", "N/A"),latest_data.get("bed_temperature", "N/A"),latest_data.get("nozzle_temperature", "N/A"),latest_data.get("update_time", "Waiting for data..."),)# Image capture functionalitydef capture_image():try:img_url = latest_data.get("image_url", None)if img_url and img_url != "N/A":response = requests.get(img_url, timeout=10)if response.status_code == 200:return Image.open(io.BytesIO(response.content))return Noneexcept Exception:print("Image capture failed:")traceback.print_exc()return Nonewith gr.Blocks(title="Simplified Printer Control") as demo:status = gr.Textbox(label="Status")bed_temp = gr.Textbox(label="Bed Temperature")nozzle_temp = gr.Textbox(label="Nozzle Temperature")update_time = gr.Textbox(label="Last Update")image_display = gr.Image(label="Captured Image", type="pil")nozzle_input = gr.Slider(label="Nozzle Temperature", minimum=180, maximum=250, value=200)bed_input = gr.Slider(label="Bed Temperature", minimum=40, maximum=100, value=60)speed_input = gr.Slider(label="Print Speed", minimum=20, maximum=150, value=60)fan_input = gr.Slider(label="Fan Speed", minimum=0, maximum=100, value=100)refresh = gr.Button("Refresh")refresh.click(fn=get_status, outputs=[status, bed_temp, nozzle_temp, update_time])capture_btn = gr.Button("Capture Image")capture_btn.click(fn=capture_image, outputs=image_display)send_params_btn = gr.Button("Send Parameters")send_params_btn.click(fn=send_print_parameters,inputs=[nozzle_input, bed_input, speed_input, fan_input],outputs=status,)print("App initializing...")threading.Thread(target=main_logic, daemon=True).start()demo.launch()1 unmodified line23456789101112131415161718192021222324252627285 unmodified lines3435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476481 unmodified lineimport paho.mqtt.client as mqttimport jsonimport timeimport threadingimport osimport base64from PIL import Imageimport ioimport numpy as npimport loggingimport sysimport randomimport cv2from PIL import ImageDrawimport requestslogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",handlers=[logging.StreamHandler(sys.stdout), logging.FileHandler("app.log")],)logger = logging.getLogger("bambu-analysis")BAMBU_HOST = os.environ.get("BAMBU_HOST", "default_host")BAMBU_PORT = int(os.environ.get("BAMBU_PORT", 1883))BAMBU_USERNAME = os.environ.get("BAMBU_USERNAME", "default_user")5 unmodified linesRPI_USERNAME = os.environ.get("RPI_USERNAME", "default_user")RPI_PASSWORD = os.environ.get("RPI_PASSWORD", "default_pass")logger.info(f"BAMBU MQTT Configuration: HOST={BAMBU_HOST}, PORT={BAMBU_PORT}, USERNAME={BAMBU_USERNAME}, PWD={'*'*len(BAMBU_PASSWORD)}")logger.info(f"RPI MQTT Configuration: HOST={RPI_HOST}, PORT={RPI_PORT}, USERNAME={RPI_USERNAME}, PWD={'*'*len(RPI_PASSWORD)}")latest_data = {"bed_temperature": "N/A","nozzle_temperature": "N/A","status": "N/A","update_time": "Waiting for data...","image_url": "N/A","progress": 0,"message": "",}bambu_client = Nonerpi_client = Noneresponse_topic = None # Will be set dynamically# add a global variable to track if the application just startedis_first_load = Truedef create_client(client_type):global bambu_client, rpi_clientif client_type == "bambu":bambu_client = mqtt.Client()bambu_client.username_pw_set(BAMBU_USERNAME, BAMBU_PASSWORD)bambu_client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)bambu_client.on_connect = on_connectbambu_client.on_message = bambu_on_messagebambu_client.connect(BAMBU_HOST, BAMBU_PORT)bambu_client.loop_start()elif client_type == "rpi":rpi_client = mqtt.Client()rpi_client.username_pw_set(RPI_USERNAME, RPI_PASSWORD)rpi_client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)rpi_client.on_connect = on_connectrpi_client.on_message = rpi_on_messagerpi_client.connect(RPI_HOST, RPI_PORT)rpi_client.loop_start()def on_connect(client, userdata, flags, rc):logger.info(f"Connected with result code {rc}")def bambu_on_message(client, userdata, message):global latest_datalogger.info("Received message")try:data = json.loads(message.payload)latest_data["bed_temperature"] = data.get("bed_temperature", "N/A")latest_data["nozzle_temperature"] = data.get("nozzle_temperature", "N/A")latest_data["status"] = data.get("status", "N/A")latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())latest_data["image_url"] = data.get("image_url", "N/A")except Exception as e:logger.error(f"Error parsing MQTT message: {e}")def rpi_on_message(client, userdata, msg):global latest_datatry:payload = msg.payload.decode("utf-8")logger.info(f"Received message from RPI: {payload}")data = json.loads(payload)status = data.get("status", "Unknown")latest_data["status"] = statuslatest_data["update_time"] = data.get("update_time", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))if "nozzle_temperature" in data:latest_data["nozzle_temperature"] = data["nozzle_temperature"]if "bed_temperature" in data:latest_data["bed_temperature"] = data["bed_temperature"]if "error" in data:logger.error(f"Error from RPI: {data['error']}")if status == "Ready":latest_data["progress"] = 0latest_data["message"] = "Printer ready"elif status == "Processing":latest_data["progress"] = 25latest_data["message"] = "Processing G-code..."except Exception as e:logger.error(f"Error processing message from RPI: {e}")try:result = json.loads(payload)if "status" in result:status = result["status"]latest_data["status"] = statusif ("command" in resultand result["command"] == "capture_image"and result.get("auto_triggered", False)):logger.info("receive capture command")threading.Thread(target=handle_auto_capture, args=(result,), daemon=True).start()except json.JSONDecodeError:logger.error(f"Invalid JSON in message: {payload}")def get_data(serial=DEFAULT_SERIAL):global bambu_client, response_topicif bambu_client is None:create_client("bambu")request_topic = f"bambu_a1_mini/request/{serial}"response_topic = f"bambu_a1_mini/response/{serial}"logger.info(f"Subscribing to {response_topic}")bambu_client.subscribe(response_topic)logger.info(f"Publishing request to {request_topic}")bambu_client.publish(request_topic, json.dumps("HI"))global latest_datalatest_data["bed_temperature"] = "N/A"timeout = 10while latest_data["bed_temperature"] == "N/A" and timeout > 0:time.sleep(1)timeout -= 1return (latest_data["status"],latest_data["bed_temperature"],latest_data["nozzle_temperature"],latest_data["update_time"],)def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):global rpi_clientserial = DEFAULT_SERIALlogger.info(f"Sending parameters to RPi for G-code generation: nozzle={nozzle_temp}, bed={bed_temp}, "f"speed={print_speed}, fan={fan_speed}")try:params = {"nozzle_temp": nozzle_temp,"bed_temp": bed_temp,"print_speed": print_speed,"fan_speed": fan_speed,}request_topic = f"bambu_a1_mini/request/{serial}"if rpi_client:rpi_client.publish(request_topic,json.dumps({"command": "generate_gcode", "parameters": params}),)logger.info("Parameters sent successfully to RPi for G-code generation")global latest_datalatest_data["status"] = "Sent"latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())return "Parameters sent successfully to RPi. Status: Sent"else:logger.warning("MQTT not connected, parameters not sent")return "MQTT not connected, parameters not sent"except Exception as e:logger.error(f"Error sending parameters: {e}")return f"Error sending parameters: {e}"latest_data["status"] = "Sending"latest_data["progress"] = 10latest_data["message"] = "Sending parameters to printer..."def get_image_base64(image):if image is None:logger.warning("No image to encode")return Nonetry:if isinstance(image, np.ndarray):image = Image.fromarray(image)buffer = io.BytesIO()image.save(buffer, format="PNG")img_str = base64.b64encode(buffer.getvalue()).decode("utf-8")logger.info(f"Image encoded to base64 (length: {len(img_str)})")return img_strexcept Exception as e:logger.error(f"Error encoding image: {e}")return Nonedef handle_auto_capture(message):try:logger.info(f"receive capture command: {message}")print_job = message.get("print_job", "unknown_job")timestamp = message.get("timestamp", time.strftime("%Y-%m-%d %H:%M:%S"))latest_data["auto_capture_requested"] = Truelatest_data["last_capture_job"] = print_joblatest_data["last_capture_time"] = timestampreturn capture_image()except Exception as e:logger.error(f"error: {e}")return None, f"capture failed: {str(e)}"def capture_image(url=None):global rpi_client, latest_dataif rpi_client is None:create_client("rpi")serial = DEFAULT_SERIALrequest_topic = f"bambu_a1_mini/request/{serial}"response_topic = f"bambu_a1_mini/response/{serial}"logger.info(f"Subscribing to {response_topic}")rpi_client.subscribe(response_topic)rpi_client.publish(request_topic,json.dumps({"command": "capture_image",}),)latest_data["image_url"] = "N/A"timeout = 45while latest_data["image_url"] == "N/A" and timeout > 0:# print("timeout", timeout)time.sleep(1)timeout -= 1url = latest_data["image_url"]if url != "N/A":try:logger.info(f"Capturing image from URL: {url}")response = requests.get(url, timeout=10)if response.status_code == 200:return Image.open(io.BytesIO(response.content))else:logger.error(f"Failed to get image from URL: {response.status_code}")except Exception as e:logger.error(f"Error capturing image from URL: {e}")else:raise Exception("url is 'N/A'")def update_print_status():global latest_datareturn (latest_data["status"],latest_data["nozzle_temperature"],latest_data["bed_temperature"],latest_data["update_time"],latest_data.get("progress", 0),latest_data.get("message", ""),)def health_check():status = {"app": "running","time": time.strftime("%Y-%m-%d %H:%M:%S"),"bambu_mqtt_connected": bambu_client is not None,"rpi_mqtt_connected": rpi_client is not None,"latest_update": latest_data["update_time"],}logger.info(f"Health check: {status}")return statusdemo = gr.Blocks(title="Bambu A1 Mini Print Control")with demo:gr.Markdown("# Bambu A1 Mini Print Control")with gr.Row():refresh_btn = gr.Button("Refresh Status")with gr.Row():current_status = gr.Textbox(label="Printer Status", value="N/A", interactive=False)current_bed_temp = gr.Textbox(label="Current Bed Temperature", value="N/A", interactive=False)current_nozzle_temp = gr.Textbox(label="Current Nozzle Temperature", value="N/A", interactive=False)last_update = gr.Textbox(label="Last Update", value="N/A", interactive=False)with gr.Row():# Left column for image and capture buttonwith gr.Column(scale=2):captured_image = gr.Image(label="Current Print Image", type="pil")capture_btn = gr.Button("Capture Image")# Right column for queue status and livestreamwith gr.Column(scale=1):gr.Markdown("### YouTube Livestream")iframe_html = """<div style="position: relative; width: 100%; padding-top: 56.25%;"><iframestyle="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"src="https://www.youtube.com/embed/ZzYOO6y6cJU"title="Bambu A1mini Livestream"frameborder="0"allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"referrerpolicy="strict-origin-when-cross-origin"allowfullscreen></iframe></div>"""gr.HTML(iframe_html)with gr.Row():with gr.Column():nozzle_temp = gr.Slider(minimum=180,maximum=250,step=1,value=200,label="Nozzle Temperature (°C)",)bed_temp = gr.Slider(minimum=40, maximum=100, step=1, value=60, label="Bed Temperature (°C)")print_speed = gr.Slider(minimum=20, maximum=150, step=1, value=60, label="Print Speed (mm/s)")fan_speed = gr.Slider(minimum=0, maximum=100, step=1, value=100, label="Fan Speed (%)")send_params_btn = gr.Button("Send Print Parameters")refresh_btn.click(fn=get_data,outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update],)capture_btn.click(fn=lambda: gr.update(interactive=False), outputs=capture_btn).then(fn=capture_image, outputs=[captured_image]).then(fn=lambda: gr.update(interactive=True), outputs=capture_btn)def api_send_print_parameters(nozzle_temp=200, bed_temp=60, print_speed=60, fan_speed=100):"""API endpoint to send print parameters to the Bambu printer via RPI MQTT"""global is_first_load# if the application just started, skip the actual operationif is_first_load:logger.info("First load detected, skipping automatic parameter sending")is_first_load = Falsereturn "Ready to send parameters. Click 'Submit' to send."# the original function, only execute when the user explicitly requests itreturn send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed)send_params_btn.click(fn=api_send_print_parameters,inputs=[nozzle_temp, bed_temp, print_speed, fan_speed],outputs=[current_status],)def api_get_data():logger.info("API call: get_data")return get_data()def api_capture_frame(url=None):logger.info(f"API call: capture_frame with URL: {url}")try:img = capture_image(url)if img:if img.mode == "RGBA":img = img.convert("RGB")buffered = io.BytesIO()img.save(buffered, format="JPEG")img_str = base64.b64encode(buffered.getvalue()).decode()return {"success": True, "image": img_str}else:return {"success": False, "error": "Failed to capture image"}except Exception as e:logger.error(f"Error in capture_frame: {e}")return {"success": False, "error": str(e)}def api_lambda(img_data=None,param_1=200,param_2=60,param_3=60,param_4=100,):logger.info(f"API call: lambda with params: {param_1}, {param_2}, {param_3}, {param_4}")try:img = Noneif (img_dataand isinstance(img_data, str)and (img_data.startswith("http://") or img_data.startswith("https://"))):logger.info(f"Lambda received image URL: {img_data}")img = capture_image(img_data)elif img_data and isinstance(img_data, str):try:logger.info("Lambda received base64 image data")img_bytes = base64.b64decode(img_data)img = Image.open(io.BytesIO(img_bytes))except Exception as e:logger.error(f"Failed to decode base64 image: {e}")if img:img_array = np.array(img)quality_level = "low"if 190 <= param_1 <= 210 and param_3 <= 50 and param_4 >= 80:quality_level = "high"elif 185 <= param_1 <= 215 and param_3 <= 70 and param_4 >= 60:quality_level = "medium"if quality_level == "high":missing_rate = 0.02excess_rate = 0.01stringing_rate = 0.01elif quality_level == "medium":missing_rate = 0.05excess_rate = 0.03stringing_rate = 0.02else: # lowmissing_rate = 0.10excess_rate = 0.07stringing_rate = 0.05uniformity_score = 1.0 - (missing_rate + excess_rate + stringing_rate)print_quality_score = 1.0 - (missing_rate * 2.0 + excess_rate * 1.5 + stringing_rate * 1.0)print_quality_score = max(0, min(1, print_quality_score))print_speed_score = param_3 / 150.0print_speed_score = max(0, min(1, print_speed_score))material_efficiency_score = 1.0 - excess_rate * 3.0material_efficiency_score = max(0, min(1, material_efficiency_score))total_performance_score = (0.5 * print_quality_score+ 0.3 * print_speed_score+ 0.2 * material_efficiency_score)img_draw = img.copy()draw = ImageDraw.Draw(img_draw)draw.text((10, 10), f"Quality: {quality_level.upper()}", fill=(255, 0, 0))draw.text((10, 30), f"Missing: {missing_rate:.2f}", fill=(255, 0, 0))draw.text((10, 50), f"Excess: {excess_rate:.2f}", fill=(255, 0, 0))draw.text((10, 70), f"Stringing: {stringing_rate:.2f}", fill=(255, 0, 0))result = {"success": True,"missing_rate": missing_rate,"excess_rate": excess_rate,"stringing_rate": stringing_rate,"uniformity_score": uniformity_score,"print_quality_score": print_quality_score,"print_speed_score": print_speed_score,"material_efficiency_score": material_efficiency_score,"total_performance_score": total_performance_score,}if img_draw.mode == "RGBA":img_draw = img_draw.convert("RGB")buffered = io.BytesIO()img_draw.save(buffered, format="JPEG")img_str = base64.b64encode(buffered.getvalue()).decode()result["image"] = img_strreturn resultelse:return {"success": False, "error": "Failed to get image"}except Exception as e:logger.error(f"Error in lambda: {e}")return {"error": str(e)}api_json_output = gr.JSON()api_text_output = gr.Textbox()capture_frame_api = demo.load(fn=api_capture_frame,inputs=[gr.Text(label="Camera URL (Optional)")],outputs=[gr.Image(label="Captured Frame"), gr.JSON()],api_name="capture_frame")lambda_api = demo.load(fn=api_lambda,inputs=[gr.Image(label="Image Data"),gr.Number(label="Nozzle Temperature", value=200),gr.Number(label="Bed Temperature", value=60),gr.Number(label="Print Speed", value=60),gr.Number(label="Fan Speed", value=100),],outputs=[gr.Image(label="Visualization"), gr.JSON()],api_name="lambda")get_data_api = demo.load(fn=api_get_data,inputs=[],outputs=gr.JSON(),api_name="get_data")send_params_api = demo.load(fn=api_send_print_parameters,inputs=[gr.Number(label="Nozzle Temperature", value=200),gr.Number(label="Bed Temperature", value=60),gr.Number(label="Print Speed", value=60),gr.Number(label="Fan Speed", value=100),],outputs=api_text_output,api_name="send_print_parameters")get_status_api = demo.load(fn=update_print_status,inputs=[],outputs=[gr.Textbox(label="Status"),gr.Textbox(label="Nozzle Temperature"),gr.Textbox(label="Bed Temperature"),gr.Textbox(label="Update Time"),gr.Number(label="Progress"),gr.Textbox(label="Message"),],api_name="get_status")health_check_api = demo.load(fn=health_check,inputs=[],outputs=gr.JSON(),api_name="health_check")if __name__ == "__main__":logger.info("Starting Bambu A1 Mini Print Control application")try:logger.info("Initializing Bambu MQTT client")create_client("bambu")except Exception as e:logger.error(f"Failed to initialize Bambu MQTT: {e}")try:logger.info("Initializing RPI MQTT client")create_client("rpi")except Exception as e:logger.error(f"Failed to initialize RPI MQTT: {e}")demo.queue().launch(show_error=True, share=False, server_name="0.0.0.0", server_port=7860)
app.py+589-83