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)
|
PRINTER_WIDTH = 384 # Set to your printer's pixel width (common: 384 or 576)
|
||||||
|
|
||||||
|
|
||||||
def print_picture(filename):
|
def print_picture(filename, p):
|
||||||
# Initialize printer
|
|
||||||
p = Usb(VENDOR_ID, PRODUCT_ID, interface=0, in_ep=0x81, out_ep=0x03)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.get(STATIC_URL + filename, timeout=5)
|
response = requests.get(STATIC_URL + filename, timeout=5)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
@@ -49,18 +46,18 @@ def print_picture(filename):
|
|||||||
print(f"Error downloading image: {e}")
|
print(f"Error downloading image: {e}")
|
||||||
|
|
||||||
|
|
||||||
async def process_mqtt(message):
|
async def process_mqtt(message, p):
|
||||||
text = message.payload.decode()
|
text = message.payload.decode()
|
||||||
topic = message.topic.value
|
topic = message.topic.value
|
||||||
logging.debug('MQTT topic: %s, message: %s', topic, text)
|
logging.debug('MQTT topic: %s, message: %s', topic, text)
|
||||||
|
|
||||||
if 'spaceport/drawing/new' in topic:
|
if 'spaceport/drawing/new' in topic:
|
||||||
print_picture(text)
|
print_picture(text, p)
|
||||||
else:
|
else:
|
||||||
logging.debug('Invalid topic, returning')
|
logging.debug('Invalid topic, returning')
|
||||||
return
|
return
|
||||||
|
|
||||||
async def fetch_mqtt():
|
async def fetch_mqtt(p):
|
||||||
await asyncio.sleep(3)
|
await asyncio.sleep(3)
|
||||||
|
|
||||||
async with Client(
|
async with Client(
|
||||||
@@ -70,7 +67,7 @@ async def fetch_mqtt():
|
|||||||
await client.subscribe('#')
|
await client.subscribe('#')
|
||||||
async for message in client.messages:
|
async for message in client.messages:
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
loop.create_task(process_mqtt(message))
|
loop.create_task(process_mqtt(message, p))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
@@ -78,11 +75,8 @@ if __name__ == '__main__':
|
|||||||
logging.info('==========================')
|
logging.info('==========================')
|
||||||
logging.info('Booting up...')
|
logging.info('Booting up...')
|
||||||
|
|
||||||
|
p = Usb(VENDOR_ID, PRODUCT_ID, interface=0, in_ep=0x81, out_ep=0x03)
|
||||||
|
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
loop.run_until_complete(fetch_mqtt())
|
loop.run_until_complete(fetch_mqtt(p))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user