Script zum Senden der aktuellen Input-Werte aller Devices in MQTT Topics

Show the world your Revolution Pi project!
Post Reply
Lace
Posts: 10
Joined: 30 Jan 2018, 12:36
Answers: 0

Script zum Senden der aktuellen Input-Werte aller Devices in MQTT Topics

Post by Lace »

Hallo,

dieses Script schickt alle Input-Werte bei Wertänderungen (und beim Start des Scriptes) an MQTT Topics revpi/inputs/INPUTNAME .
Wie Werte werden als Retained Nachrichten gesendet, so ist der letzte Wert im topic immer Verfügbar wenn ein neuer Client sich für die Werte interessiert.
Im Script wird der MQTT Broker auf localhost ohne Authentifizierung angesprochen.

Das Script benötigt folgende Bibliotheken:

- die Python Bibliothek revpimodio2, zu installieren mit
sudo apt-get install python3-revpimodio2

- die Python Bibliothek paho-mqtt
sudo pip3 install paho-mqtt

Wenn Ihr jetzt z.B. Node-RED verwendet könnt ihr ganz einfach die Input-Werte über den MQTT-Input-Node empfangen und weiterverarbeiten.

Installation:
==========
fügt in die Datei /etc/rc.local folgendes ein (vor "exit 0"):
/usr/bin/python3 pfad/zum/script/revpi_inputs_to_mqtt.py &

Als MQTT-Broker könnt ihr z.B. mosquitto installieren
sudo apt-get install mosquitto mosquitto-clients

Abfragen der Werte im MQTT Broker:
==============================
mosquitto_sub -h localhost -t "#"

Hier das Script, viel Spaß damit:
=========================

Code: Select all

import revpimodio2
import time
import paho.mqtt.client as mqtt
import json

def on_connect(client, userdata, flags, rc):
  print("Connected with result code " + str(rc))

firstcycle = True

mqttClient = mqtt.Client()
mqttClient.on_connect = on_connect
mqttClient.connect("localhost", 1883, 0)


# RevPiModIO Instantiieren
rpi = revpimodio2.RevPiModIO(autorefresh=True)

# Strg+C automatisch verarbeiten
rpi.handlesignalend()

# prepare list of inputs of all connected devices
myinputs = dict()
for name in rpi.device:
  if rpi.device[str(name)].position == 0:
    continue
  allinputs = rpi.device[str(name)].get_inputs()
  for thisinput in allinputs:
    myinputs[str(thisinput)] = 0

# cycle loop function
def cycleprg(zyklustools):
  global firstcycle

  # iterate through all inputs and check if value has changed
  # if it has changed or this is the first cycle mqtt publish it
  for k, v in myinputs.items():
    valChanged = False;
    if rpi.io[k].value != v:
      myinputs[k] = rpi.io[k].value
      valChanged = True
    if (valChanged == True) or (firstcycle == True):
      mqttClient.publish("revpi/inputs/"+k,myinputs[k], qos=0,retain=True)
  firstcycle = False

rpi.cycleloop(cycleprg)
Post Reply