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.

69 lines
2.3 KiB

2 months ago
2 months ago
  1. import time
  2. import asyncio
  3. import json
  4. from lib.topic_message import TopicMessage, TMQueue
  5. from lib.TMP117 import TMP117
  6. async def measure_sensors(
  7. sensors: list[TMP117],
  8. interval_s: float | int,
  9. microcontroller_id: int,
  10. message_queue: TMQueue,
  11. temperature_topic: str):
  12. """
  13. Readout configuration of all sensors, then timestamp, temperature of all sensors. Adds data to message_queue. Performs every interval_s, correcting for execution time.
  14. """
  15. next_time = time.ticks_us()
  16. while True:
  17. # Initialise
  18. temperatures = []
  19. timestamps = []
  20. configs = []
  21. # Readout configuration of sensors pre-temperature measurement
  22. for sensor in sensors:
  23. try:
  24. configs.append(sensor.read_configuration_integer())
  25. except OSError as E:
  26. print(f"ERROR: Sensor {sensor.name}, {E}")
  27. configs.append(None)
  28. # Read time and temperature
  29. for sensor in sensors:
  30. try:
  31. temperatures.append(sensor.read_temperature())
  32. except OSError as E:
  33. print(f"ERROR: Sensor {sensor.name}, {E}")
  34. temperatures.append(None)
  35. timestamps.append(time.time_ns())
  36. # Package into message
  37. for i in range(len(sensors)):
  38. message = json.dumps({
  39. "micro": microcontroller_id,
  40. "sensor": sensors[i].name,
  41. "temperature": temperatures[i],
  42. "time": timestamps[i],
  43. "config": configs[i]
  44. })
  45. x = TopicMessage(temperature_topic, message)
  46. message_queue.add(x)
  47. # Calculate time to sleep
  48. next_time = time.ticks_add(next_time, int(interval_s*1000000))
  49. sleep_time = time.ticks_diff(next_time, time.ticks_us())/1e6
  50. await asyncio.sleep(sleep_time)
  51. async def switch_inbound_message_queue(inbound_queue: TMQueue, interval_s):
  52. """Checks inbound queue and decides what to do with the messages"""
  53. while True:
  54. # Iterate through all inbound messages and execute relevant task.
  55. while not inbound_queue.is_empty():
  56. tmsg = inbound_queue.get()
  57. topic = tmsg.topic
  58. message = tmsg.message
  59. pass
  60. await asyncio.sleep(interval_s)