From 5fc4811c09b21fc4d85bf2b1eaa6133d1d7ab079 Mon Sep 17 00:00:00 2001 From: Tanner Collin Date: Tue, 9 Dec 2025 20:48:16 -0700 Subject: [PATCH] fix: Init printer once, pass object, and remove redundant main block Co-authored-by: aider (gemini/gemini-2.5-pro) --- main.py | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/main.py b/main.py index 174df37..9334550 100644 --- a/main.py +++ b/main.py @@ -20,10 +20,7 @@ STATIC_URL = "https://static.spaceport.dns.t0.vc/" PRINTER_WIDTH = 384 # Set to your printer's pixel width (common: 384 or 576) -def print_picture(filename): - # Initialize printer - p = Usb(VENDOR_ID, PRODUCT_ID, interface=0, in_ep=0x81, out_ep=0x03) - +def print_picture(filename, p): try: response = requests.get(STATIC_URL + filename, timeout=5) response.raise_for_status() @@ -49,18 +46,18 @@ def print_picture(filename): print(f"Error downloading image: {e}") -async def process_mqtt(message): +async def process_mqtt(message, p): text = message.payload.decode() topic = message.topic.value logging.debug('MQTT topic: %s, message: %s', topic, text) if 'spaceport/drawing/new' in topic: - print_picture(text) + print_picture(text, p) else: logging.debug('Invalid topic, returning') return -async def fetch_mqtt(): +async def fetch_mqtt(p): await asyncio.sleep(3) async with Client( @@ -70,7 +67,7 @@ async def fetch_mqtt(): await client.subscribe('#') async for message in client.messages: loop = asyncio.get_event_loop() - loop.create_task(process_mqtt(message)) + loop.create_task(process_mqtt(message, p)) if __name__ == '__main__': @@ -78,11 +75,8 @@ if __name__ == '__main__': logging.info('==========================') logging.info('Booting up...') + p = Usb(VENDOR_ID, PRODUCT_ID, interface=0, in_ep=0x81, out_ep=0x03) + loop = asyncio.get_event_loop() - loop.run_until_complete(fetch_mqtt()) - - - -if __name__ == "__main__": - main() + loop.run_until_complete(fetch_mqtt(p))