-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmqtt_ds18b20_read_temp_publish.py
More file actions
67 lines (58 loc) · 2 KB
/
mqtt_ds18b20_read_temp_publish.py
File metadata and controls
67 lines (58 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Lecture des informations de capteurs de temperature DS18B20
et envoi vers un broker mqtt
# use case: python3 mqtt_ds18b20_read_temp_publish.py
"""
import time
import sys
import os
from mymqtt import myMqtt
from paho.mqtt import client as mqtt_client
client_id="ds18_mqtt"
broker="127.0.01"
port = 1883
mqttc = myMqtt(client_id)
ymdhms = mqttc.yyyymmddhhmmss()
w1_dir = "/sys/bus/w1/devices/"
item = "temperature"
item_values={}
sensors = os.listdir(f"{w1_dir}")
nb_sensors = 0
for id in sensors:
if "28-" in id:
print(f"Existing ds18b20 sensor: {w1_dir}{id}")
item_values[id]=""
nb_sensors += 1
mqttc.connect_to(broker, port, publisher=True)
mqttc.log.info(f"time/{client_id}/start/loop")
if nb_sensors == 0:
mqttc.publish(topic=f"time/{client_id}/end/loop", msg="No sensor, leaving")
mqttc.publish(topic=f"time/{client_id}/end/loop", msg=ymdhms)
mqttc.log.info(f"time/{client_id}/end/loop")
mqttc.disconnect()
exit()
else:
mqttc.publish(topic=f"time/{client_id}/start/loop", msg=ymdhms)
try:
while True:
for id in sensors:
if "28-" in id:
ds18b20_file = open(f"/sys/bus/w1/devices/{id}/{item}", "r")
file_content = ds18b20_file.read()
ds18b20_file.close()
for line in file_content.split("\n"):
if len(line) > 0:
value = line
if item == "temperature":
# Temperature values are in 1/1000 °C
value_int = int(value)
value = str(value_int/1000)
if value != item_values[id]:
print(f"topic=ds28b20/{id}/{item} msg={value}")
mqttc.publish(topic=f"ds28b20/{id}/{item}", msg=value, retain=True)
item_values[id] = value
time.sleep(5)
except KeyboardInterrupt:
ser.close()