Update app.py
Browse files46 unmodified lines474849505152535441 unmodified lines96979897991009910110210110210310410510610710810911011111211311411511611711811912012112212312412512612712810412913013113213313413513613713813914014114214314414514614714814927 unmodified lines1771781791381801811821831841421851861871881891901914 unmodified lines1961971981541551992002011572022031591602042052062072082092102112122131 unmodified line21521621721821922022122222322422522614 unmodified lines24124224318818919019119219319419519619719819920020120220320420520620720820921021124424521324624724824925025125225325425525621521625725825926026148 unmodified lines31031131231331431531631731831932032132232332432532640 unmodified lines367368369317370371372373239 unmodified lines61361461561661761861962062162262362462562662762862963063163263363463563663763863911 unmodified lines65165265358065446 unmodified lines "status": "N/A", "update_time": "Waiting for data...", "image_url": "N/A", "progress": 0, "message": "", }
bambu_client = None41 unmodified lines logger.error(f"Error parsing MQTT message: {e}")
def rpi_on_message(client, userdata, message):def rpi_on_message(client, userdata, msg): global latest_data logger.info("Received message") try: data = json.loads(message.payload) latest_data["image_url"] = data.get("image_url", "N/A") 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"] = status latest_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"] = 0 latest_data["message"] = "Printer ready" elif status == "Processing": latest_data["progress"] = 25 latest_data["message"] = "Processing G-code..." except Exception as e: logger.error(f"Error parsing MQTT message: {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"] = status if "command" in result and 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}") except Exception as e: logger.error(f"Error processing RPI message: {e}")
def get_data(serial=DEFAULT_SERIAL):27 unmodified lines
def send_print_parameters(nozzle_temp, bed_temp, print_speed, fan_speed): global bambu_client global rpi_client
serial = DEFAULT_SERIAL
logger.info( f"Sending parameters to {serial}: nozzle={nozzle_temp}, bed={bed_temp}, speed={print_speed}, fan={fan_speed}" 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,4 unmodified lines
request_topic = f"bambu_a1_mini/request/{serial}"
if bambu_client: bambu_client.publish( if rpi_client: rpi_client.publish( request_topic, json.dumps({"command": "set_parameters", "parameters": params}), json.dumps({"command": "generate_gcode", "parameters": params}), ) logger.info("Parameters sent successfully") return "Parameters sent successfully" logger.info("Parameters sent successfully to RPi for G-code generation") global latest_data latest_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"1 unmodified line logger.error(f"Error sending parameters: {e}") return f"Error sending parameters: {e}"
latest_data["status"] = "Sending" latest_data["progress"] = 10 latest_data["message"] = "Sending parameters to printer..."
def get_image_base64(image): if image is None:14 unmodified lines return None
def get_test_image(image_name=None): test_dir = os.path.join(os.path.dirname(__file__), "test_images")
if not os.path.exists(test_dir): logger.error(f"Test images directory not found: {test_dir}") return None
image_files = [ f for f in os.listdir(test_dir) if f.lower().endswith((".png", ".jpg", ".jpeg", ".bmp")) ]
if not image_files: logger.error("No test images found") return None
if image_name and image_name in image_files: image_path = os.path.join(test_dir, image_name) else: image_path = os.path.join(test_dir, random.choice(image_files))
logger.info(f"Using test image: {image_path}")
def handle_auto_capture(message): try: return Image.open(image_path) 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"] = True latest_data["last_capture_job"] = print_job latest_data["last_capture_time"] = timestamp return capture_image() except Exception as e: logger.error(f"Failed to open test image: {e}") return None logger.error(f"error: {e}") return None, f"capture failed: {str(e)}"
def capture_image(url=None, use_test_image=False, test_image_name=None):48 unmodified lines else: raise Exception("url is 'N/A'")
def update_print_status(): global latest_data return ( 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 = {40 unmodified lines <div style="position: relative; width: 100%; padding-top: 56.25%;"> <iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" src="https://www.youtube.com/embed/XoYGeFxKpH0" src="https://www.youtube.com/embed/x8Iii1cKWB8" title="Bambu A1mini Livestream" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 239 unmodified lines 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")
11 unmodified lines
demo.queue().launch( show_error=True, share=False, server_name="0.0.0.0", server_port=7860 ) )app.py+115-41