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.

temp_sensor.py 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import paho.mqtt.client as mqtt
  2. import queue
  3. import time
  4. from w1thermsensor import W1ThermSensor
  5. sensors = {
  6. '0517021db9ff': 'rack_ceiling',
  7. '0517022f8eff': 'rack_back',
  8. '0416a02b0eff': 'rack_front',
  9. '051702869eff': 'rack_floor'
  10. }
  11. msgs = queue.Queue()
  12. temps = []
  13. available = []
  14. def on_connect(client, userdata, flags, rc):
  15. print("Connected with result code " + str(rc))
  16. #client.subscribe(cfg.mqtt['prefix'] + "/pdu/outlet/+/+")
  17. if rc==0:
  18. client.connected_flag=True
  19. client.publish("$CONNECTED/rack-temp", 1, retain=True)
  20. else:
  21. client.bad_connection_flag=True
  22. def add_msg_to_queue(topic, payload):
  23. msg = {
  24. 'topic': 'sensor/office/temp/{}'.format(topic),
  25. 'payload': "{:.2f}".format(payload),
  26. 'qos': 0,
  27. 'retain': False
  28. }
  29. msgs.put(msg)
  30. print(msg)
  31. def set_sensor_status():
  32. for uuid, sensor in sensors.items():
  33. msg = {
  34. 'topic': 'sensor/office/temp/{}/status'.format(sensor),
  35. 'payload': 'online' if sensor in available else 'offline',
  36. 'qos': 0,
  37. 'retain': False
  38. }
  39. msgs.put(msg)
  40. print(msg)
  41. client = mqtt.Client("rack-temp")
  42. client.on_connect = on_connect
  43. #client.on_message = on_message
  44. client.will_set("$CONNECTED/rack-temp", 0, qos=0, retain=True)
  45. client.connect("mqtt.lan.uctrl.net")
  46. client.loop_start()
  47. while True:
  48. for sensor in W1ThermSensor.get_available_sensors():
  49. temp = sensor.get_temperature()
  50. add_msg_to_queue(sensors[sensor.id], temp)
  51. temps.append(temp)
  52. available.append(sensors[sensor.id])
  53. average = sum(temps)/len(temps)
  54. set_sensor_status()
  55. add_msg_to_queue('average', average)
  56. while not msgs.empty():
  57. client.publish(**msgs.get())
  58. temps.clear()
  59. available.clear()
  60. time.sleep(15)