Skip to content

Instantly share code, notes, and snippets.

@jacobtomlinson
Created March 29, 2017 07:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jacobtomlinson/5cf933331fdda96212092f54f441b573 to your computer and use it in GitHub Desktop.
Save jacobtomlinson/5cf933331fdda96212092f54f441b573 to your computer and use it in GitHub Desktop.
Send 1-wire temperature values from a Raspberry Pi to an MQTT broker
from __future__ import print_function
import os
import time
import paho.mqtt.client as mqtt
from paho.mqtt.client import MQTT_ERR_SUCCESS, MQTT_ERR_NO_CONN
DEVICES_PATH = "/sys/bus/w1/devices"
MQTT_HOST = "localhost"
MQTT_PORT = 1883
SLEEP_TIME = 30
def connect_mqtt():
mqttc = mqtt.Client()
print("Connecting to {}".format(MQTT_HOST))
mqttc.connect(MQTT_HOST, MQTT_PORT, 60)
print("Connected")
mqttc.loop_start()
mqttc.on_disconnect = on_disconnect
return mqttc
def disconnect_mqtt(mqttc):
mqttc.loop_stop()
mqttc.disconnect()
def on_disconnect(client, userdata, rc):
if rc != 0:
print("Unexpected disconnection.")
client.reconnect()
def get_thermometer_names():
thermometers = [x[1] for x in os.walk(DEVICES_PATH)][0]
while "w1_bus_master1" in thermometers: thermometers.remove("w1_bus_master1")
return thermometers
def get_thermometer_temp(thermometer):
with open("{}/{}/w1_slave".format(DEVICES_PATH, thermometer), "r") as tfile:
text = tfile.read()
secondline = text.split("\n")[1]
temperaturedata = secondline.split(" ")[9]
temperature = float(temperaturedata[2:])
temperature = temperature / 1000
return temperature
def publish_temp(mqttc, thermometer, temp):
topic = "raspberry-pi/w1/thermometer/{}".format(thermometer)
(result, mid) = mqttc.publish(topic, temp)
if result == MQTT_ERR_SUCCESS:
print("Published {} to {}".format(temp, topic))
elif result == MQTT_ERR_NO_CONN:
print("Connection error")
else:
print("Unknown error")
def main():
print("Starting")
try:
mqttc = connect_mqtt()
thermometers = get_thermometer_names()
print("Detected {} thermometers".format(len(thermometers)))
while True:
for thermometer in thermometers:
temp = get_thermometer_temp(thermometer)
publish_temp(mqttc, thermometer, temp)
time.sleep(SLEEP_TIME)
except KeyboardInterrupt:
print("Exiting")
finally:
print("Disconnecting from {}".format(MQTT_HOST))
disconnect_mqtt(mqttc)
print("Done")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment