Skip to content

Instantly share code, notes, and snippets.

@derme302
Created August 10, 2023 03:48
Show Gist options
  • Save derme302/7385a4e8fed328f3f32a9250afd0c680 to your computer and use it in GitHub Desktop.
Save derme302/7385a4e8fed328f3f32a9250afd0c680 to your computer and use it in GitHub Desktop.
import glob
import time
import paho.mqtt.publish as mqtt
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
with open(device_file, 'r') as f:
lines = f.readlines()
return lines
def read_temp(celsius=True):
lines = read_temp_raw()
while True:
if lines != []:
if lines[0].strip()[-3:] == 'YES':
break
else:
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_float = float(temp_string) / 1000.0
if (celsius):
temp_c = round(temp_float, 2)
return temp_c
else:
temp_f = temp_float * 9.0 / 5.0 + 32.0
return temp_f
def mqtt_thermometre(host, topic):
temp = read_temp()
mqtt.single(topic, payload=temp, hostname=host)
if __name__ == "__main__":
while True:
mqtt_thermometre("home/fish_temp", "192.168.1.2")
time.sleep(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment