added mqtt code for sensor

Signed-off-by: Ebbe Baß <ebbe@ping-mee.de>
master
Ebbe Baß 2022-07-12 11:52:48 +02:00
parent 72ed90e722
commit 6f89c8f73a
1 changed files with 47 additions and 2 deletions

49
main.py
View File

@ -1,3 +1,4 @@
from string import whitespace
import time
from datetime import datetime
try:
@ -64,7 +65,51 @@ def get_water_level():
def get_temperature():
i2c = busio.I2C(board.SCL, board.SDA)
bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c, address=0x76)
return int(bmp280.temperature)
rounded_temp = int(bmp280.temperature)
return str(rounded_temp)
print(get_water_level())
print(get_temperature())
print(get_temperature())
def mqtt_on_connect(client):
client.subscribe("strawberry-pi-greenhouse/relay/channel/1")
client.subscribe("strawberry-pi-greenhouse/relay/channel/2")
client.subscribe("strawberry-pi-greenhouse/relay/channel/3")
client.subscribe("strawberry-pi-greenhouse/relay/channel/4")
def mqtt_on_message(msg):
print("topic: " ,str(msg.topic))
print("payload: " ,str(msg.payload.decode("utf-8")))
topic = str(msg.topic)
payload = str(msg.payload.decode("utf-8"))
if topic == "strawberry-pi-greenhouse/relay/channel/1":
pass
elif topic == "strawberry-pi-greenhouse/relay/channel/2":
pass
elif topic == "strawberry-pi-greenhouse/relay/channel/3":
pass
elif topic == "strawberry-pi-greenhouse/relay/channel/4":
pass
if __name__ == "__main__":
mqttBroker ="homeassistant.ping-mee.local"
client = mqtt.Client("greenhouse_client")
client.username_pw_set("mqtt", "pmMQTT_11!")
debug_print("Connecting to MQTT Broker "+str(mqttBroker))
client.connect(mqttBroker)
client.on_connect = mqtt_on_connect
client.on_message = mqtt_on_message
client.loop_start()
try:
client.loop_start()
while True:
client.publish("strawberry-pi-greenhouse/sensor/temperature", get_temperature())
debug_print("Published current temperature: "+get_temperature())
client.publish("strawberry-pi-greenhouse/sensor/water-level", get_water_level())
debug_print("Published current water level: "+get_water_level())
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()