fix: Init printer once, pass object, and remove redundant main block
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
This commit is contained in:
22
main.py
22
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))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user