From 6f89c8f73a4737bfaeae9b62c74d9a1ce539cc49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ebbe=20Ba=C3=9F?= Date: Tue, 12 Jul 2022 11:52:48 +0200 Subject: [PATCH] added mqtt code for sensor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Ebbe Baß --- main.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index ed83d14..e5ba5c0 100644 --- a/main.py +++ b/main.py @@ -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()) \ No newline at end of file +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() \ No newline at end of file