update
Browse files32 unmodified lines333435363738394041424344454665 unmodified lines11211311411511611711811912012112212312412512612712812942 unmodified lines17217317417517617717817932 unmodified lines)logger = logging.getLogger(__name__)# Global variables to store received datalatest_data = {"bed_temperature": "N/A","nozzle_temperature": "N/A","status": "N/A","update_time": "Waiting for data...","current_image_url": None,"print_progress": 0}# Initialize analysis components65 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_data42 unmodified linesexcept Exception as e:return f"Error sending parameters: {e}"# Initialize MQTT clientmqtt_client = create_client(HOST, PORT, USERNAME, PASSWORD)def update_printer_status():"""Get current printer status"""32 unmodified lines3334353637383940414243444565 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217342 unmodified lines21621721821922022122222322422522622722832 unmodified lines)logger = logging.getLogger(__name__)# Global variablesclient = Nonelatest_data = {"bed_temperature": "N/A","nozzle_temperature": "N/A","status": "Disconnected","update_time": "Not connected"}# Initialize analysis components65 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:# Create new clientclient = 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_disconnect# Try to connectprint(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) # Wait before retryprint("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")serial = os.getenv("PRINTER_SERIAL", "0309CA471800852")response_topic = f"bambu_a1_mini/response/{serial}"client.subscribe(response_topic)print(f"Subscribed to {response_topic}")# 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_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 on_message(client, userdata, message):global latest_data42 unmodified linesexcept Exception as e:return f"Error sending parameters: {e}"# Initialize MQTT client (but don't fail if it doesn't connect)try: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_printer_status():"""Get current printer status"""
app.py+65-16