Auf dem Raspberry Pi:
# python3.6
import random
import json
import time
import RPi.GPIO as GPIO
from paho.mqtt import client as mqtt_client
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,0)
broker = '192.168.66.20'
port = 1883
topic = "instar/+/status/alarm/triggered"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'
def connect_mqtt() -> mqtt_client:
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
#print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
t = (msg.payload.decode())
#print(t)
g = json.loads(t)
#print(g)
#print("Alarmbereich : " + str(g["val"]))
h = (g["val"])
print(h)
i = int(h) # Umwandlung in INT
if i > 0:
GPIO.output(18,1)
time.sleep(2) # 2 Sekunden Impuls für Alarmanlage
GPIO.output(18,0)
else:
GPIO.output(18,0)
client.subscribe(topic)
client.on_message = on_message
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ == '__main__':
run()
Das Skript rufe ich beim Systemstart auf:
sudo crontab -e
darin: @reboot sleep 15 && /usr/bin/python3 /home/pi/rkk.py &