Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. from __future__ import print_function
  2.  
  3. import os
  4. import time
  5.  
  6. import paho.mqtt.client as mqtt
  7. from paho.mqtt.client import MQTT_ERR_SUCCESS, MQTT_ERR_NO_CONN
  8.  
  9.  
  10. DEVICES_PATH = "/sys/bus/w1/devices"
  11. MQTT_HOST = "localhost"
  12. MQTT_PORT = 1883
  13. SLEEP_TIME = 30
  14.  
  15.  
  16. def connect_mqtt():
  17. mqttc = mqtt.Client()
  18. print("Connecting to {}".format(MQTT_HOST))
  19. mqttc.connect(MQTT_HOST, MQTT_PORT, 60)
  20. print("Connected")
  21. mqttc.loop_start()
  22. mqttc.on_disconnect = on_disconnect
  23. return mqttc
  24.  
  25.  
  26. def disconnect_mqtt(mqttc):
  27. mqttc.loop_stop()
  28. mqttc.disconnect()
  29.  
  30.  
  31. def on_disconnect(client, userdata, rc):
  32. if rc != 0:
  33. print("Unexpected disconnection.")
  34. client.reconnect()
  35.  
  36.  
  37. def get_thermometer_names():
  38. thermometers = [x[1] for x in os.walk(DEVICES_PATH)][0]
  39. while "w1_bus_master1" in thermometers: thermometers.remove("w1_bus_master1")
  40. return thermometers
  41.  
  42.  
  43. def get_thermometer_temp(thermometer):
  44. with open("{}/{}/w1_slave".format(DEVICES_PATH, thermometer), "r") as tfile:
  45. text = tfile.read()
  46. secondline = text.split("\n")[1]
  47. temperaturedata = secondline.split(" ")[9]
  48. temperature = float(temperaturedata[2:])
  49. temperature = temperature / 1000
  50. return temperature
  51.  
  52.  
  53. def publish_temp(mqttc, thermometer, temp):
  54. topic = "raspberry-pi/w1/thermometer/{}".format(thermometer)
  55. (result, mid) = mqttc.publish(topic, temp)
  56. if result == MQTT_ERR_SUCCESS:
  57. print("Published {} to {}".format(temp, topic))
  58. elif result == MQTT_ERR_NO_CONN:
  59. print("Connection error")
  60. else:
  61. print("Unknown error")
  62.  
  63.  
  64. def main():
  65. print("Starting")
  66. try:
  67. mqttc = connect_mqtt()
  68. thermometers = get_thermometer_names()
  69. print("Detected {} thermometers".format(len(thermometers)))
  70. while True:
  71. for thermometer in thermometers:
  72. temp = get_thermometer_temp(thermometer)
  73. publish_temp(mqttc, thermometer, temp)
  74. time.sleep(SLEEP_TIME)
  75. except KeyboardInterrupt:
  76. print("Exiting")
  77. finally:
  78. print("Disconnecting from {}".format(MQTT_HOST))
  79. disconnect_mqtt(mqttc)
  80. print("Done")
  81.  
  82.  
  83. if __name__ == "__main__":
  84. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement