update
Browse files37 unmodified lines383940414243444551 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521 unmodified line1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982995 unmodified lines30530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034156 unmodified lines3983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354 unmodified lines44044144244344444544644744844945045145245345445545645745845946046146246346446546637 unmodified lineslatest_data = {"bed_temperature": "N/A","nozzle_temperature": "N/A","status": "Disconnected","update_time": "Not connected"}# Initialize analysis components51 unmodified lineszip_buffer.seek(0)return zip_bufferdef create_client(host, port, username, password, max_retries=3):"""Create MQTT client with retry mechanism"""global clientfor attempt in range(max_retries):try:client = mqtt.Client(protocol=mqtt.MQTTv311)client.username_pw_set(username, password)client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)client.on_connect = on_connectclient.on_message = on_messageclient.on_disconnect = on_disconnectprint(f"Attempting to connect to MQTT broker (attempt {attempt + 1}/{max_retries})")client.connect(host, port, keepalive=60)client.loop_start()return Trueexcept Exception as e:print(f"Connection attempt {attempt + 1} failed: {e}")if client:client.loop_stop()client = Noneif attempt < max_retries - 1:time.sleep(5)print("Failed to connect to MQTT broker after all attempts")return Falsedef on_connect(client, userdata, flags, rc):"""Callback when connected to MQTT broker"""if rc == 0:print("Successfully connected to MQTT broker")response_topic = f"bambu_a1_mini/response/{PRINTER_SERIAL}"request_topic = f"bambu_a1_mini/request/{PRINTER_SERIAL}"client.subscribe(response_topic)print(f"Subscribed to {response_topic}")# Send initial requestclient.publish(request_topic, json.dumps("HI"))# Update statusglobal latest_datalatest_data["status"] = "Connected"latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S")else:print(f"Failed to connect to MQTT broker with code: {rc}")def on_message(client, userdata, message):"""Handle incoming MQTT messages"""global latest_dataprint("Received message")try:1 unmodified linelatest_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")except Exception as e:print(f"Error parsing MQTT message: {e}")def on_disconnect(client, userdata, rc):"""Callback when disconnected from MQTT broker"""print("Disconnected from MQTT broker")global latest_datalatest_data["status"] = "Disconnected"latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S")if rc != 0:print("Unexpected disconnection. Attempting to reconnect...")create_client(HOST, PORT, USERNAME, PASSWORD)def send_print_command(params):"""Send print parameters to Pi 4B"""command = create_print_command(params)mqtt_client.publish(TOPICS['printer']['command'], json.dumps(command))logger.info(f"Print command sent for square {params.get('square_id')}")return "Print command sent successfully"def send_camera_command(square_id: str):"""Send capture command to Pi Zero"""command = create_capture_command(square_id)mqtt_client.publish(TOPICS['camera']['command'], json.dumps(command))logger.info(f"Camera command sent for square {square_id}")return "Camera command sent successfully"def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):"""Send new print parameters to printer"""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/{PRINTER_SERIAL}"if client:client.publish(request_topic, json.dumps({'command': 'set_parameters','parameters': params}))return "Parameters sent successfully"return "MQTT not connected"except Exception as e:return f"Error sending parameters: {e}"# Initialize MQTT clienttry:mqtt_connected = create_client(HOST, PORT, USERNAME, PASSWORD)if not mqtt_connected:print("Warning: Starting without MQTT connection")except Exception as e:print(f"Warning: Failed to initialize MQTT: {e}")def update_status():"""Update printer status display"""if client is None:return "N/A", "N/A", "Disconnected", "Not connected"try:request_topic = f"bambu_a1_mini/request/{PRINTER_SERIAL}"client.publish(request_topic, json.dumps("HI"))return (latest_data["nozzle_temperature"],latest_data["bed_temperature"],latest_data["status"],latest_data["update_time"])except Exception as e:print(f"Status update error: {e}")return "N/A", "N/A", "Error", str(e)def analyze_print(image, nozzle_temp, bed_temp, print_speed, fan_speed):"""Analyze print quality and return evaluation results"""if image is None:return None, 0, 0, 0, 0, 0, 0, 0, 0# Package current parameterscurrent_params = {'nozzle_temp': float(nozzle_temp),'bed_temp': float(bed_temp),'print_speed': float(print_speed),'fan_speed': float(fan_speed)}# Analyze print qualityanalysis_results = detector.analyze_print(image)# Get optimization resultsresults = optimizer.evaluate_objectives(image, current_params)# Calculate quality metricsmetrics = detector.calculate_quality_metrics(image)return (analysis_results['binary_mask'], # Visualizationfloat(metrics['missing_rate']),float(metrics['excess_rate']),float(metrics['stringing_rate']),float(metrics['uniformity_score']),float(analysis_results['quality_score']),float(results['objectives']['speed']),float(results['objectives']['material']),float(results['objectives']['total']))# Gradio interfacewith gr.Blocks(title="Bambu A1 Mini Print Analysis") as demo:gr.Markdown("# Bambu A1 Mini Print Quality Analysis")# Current printer parameters displaywith gr.Row():current_nozzle_temp = gr.Textbox(label="Current Nozzle Temperature",value="N/A",interactive=False)current_bed_temp = gr.Textbox(label="Current Bed Temperature",value="N/A",interactive=False)current_status = gr.Textbox(label="Printer Status",value="N/A",interactive=False)last_update = gr.Textbox(label="Last Update",value="N/A",interactive=False)refresh_btn = gr.Button("Refresh Status")with gr.Row():# show S3 images3_image = gr.Image(5 unmodified lineslabel="Current Print Image",type="numpy")with gr.Row():with gr.Column():# Print parameter inputsnozzle_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 (%)")# Buttonswith gr.Row():capture_btn = gr.Button("Capture Image")analyze_btn = gr.Button("Analyze Print")send_params_btn = gr.Button("Send Print Parameters") # 新增按钮with gr.Column():# Results visualizationresult_image = gr.Image(label="Analysis Result")56 unmodified lines)# connect refresh buttondef update_status():"""Update printer status display"""return (latest_data["nozzle_temperature"],latest_data["bed_temperature"],latest_data["status"],latest_data["update_time"])refresh_btn.click(fn=update_status,outputs=[current_nozzle_temp,current_bed_temp,current_status,last_update])# Auto refreshdef auto_refresh():while True:try:time.sleep(5)values = update_status()current_nozzle_temp.value = values[0]current_bed_temp.value = values[1]current_status.value = values[2]last_update.value = values[3]except Exception as e:print(f"Auto refresh error: {e}")continuethreading.Thread(target=auto_refresh, daemon=True).start()4 unmodified linesoutputs=[current_status])def handle_print_workflow(params):"""Coordinate print and capture workflow"""try:# 1. Send print command to Pi 4Bprinter_command = create_print_command(params)mqtt_client.publish(TOPICS['printer']['command'], json.dumps(printer_command))# 2. Wait for printer ready status# (handle by on_message callback)# 3. Send capture command to Pi Zerocamera_command = create_capture_command(params['square_id'])mqtt_client.publish(TOPICS['camera']['command'], json.dumps(camera_command))# 4. Wait for image URL# (handle by on_message callback)return "Workflow started successfully"except Exception as e:return f"Error: {str(e)}"# Launch the appif __name__ == "__main__":demo.launch(ssr=False)37 unmodified lines383940414243444551 unmodified lines9798991001011021031041051061071081091101111121131141151161 unmodified line1181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611625 unmodified lines16816917017117217317417517617717817918018118218318418518618718856 unmodified lines2452462472482492502512522532542552562572582592602614 unmodified lines26626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532637 unmodified lineslatest_data = {"bed_temperature": "N/A","nozzle_temperature": "N/A","status": "N/A","update_time": "Waiting for data..."}# Initialize analysis components51 unmodified lineszip_buffer.seek(0)return zip_bufferdef create_client(host, port, username, password):global clientclient = mqtt.Client()client.username_pw_set(username, password)client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)client.on_connect = on_connectclient.on_message = on_messageclient.connect(host, port)client.loop_start()def on_connect(client, userdata, flags, rc):print(f"Connected with result code {rc}")def on_message(client, userdata, message):global latest_dataprint("Received message")try:1 unmodified linelatest_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())except Exception as e:print(f"Error parsing MQTT message: {e}")def get_data():"""Request data from the MQTT broker."""global clientif client is None:create_client(HOST, PORT, USERNAME, PASSWORD)serial = "0309CA471800852"request_topic = f"bambu_a1_mini/request/{serial}"response_topic = f"bambu_a1_mini/response/{serial}"print(f"Subscribing to {response_topic}")client.subscribe(response_topic)# Send a request to get dataclient.publish(request_topic, json.dumps("HI"))return (latest_data["status"],latest_data["bed_temperature"],latest_data["nozzle_temperature"],latest_data["update_time"])# Gradio interfacewith gr.Blocks(title="Bambu A1 Mini Print Analysis") as demo:gr.Markdown("# Bambu A1 Mini Print Quality Analysis")with gr.Row():current_nozzle_temp = gr.Textbox(label="Current Nozzle Temperature", value="N/A", interactive=False)current_bed_temp = gr.Textbox(label="Current Bed Temperature", value="N/A", interactive=False)current_status = gr.Textbox(label="Printer Status", value="N/A", interactive=False)last_update = gr.Textbox(label="Last Update", value="N/A", interactive=False)refresh_btn = gr.Button("Refresh Status")with gr.Row():# show S3 images3_image = gr.Image(5 unmodified lineslabel="Current Print Image",type="numpy")with gr.Row():with gr.Column():# Print parameter inputsnozzle_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 (%)")# Buttonswith gr.Row():capture_btn = gr.Button("Capture Image")analyze_btn = gr.Button("Analyze Print")send_params_btn = gr.Button("Send Print Parameters")with gr.Column():# Results visualizationresult_image = gr.Image(label="Analysis Result")56 unmodified lines)# connect refresh buttonrefresh_btn.click(fn=get_data, outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update])# Auto refreshdef auto_refresh():while True:time.sleep(5)status, bed_temp, nozzle_temp, update_time = get_data()current_status.value = statuscurrent_bed_temp.value = bed_tempcurrent_nozzle_temp.value = nozzle_templast_update.value = update_timethreading.Thread(target=auto_refresh, daemon=True).start()4 unmodified linesoutputs=[current_status])def analyze_print(image, nozzle_temp, bed_temp, print_speed, fan_speed):"""Analyze print quality and return evaluation results"""if image is None:return None, 0, 0, 0, 0, 0, 0, 0, 0# Package current parameterscurrent_params = {'nozzle_temp': float(nozzle_temp),'bed_temp': float(bed_temp),'print_speed': float(print_speed),'fan_speed': float(fan_speed)}# Analyze print qualityanalysis_results = detector.analyze_print(image)# Get optimization resultsresults = optimizer.evaluate_objectives(image, current_params)# Calculate quality metricsmetrics = detector.calculate_quality_metrics(image)return (analysis_results['binary_mask'], # Visualizationfloat(metrics['missing_rate']),float(metrics['excess_rate']),float(metrics['stringing_rate']),float(metrics['uniformity_score']),float(analysis_results['quality_score']),float(results['objectives']['speed']),float(results['objectives']['material']),float(results['objectives']['total']))def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed):"""Send new print parameters to printer"""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/{PRINTER_SERIAL}"if client:client.publish(request_topic, json.dumps({'command': 'set_parameters','parameters': params}))return "Parameters sent successfully"return "MQTT not connected"except Exception as e:return f"Error sending parameters: {e}"# Launch the appif __name__ == "__main__":demo.launch()
app.py+99-239