A repository for MicroPython code that communicates with and relays information from the Texas Instruments TMP117/119 temperature sensor.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.7 KiB

2 months ago
  1. import ntptime
  2. import asyncio
  3. from lib.mqtt_as import MQTTClient
  4. from lib.topic_message import TopicMessage, TMQueue
  5. async def mqtt_up(
  6. mqtt_client: MQTTClient,
  7. inbound_topic,
  8. todo):
  9. """
  10. Perform asynchronous "todo" when MQTT client is connected.
  11. """
  12. while True:
  13. await mqtt_client.up.wait() # type: ignore
  14. mqtt_client.up.clear()
  15. await mqtt_client.subscribe(inbound_topic)
  16. await todo()
  17. async def mqtt_down(
  18. mqtt_client: MQTTClient,
  19. todo):
  20. """
  21. Perform asynchronous "todo" when MQTT client is disconnected.
  22. """
  23. while True:
  24. await mqtt_client.down.wait() # type: ignore
  25. mqtt_client.down.clear()
  26. await todo()
  27. async def wireless_sync_clock(
  28. mqtt_client: MQTTClient,
  29. interval_s):
  30. """Sync clock via NTP server"""
  31. while True:
  32. ntptime.settime()
  33. await asyncio.sleep(interval_s)
  34. async def mqtt_publish_tmsgs(
  35. mqtt_client: MQTTClient,
  36. outbound_queue: TMQueue,
  37. post_interval: float | int):
  38. """Publishes all TopicMessage items in queue over MQTT"""
  39. while True:
  40. while not outbound_queue.is_empty():
  41. item = outbound_queue.get()
  42. await mqtt_client.publish(item.topic, item.message, qos=1)
  43. await asyncio.sleep(post_interval)
  44. async def mqtt_message_parser(
  45. mqtt_client: MQTTClient,
  46. inbound_queue: TMQueue):
  47. """Parse messages recieved by MQTT client and add them to the inbound queue"""
  48. async for topic, message, retained in mqtt_client.queue: # type: ignore
  49. topic = topic.decode()
  50. message = message.decode()
  51. inbound_queue.add(TopicMessage(topic, message))