update
Browse files21 unmodified lines2223242526272829303132333435363738394041424344452 unmodified lines484950515253544 unmodified lines59606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521535 unmodified lines15916016116216316416546 unmodified lines21221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328419 unmodified lines3043053063073083093104 unmodified lines3153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573582 unmodified lines3613623633643653663679 unmodified lines37737837938038138238338438521 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")DEFAULT_SERIAL = "0309CA471800852"# Global variablesclient = Nonelatest_data = {"bed_temperature": "N/A","nozzle_temperature": "N/A","status": "N/A","update_time": "Waiting for data..."}def create_client(host, port, username, password):"""创建并配置MQTT客户端"""global clienttry:logger.info(f"Creating MQTT client for {host}:{port}")2 unmodified linesclient.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)client.on_connect = on_connectclient.on_message = on_messageclient.on_disconnect = on_disconnectlogger.info("Connecting to MQTT broker...")client.connect(host, port)4 unmodified linesreturn Falsedef on_connect(client, userdata, flags, rc):"""MQTT连接回调"""if rc == 0:logger.info("Successfully connected to MQTT broker")serial = DEFAULT_SERIALresponse_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_datalatest_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}")def on_message(client, userdata, message):"""MQTT消息回调"""try:logger.info(f"Received message on topic: {message.topic}")data = json.loads(message.payload)logger.debug(f"Message content: {data}")global latest_datalatest_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: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}")global latest_datalatest_data["status"] = "Disconnected"latest_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S")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 clientif client is None or not client.is_connected():logger.warning("MQTT client not connected. Attempting to connect...")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"))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 linesrequest_topic = f"bambu_a1_mini/request/{serial}"if client and client.is_connected():client.publish(request_topic, json.dumps({'command': 'set_parameters','parameters': params46 unmodified linesstatus = {"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,"latest_update": latest_data["update_time"]}logger.info(f"Health check: {status}")return status# API端点函数def api_get_status(serial=DEFAULT_SERIAL):"""API端点:获取状态"""logger.info(f"API call: get_status for {serial}")try:return get_data(serial)except Exception as e:logger.error(f"Error in api_get_status: {e}")return ("Error", "N/A", "N/A", str(e))def api_get_image():"""API端点:获取图像"""logger.info("API call: get_image")try:img = capture_image()return get_image_base64(img)except Exception as e:logger.error(f"Error in api_get_image: {e}")return Nonedef api_send_parameters(params):"""API端点:发送参数"""logger.info(f"API call: send_parameters with {params}")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)except Exception as e:logger.error(f"Error in api_send_parameters: {e}")return f"Error: {str(e)}"def api_health_check():"""API端点:健康检查"""logger.info("API call: health_check")try:return health_check()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")# 创建主界面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 linessend_params_btn.click(fn=send_print_parameters,inputs=[nozzle_temp, bed_temp, print_speed, fan_speed, serial],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 linestry:time.sleep(5)logger.debug("Auto-refreshing printer status")status, bed_temp, nozzle_temp, update_time = get_data(DEFAULT_SERIAL)# 更新UIcurrent_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端点应该与主界面集成在一起# 这里分开只是为了演示目的21 unmodified lines2223242526272829303132333435363738394041424344454647482 unmodified lines5152535455564 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271285 unmodified lines13413513613713813914046 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325419 unmodified lines2742752762772782794 unmodified lines2842852862872882892902912922932 unmodified lines2962972982993003013029 unmodified lines31231331431531631731831932032132232332432521 unmodified lines)logger = logging.getLogger("bambu-analysis")# Environment Variables - 使用同事的配置方式HOST = "mqtt.bambulab.com"PORT = 8883USERNAME = "bblp"PASSWORD = "bblp"DEFAULT_SERIAL = "0309CA471800852"# Global variables to store received data - 完全保持同事的数据结构latest_data = {"bed_temperature": "N/A","nozzle_temperature": "N/A","status": "N/A","update_time": "Waiting for data...",}# MQTT Client setup - 完全保持同事的客户端设置client = Noneresponse_topic = None # Will be set dynamicallydef create_client(host, port, username, password):"""创建并配置MQTT客户端 - 使用同事的代码"""global clienttry:logger.info(f"Creating MQTT client for {host}:{port}")2 unmodified linesclient.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)client.on_connect = on_connectclient.on_message = on_messagelogger.info("Connecting to MQTT broker...")client.connect(host, port)4 unmodified linesreturn Falsedef on_connect(client, userdata, flags, rc):"""MQTT连接回调 - 使用同事的代码"""logger.info(f"Connected with result code {rc}")def on_message(client, userdata, message):"""MQTT消息回调 - 使用同事的代码"""global latest_datalogger.info("Received message")try:data = json.loads(message.payload)logger.debug(f"Message content: {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", time.localtime())except Exception as e:logger.error(f"Error parsing MQTT message: {e}")def get_data(serial=DEFAULT_SERIAL):"""获取打印机状态数据 - 使用同事的代码"""global client, response_topic, latest_datalogger.info(f"Requesting data for printer {serial}")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}")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 = 10logger.info("Waiting for response...")while latest_data["bed_temperature"] == "N/A" and timeout > 0:time.sleep(1)timeout -= 1logger.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 # 使用默认序列号logger.info(f"Sending parameters to {serial}: nozzle={nozzle_temp}, bed={bed_temp}, speed={print_speed}, fan={fan_speed}")try:params = {5 unmodified linesrequest_topic = f"bambu_a1_mini/request/{serial}"if client:client.publish(request_topic, json.dumps({'command': 'set_parameters','parameters': params46 unmodified linesstatus = {"app": "running","time": time.strftime("%Y-%m-%d %H:%M:%S"),"mqtt_connected": client is not None,"latest_update": latest_data["update_time"]}logger.info(f"Health check: {status}")return status# API端点函数def api_get_data():"""API端点:获取状态"""logger.info("API call: get_data")try:return get_data()except Exception as e:logger.error(f"Error in api_get_data: {e}")return ("Error", "N/A", "N/A", str(e))def api_capture_frame(img=None):"""API端点:获取图像"""logger.info("API call: capture_frame")try:img = capture_image()return imgexcept Exception as e:logger.error(f"Error in api_capture_frame: {e}")return Nonedef api_lambda(img=None, param_1=200, param_2=60, param_3=60, param_4=100):"""API端点:分析图像"""logger.info("API call: lambda")try:# 这里应该是实际的图像分析代码# 目前返回占位数据return (img, # 分析结果图像0.05, # missing_rate0.03, # excess_rate0.02, # stringing_rate0.9, # uniformity_score0.85, # print_quality_score0.7, # print_speed_score0.8, # material_efficiency_score0.8, # total_performance_scorelatest_data["status"] # printer_status)except Exception as e:logger.error(f"Error in api_lambda: {e}")return Nonedef 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 send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed)except Exception as e: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():refresh_btn = gr.Button("Refresh Status")with gr.Row():19 unmodified lines# 连接按钮refresh_btn.click(fn=get_data,outputs=[current_status, current_bed_temp, current_nozzle_temp, last_update])4 unmodified linessend_params_btn.click(fn=send_print_parameters,inputs=[nozzle_temp, bed_temp, print_speed, fan_speed],outputs=[current_status])# 自动刷新线程def auto_refresh():"""自动刷新状态的后台线程"""2 unmodified linestry:time.sleep(5)logger.debug("Auto-refreshing printer status")status, bed_temp, nozzle_temp, update_time = get_data()# 更新UIcurrent_status.update(value=status)9 unmodified lines# 启动应用if __name__ == "__main__":logger.info("Starting Bambu A1 Mini Print Control application")# 定义API端点demo.queue()# 添加API端点demo.launch(show_error=True,share=False,server_name="0.0.0.0",server_port=7860)
app.py+103-163