update
Browse files21 unmodified lines2223242526272829252627282930313233323334353638373839404142434442454647482 unmodified lines515253515455564 unmodified lines6162636263646566676869707172737475767778798081828384646566678768697071897273749375767797787980811011021038283848510510610786871091101111121131141151161171181191201211221238889909112512612712812913013113213313413513613713813914014114214314414514614792939495969798991001011021031041051061071081091101111121131141151161171181191201211221491231241251261271285 unmodified lines13413513616213713813914046 unmodified lines18718818921519019119219319419519622219719822419920022620120222820320420523120620723320820921023621121223821321421524124224321621721821924524624724824925025122022122222322422522622722822923023123223323425425523523623725725825923823924024126124224326326426526626726826927027127227327424424524624724824925025128125225325419 unmodified lines2742752763072772782794 unmodified lines2842852863182872882892903223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543552912922932 unmodified lines2962972983642993003013029 unmodified lines31231331438038131538338438531631731831932032132232332432521 unmodified lines)logger = logging.getLogger("bambu-analysis")
# Environment Variables - 尝试从环境变量获取,如果没有则使用默认值HOST = os.environ.get("host", "mqtt.bambulab.com")PORT = int(os.environ.get("port", "8883"))USERNAME = os.environ.get("username", "bblp")PASSWORD = os.environ.get("password", "bblp")# Environment Variables - 使用同事的配置方式HOST = "mqtt.bambulab.com"PORT = 8883USERNAME = "bblp"PASSWORD = "bblp"DEFAULT_SERIAL = "0309CA471800852"
# Global variablesclient = None# Global variables to store received data - 完全保持同事的数据结构latest_data = { "bed_temperature": "N/A", "nozzle_temperature": "N/A", "status": "N/A", "update_time": "Waiting for data..." "update_time": "Waiting for data...",}
# MQTT Client setup - 完全保持同事的客户端设置client = Noneresponse_topic = None # Will be set dynamically
def create_client(host, port, username, password): """创建并配置MQTT客户端""" """创建并配置MQTT客户端 - 使用同事的代码""" global client try: logger.info(f"Creating MQTT client for {host}:{port}")2 unmodified lines client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS) client.on_connect = on_connect client.on_message = on_message client.on_disconnect = on_disconnect logger.info("Connecting to MQTT broker...") client.connect(host, port)4 unmodified lines return False
def on_connect(client, userdata, flags, rc): """MQTT连接回调""" if rc == 0: logger.info("Successfully connected to MQTT broker") serial = DEFAULT_SERIAL response_topic = f"bambu_a1_mini/response/{serial}" request_topic = f"bambu_a1_mini/request/{serial}" try: client.subscribe(response_topic) logger.info(f"Subscribed to {response_topic}") # 发送初始请求 client.publish(request_topic, json.dumps("HI")) logger.info(f"Sent initial request to {request_topic}") # 更新状态 global latest_data latest_data["status"] = "Connected" latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S") except Exception as e: logger.error(f"Error in on_connect callback: {e}") else: logger.error(f"Failed to connect to MQTT broker with code: {rc}") """MQTT连接回调 - 使用同事的代码""" logger.info(f"Connected with result code {rc}")
def on_message(client, userdata, message): """MQTT消息回调""" """MQTT消息回调 - 使用同事的代码""" global latest_data logger.info("Received message") try: logger.info(f"Received message on topic: {message.topic}") data = json.loads(message.payload) logger.debug(f"Message content: {data}") global latest_data 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") latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) except Exception as e: logger.error(f"Error parsing MQTT message: {e}")
def on_disconnect(client, userdata, rc): """MQTT断开连接回调""" logger.warning(f"Disconnected from MQTT broker with code: {rc}")def get_data(serial=DEFAULT_SERIAL): """获取打印机状态数据 - 使用同事的代码""" global client, response_topic, latest_data global latest_data latest_data["status"] = "Disconnected" latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S") logger.info(f"Requesting data for printer {serial}") if rc != 0: logger.warning("Unexpected disconnection. Attempting to reconnect...") try: create_client(HOST, PORT, USERNAME, PASSWORD) except Exception as e: logger.error(f"Failed to reconnect: {e}")
def get_data(serial=DEFAULT_SERIAL): """获取打印机状态数据""" logger.info("Requesting printer data") try: global client if client is None or not client.is_connected(): logger.warning("MQTT client not connected. Attempting to connect...") create_client(HOST, PORT, USERNAME, PASSWORD) if client is None: logger.info("Creating new MQTT client") create_client(HOST, PORT, USERNAME, PASSWORD)
request_topic = f"bambu_a1_mini/request/{serial}" response_topic = f"bambu_a1_mini/response/{serial}" logger.info(f"Subscribing to {response_topic}") if client and client.is_connected(): client.subscribe(response_topic) # 发送请求 logger.info(f"Sending data request to {request_topic}") client.publish(request_topic, json.dumps("HI")) return ( latest_data["status"], latest_data["bed_temperature"], latest_data["nozzle_temperature"], latest_data["update_time"] ) else: logger.error("MQTT client not available") return ("Disconnected", "N/A", "N/A", "MQTT not connected") except Exception as e: logger.error(f"Error in get_data: {e}") return (f"Error: {str(e)}", "N/A", "N/A", time.strftime("%Y-%m-%d %H:%M:%S")) request_topic = f"bambu_a1_mini/request/{serial}" response_topic = f"bambu_a1_mini/response/{serial}" logger.info(f"Subscribing to {response_topic}") client.subscribe(response_topic) # 发送请求获取数据 logger.info(f"Publishing request to {request_topic}") client.publish(request_topic, json.dumps("HI")) # 等待数据更新 latest_data["bed_temperature"] = "N/A" timeout = 10 logger.info("Waiting for response...") while latest_data["bed_temperature"] == "N/A" and timeout > 0: time.sleep(1) timeout -= 1 logger.debug(f"Waiting... {timeout} seconds left") if timeout <= 0: logger.warning("Timeout waiting for response") return ("Disconnected", "N/A", "N/A", "Timeout waiting for response") logger.info(f"Got response: {latest_data}") return ( 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, serial=DEFAULT_SERIAL):def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed): """发送打印参数到打印机""" serial = DEFAULT_SERIAL # 使用默认序列号 logger.info(f"Sending parameters to {serial}: nozzle={nozzle_temp}, bed={bed_temp}, speed={print_speed}, fan={fan_speed}") try: params = {5 unmodified lines request_topic = f"bambu_a1_mini/request/{serial}" if client and client.is_connected(): if client: client.publish(request_topic, json.dumps({ 'command': 'set_parameters', 'parameters': params46 unmodified lines status = { "app": "running", "time": time.strftime("%Y-%m-%d %H:%M:%S"), "mqtt_connected": client is not None and client.is_connected() if client else False, "mqtt_connected": client is not None, "latest_update": latest_data["update_time"] } logger.info(f"Health check: {status}") return status
# API端点函数def api_get_status(serial=DEFAULT_SERIAL):def api_get_data(): """API端点:获取状态""" logger.info(f"API call: get_status for {serial}") logger.info("API call: get_data") try: return get_data(serial) return get_data() except Exception as e: logger.error(f"Error in api_get_status: {e}") logger.error(f"Error in api_get_data: {e}") return ("Error", "N/A", "N/A", str(e))
def api_get_image():def api_capture_frame(img=None): """API端点:获取图像""" logger.info("API call: get_image") logger.info("API call: capture_frame") try: img = capture_image() return get_image_base64(img) return img except Exception as e: logger.error(f"Error in api_get_image: {e}") logger.error(f"Error in api_capture_frame: {e}") return None
def api_send_parameters(params): """API端点:发送参数""" logger.info(f"API call: send_parameters with {params}")def api_lambda(img=None, param_1=200, param_2=60, param_3=60, param_4=100): """API端点:分析图像""" logger.info("API call: lambda") try: serial = params.get('serial', DEFAULT_SERIAL) return send_print_parameters( params.get('nozzle_temp', 200), params.get('bed_temp', 60), params.get('print_speed', 60), params.get('fan_speed', 100), serial # 这里应该是实际的图像分析代码 # 目前返回占位数据 return ( img, # 分析结果图像 0.05, # missing_rate 0.03, # excess_rate 0.02, # stringing_rate 0.9, # uniformity_score 0.85, # print_quality_score 0.7, # print_speed_score 0.8, # material_efficiency_score 0.8, # total_performance_score latest_data["status"] # printer_status ) except Exception as e: logger.error(f"Error in api_send_parameters: {e}") return f"Error: {str(e)}" logger.error(f"Error in api_lambda: {e}") return None
def api_health_check(): """API端点:健康检查""" logger.info("API call: health_check")def api_send_print_parameters(nozzle_temp=200, bed_temp=60, print_speed=60, fan_speed=100): """API端点:发送打印参数""" logger.info(f"API call: send_print_parameters with nozzle={nozzle_temp}, bed={bed_temp}, speed={print_speed}, fan={fan_speed}") try: return health_check() return send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed) except Exception as e: logger.error(f"Error in api_health_check: {e}") return {"status": "error", "error": str(e)}
# 初始化MQTT客户端try: logger.info("Initializing MQTT client") mqtt_connected = create_client(HOST, PORT, USERNAME, PASSWORD) if not mqtt_connected: logger.warning("Starting without MQTT connection")except Exception as e: logger.error(f"Failed to initialize MQTT: {e}") logger.warning("Starting without MQTT connection") logger.error(f"Error in api_send_print_parameters: {e}") return f"Error: {str(e)}"
# 创建主界面with gr.Blocks(title="Bambu A1 Mini Print Control") as demo: gr.Markdown("# Bambu A1 Mini Print Control") with gr.Row(): serial = gr.Textbox(DEFAULT_SERIAL, label="Serial Number") refresh_btn = gr.Button("Refresh Status") with gr.Row():19 unmodified lines # 连接按钮 refresh_btn.click( fn=get_data, inputs=[serial], outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update] ) 4 unmodified lines send_params_btn.click( fn=send_print_parameters, inputs=[nozzle_temp, bed_temp, print_speed, fan_speed, serial], inputs=[nozzle_temp, bed_temp, print_speed, fan_speed], outputs=[current_status] )
# 创建API端点with gr.Blocks() as api_blocks: gr.Interface( fn=api_get_status, inputs=gr.Textbox(value=DEFAULT_SERIAL, label="Serial Number"), outputs="json", title="Get Printer Status", description="Get the current status of the printer" ) gr.Interface( fn=api_get_image, inputs=None, outputs="json", title="Get Print Image", description="Get the current print image as base64" ) gr.Interface( fn=api_send_parameters, inputs="json", outputs="text", title="Send Print Parameters", description="Send parameters to the printer" ) gr.Interface( fn=api_health_check, inputs=None, outputs="json", title="Health Check", description="Check the health of the application" )
# 自动刷新线程def auto_refresh(): """自动刷新状态的后台线程"""2 unmodified lines try: time.sleep(5) logger.debug("Auto-refreshing printer status") status, bed_temp, nozzle_temp, update_time = get_data(DEFAULT_SERIAL) status, bed_temp, nozzle_temp, update_time = get_data() # 更新UI current_status.update(value=status)9 unmodified lines# 启动应用if __name__ == "__main__": logger.info("Starting Bambu A1 Mini Print Control application") # 启动主界面 demo.queue().launch(show_error=True) # 启动API端点 # 注意:在实际部署中,这些API端点应该与主界面集成在一起 # 这里分开只是为了演示目的 # 定义API端点 demo.queue() # 添加API端点 demo.launch( show_error=True, share=False, server_name="0.0.0.0", server_port=7860 )app.py+103-163