1.2.51. fejezet, MQTT

Arduino hőmérő mintakód

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>;
#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
 
float hum;
float temp;
EthernetClient ethClient;
PubSubClient client(ethClient);
 
// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177);
IPAddress server(192, 168, 1, 88);
 
void callback(char* topic, byte* payload, unsigned int length) {
  String command = "";
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i=0;i<length;i++) {
    command.concat((char)payload[i]);
  }
  Serial.println(command);
  if (command == "get") {
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    String resp = "{\"Humidity\":\"";
    resp.concat(hum);
    resp.concat(" %\", \"Temp\":\"");
    resp.concat(temp);
    resp.concat(" Celsius\"}");
    client.publish("outTopic",resp.c_str());
  }
}
 
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient")) {
      Serial.println("connected");
      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);
  dht.begin();
 
  client.setServer(server, 1883);
  client.setCallback(callback);
 
  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(1500);
}
 
void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

Mosquitto kliens parancsok:

sudo apt-get install mosquitto-clients
 
mosquitto_sub -h 192.168.1.88 -d -t outTopic
mosquitto_pub -h 192.168.1.88 -d -t inTopic -m "get"

Paho Python kliens

Paho telepítése:

pip install paho-mqtt

Mintakód:

#!/usr/bin/python
import paho.mqtt.client as mqtt
import time
import signal
import sys
import json
 
def signal_handler(sig, frame):
    client.loop_stop()
    print("loop stoped")
    sys.exit(0)
 
def on_message(client, userdata, message):
    msg = json.loads(str(message.payload.decode("utf-8")))
    print "Temp: " , msg['Temp'] 
    print "Humidity: " , msg['Humidity']
 
mqttBroker ="192.168.1.88"
 
client = mqtt.Client("pyClient")
client.connect(mqttBroker) 
 
client.loop_start()
 
client.subscribe("outTopic")
client.on_message=on_message 
 
signal.signal(signal.SIGINT, signal_handler)
 
while True:
    client.publish("inTopic", "get")
    time.sleep(5)

Kapcsolódó hivatkozások