Ein MQTT Server ermöglicht den Austausch von Befehlen oder Daten zwischen externen Geräten wir WeMos, Raspberry Pi, Arduino, usw.
Nachfolgend wird die Installation von MQTT auf einem Raspberry Pi beschrieben (bei mir läuft darauf FHEM).
Anschliessend wird gezeigt, wie die bidirektionale Kommunikation ablaufen kann.
Installation auf dem Raspberry Pi:
sudo apt-get update
sudo apt-get upgrade
wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-jessie.list
sudo apt-get update
sudo apt-get install mosquitto
sudo cpan install Net::MQTT:Simple
sudo cpan install Net::MQTT:Constants
sudo apt-get install mosquitto mosquitto-clients
Erster Test:
mosquitto_sub -d -t hello/world
Nun wird eine zweite Shell aufgemacht in der wir folgendes eingeben:
mosquitto_pub -d -t hello/world -m „Gruss von Terminal 2“
Mosquitto Befehle:
- sudo service mosquitto status
- sudo service mosquitto stop
- sudo service mosquitto start
Angaben unter FHEM (Beispiel):
#########################################################################
## Definition …: WeMos1 mit Sensor PIR1 und LED1 in Kommunikation mit FHEM über MQTT
## Zweck………: Einbruch detektieren
## Standort……: Autarkes Eigenbausystem mit WeMos, LED, Buzzer und Battery
## Typ………..:
## Installation..: 24.12.2016
## Besonderheiten: Hier zu Testzwecken nur mit einem Sensor und einer LED
##
#########################################################################
#
define WeMos1 dummy
attr WeMos1 room Alarmanlage
define mqtt MQTT 192.xxx.xxx.xx:1883
attr mqtt room Alarmanlage
define mqtt_WeMos1 MQTT_BRIDGE WeMos1
attr mqtt_WeMos1 IODev mqtt
attr mqtt_WeMos1 publishState fhem/devices/wemos1_sensor1
attr mqtt_WeMos1 subscribeSet fhem/devices/wemos1_sensor1/set
attr mqtt_WeMos1 room Alarmanlage
attr mqtt_WeMos1 stateFormat transmission-state
FHEM reboot (auf dem Raspberry Pi):
sudo /etc/init.d/fhem stop
sudo /etc/init.d/fhem start
Test des Zusammenspiels von Raspberry Pi mit FHEM (Eingabe auf Kommandozeile Raspberry PI):
mosquitto_pub –q 2 –t /fhem/devices/wemos1_sensor1/set –m on
Beispielprogramm auf dem WeMosD1:
/*
WeMos D1 – MQTT Sensor Client by Thomas Krummer, 2017
*/
const byte LED1 = D5; // Ist eine Warn-LED die direkt am Bewegungssensor PIR1 angebracht ist und ist bei Bewegung an
const byte PIR1 = D2; // Ist der Bewegungssensor PIR1
int PIR1_Value;
int Status = 0; // für die spätere Signalverarbeitung und gibt nur ein Kommando an MQTT, wenn eine Änderung zu verzeichnen ist
int Merker = 0; // merkt sich den ursprünglichen Zustand von PIR1
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
bool autoConnect;
const char *ssid = „KxxxxxxxN“;
const char *password = „xxxxxxxxxx“;
const char *mqtt_server = „192.xxx.xxx.xx“;
const char* inTopic = „fhem/devices/wemos1_sensor1“;
const char* outTopic = „fhem/devices/wemos1_sensor1/set“;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
char message_buff[100];
void setup_wifi() {
int ret;
ESP.eraseConfig();
WiFi.mode(WIFI_STA); // Mode AP or Normal
delay(10);
// Get current autoconnect state from SDK
autoConnect = WiFi.getAutoConnect();
WiFi.begin(„DummySSID“, „whateverkeyjustdontconnect“);
uint8_t timeout = 10; // 10 * 500 ms = 5 sec time out
// 500ms loop
while ( ((ret = WiFi.status()) != WL_CONNECTED) && timeout ) {
Serial.print(„.“);
delay(500);
–timeout;
}
WiFi.begin(ssid, password);
// We start by connecting to a WiFi network
Serial.println();
Serial.print(„Connecting to „);
Serial.println(ssid);while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(„.“);
}
Serial.println(„“);
Serial.println(„WiFi connected“);
Serial.println(„IP address: „);
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
int i = 0;
// create character buffer with ending null terminator (string)
for (i = 0; i < length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = ‚\0‘;
String msgString = String(message_buff);
Serial.println(„Message:“ + msgString);
}
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(„Attempting MQTT connection…“);
// Create a random client ID
String clientId = „ESP8266Client-„;
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println(„connected“);
// Once connected, publish an announcement…
client.publish(outTopic, „online“);
// … and resubscribe
client.subscribe(inTopic);
} else {
Serial.print(„failed, rc=“);
Serial.print(client.state());
Serial.println(“ try again in 5 seconds“);
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(9600);
setup_wifi();
client.setServer(mqtt_server, 1883);
pinMode(LED1, OUTPUT);
pinMode(PIR1, INPUT);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
PIR1_Value = digitalRead(PIR1);
if (Merker != PIR1_Value) {Status = 1;} else {Status = 0;}
digitalWrite(LED1,PIR1_Value);
Serial.println(Status);
if (Status == 1) { if (PIR1_Value == 1) {client.publish(outTopic, „on“);} else {client.publish(outTopic, „off“);} Merker = PIR1_Value;}
delay (2000);
client.loop();
}
Test auch über den PC möglich:
Einfach das PC Programm MQTTFX auf den PC laden und den Kanäle auf „fhem/devices/wemos1_sensor1/set“ bzw. ohne „/set“ einstellen und den Pfad des MQTT Servers (Raspberry Pi) Adresse mit „:1883 “ angeben.
Die Kommunikation zwischen WeMos und dem Raspberry Pi bzw. FHEM kann mitverfolgt werden.
EINFACH NUR GEIL!