Skip to content

Commit 2969448

Browse files
author
root
committed
Initial Release
1 parent 5605144 commit 2969448

File tree

2 files changed

+158
-0
lines changed

2 files changed

+158
-0
lines changed

bme280-homie.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#!/usr/bin/python3
2+
import board, busio
3+
import adafruit_bme280
4+
import paho.mqtt.client as mqtt
5+
import time, ssl, systemd.daemon
6+
7+
# set the variables
8+
broker='FQDN / IP Adresse'
9+
port=8883
10+
mqttclientid = "clientid-bme280-homie"
11+
clientid = "clientid-bme280"
12+
clientname = "Clientname BME280 Sensor"
13+
nodes="bme280"
14+
username='mosquitto'
15+
password='password'
16+
insecure=True
17+
qos=1
18+
retain_message=True
19+
# Retry to connect to mqtt broker
20+
mqttretry = 5
21+
# how often should be a publish to MQTT (in Seconds)
22+
publishtime=15
23+
24+
# do the stuff
25+
### Functions
26+
def publish(topic, payload):
27+
client.publish("homie/" + clientid + "/" + topic,payload,qos,retain_message)
28+
29+
def on_connect(client, userdata, flags, rc):
30+
print("MQTT Connection established, Returned code=",rc)
31+
# homie client config
32+
publish("$state","init")
33+
publish("$homie","4.0")
34+
publish("$name",clientname)
35+
publish("$nodes",nodes)
36+
# homie node config
37+
publish(nodes + "/$name","BME280 Sensor")
38+
publish(nodes + "/$properties","temperature,humidity,pressure")
39+
publish(nodes + "/temperature/$name","Temperature")
40+
publish(nodes + "/temperature/$unit","°C")
41+
publish(nodes + "/temperature/$datatype","float")
42+
publish(nodes + "/temperature/$settable","false")
43+
publish(nodes + "/humidity/$name","Humidity")
44+
publish(nodes + "/humidity/$unit","%")
45+
publish(nodes + "/humidity/$datatype","float")
46+
publish(nodes + "/humidity/$settable","false")
47+
publish(nodes + "/pressure/$name","Pressure")
48+
publish(nodes + "/pressure/$unit","hPa")
49+
publish(nodes + "/pressure/$datatype","float")
50+
publish(nodes + "/pressure/$settable","false")
51+
# homie stae ready
52+
publish("$state","ready")
53+
54+
def on_disconnect(client, userdata, rc):
55+
print("MQTT Connection disconnected, Returned code=",rc)
56+
57+
# running the Script
58+
# define BME280 Sensor
59+
i2c = busio.I2C(board.SCL, board.SDA)
60+
bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, address=0x76)
61+
# change this to match the location's pressure (hPa) at sea level
62+
#bme280.sea_level_pressure = 1010
63+
bme280.mode = adafruit_bme280.MODE_NORMAL
64+
time.sleep(1)
65+
66+
#MQTT Connection
67+
mqttattempts = 0
68+
while mqttattempts < mqttretry:
69+
try:
70+
client=mqtt.Client(mqttclientid)
71+
client.username_pw_set(username, password)
72+
client.tls_set(cert_reqs=ssl.CERT_NONE) #no client certificate needed
73+
client.tls_insecure_set(insecure)
74+
client.will_set("homie/" + clientid + "/$state","lost",qos,retain_message)
75+
client.connect(broker, port)
76+
client.loop_start()
77+
mqttattempts = mqttretry
78+
except :
79+
print("Could not establish MQTT Connection! Try again " + str(mqttretry - mqttattempts) + "x times")
80+
mqttattempts += 1
81+
if mqttattempts == mqttretry:
82+
print("Could not connect to MQTT Broker! exit...")
83+
exit (0)
84+
time.sleep(5)
85+
86+
# Tell systemd that our service is ready
87+
systemd.daemon.notify('READY=1')
88+
89+
client.on_connect = on_connect
90+
client.on_disconnect = on_disconnect
91+
92+
# finaly the loop
93+
while True:
94+
try:
95+
publish(nodes + "/temperature","{:.2f}".format(bme280.temperature))
96+
publish(nodes + "/humidity","{:.2f}".format(bme280.humidity))
97+
publish(nodes + "/pressure","{:.2f}".format(bme280.pressure))
98+
time.sleep(publishtime)
99+
100+
except KeyboardInterrupt:
101+
print("Goodbye!")
102+
# At least close MQTT Connection
103+
publish("$state","disconnected")
104+
time.sleep(1)
105+
client.disconnect()
106+
client.loop_stop()
107+
exit (0)
108+
109+
except :
110+
print("An Error accured ... ")
111+
time.sleep(3)
112+
continue
113+
114+
# At least close MQTT Connection
115+
print("Script stopped")
116+
publish("$state","disconnected")
117+
time.sleep(1)
118+
client.disconnect()
119+
client.loop_stop()

bme280_homie.service

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# systemd unit file for the Python BME280 Service
2+
[Unit]
3+
4+
# Human readable name of the unit
5+
Description=BME280 MQTT Homie Service
6+
7+
# Starting after System is online and docker is running
8+
# Only needed if MQTT is used
9+
Wants=network-online.target
10+
After=network-online.target
11+
#After=docker.service
12+
#After=docker.socket
13+
14+
[Service]
15+
16+
# Command to execute when the service is started
17+
ExecStart=/usr/bin/python3 /usr/local/sbin/bme280-homie.py
18+
19+
# Disable Python's buffering of STDOUT and STDERR, so that output from the
20+
# service shows up immediately in systemd's logs
21+
Environment=PYTHONUNBUFFERED=1
22+
23+
# Automatically restart the service if it crashes
24+
Restart=on-failure
25+
26+
# Our service will notify systemd once it is up and running
27+
Type=notify
28+
29+
# Use a dedicated user to run our service
30+
User=root
31+
32+
# Send CTRL+C tot python Script to terminate it clean
33+
KillSignal=SIGINT
34+
35+
[Install]
36+
37+
# Tell systemd to automatically start this service when the system boots
38+
# (assuming the service is enabled)
39+
WantedBy=default.target

0 commit comments

Comments
 (0)