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.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import time
  2. import paho.mqtt.publish as publish
  3. from w1thermsensor import W1ThermSensor
  4. sensors = {
  5. '0517021db9ff': 'rack_ceiling',
  6. '0517022f8eff': 'rack_back',
  7. '0416a02b0eff': 'rack_front',
  8. '051702869eff': 'rack_floor'
  9. }
  10. msgs = []
  11. temps = []
  12. available = []
  13. def add_msg_to_queue(topic, payload):
  14. msg = {
  15. 'topic': 'sensor/office/temp/{}'.format(topic),
  16. 'payload': "{:.2f}".format(payload),
  17. 'qos': 0,
  18. 'retain': False
  19. }
  20. msgs.append(msg)
  21. print(msg)
  22. def set_sensor_status():
  23. for uuid, sensor in sensors.items():
  24. msg = {
  25. 'topic': 'sensor/office/temp/{}/status'.format(sensor),
  26. 'payload': 'online' if sensor in available else 'offline',
  27. 'qos': 0,
  28. 'retain': False
  29. }
  30. msgs.append(msg)
  31. print(msg)
  32. while True:
  33. for sensor in W1ThermSensor.get_available_sensors():
  34. temp = sensor.get_temperature()
  35. add_msg_to_queue(sensors[sensor.id], temp)
  36. temps.append(temp)
  37. available.append(sensors[sensor.id])
  38. average = sum(temps)/len(temps)
  39. set_sensor_status()
  40. add_msg_to_queue('average', average)
  41. publish.multiple(msgs, hostname="192.168.1.119", client_id="rack_temp")
  42. temps.clear()
  43. available.clear()
  44. time.sleep(15)