This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm whether you accept or reject these cookies being set.

A cookie will be stored in your browser regardless of choice to prevent you being asked this question again. You will be able to change your cookie settings at any time using the link in the footer.

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A basic tutorial on MQTT please
#1
Because I cant edit the SPI settings in OP0.17, I'm trying to get my head around MQTT and the OP implementation.
Id like to publish some sensor data generated by an ESP2866 over WiFi but currently have no idea how to populate the OP and ESP2866 MQTT fields.
I know I could spend a while googling MQTT but Id appreciate some guidance to get me started.
Anyone ?
Thanks
Steve
Reply
#2
its just publish & subscribe..
there is a example of a nodemcu with a 4way relay and temperature sensor arduino ide.code at bottom of post.. subscribe topic A,B,C,D, outTopictemp ..
it would probably be easier to use espeasy and set that up, here is an example of a node subscribing to a esp32 with a bmp280..you can use the same message topic to subscribe in open plotter /controller name/device/data then choose an appropriate sk key to use it in the sys.
i have it working on op 0.17 no problem reading temperature from the arduino code below and from a esp32 with espeasy. ..
either way you are going to have to learn how it works to use it that means google...
almost forgot you need to set it up in op.." broker localhost, port 1883, name, password "

input nodes for node-red
Code:
[
   {
       "id": "95912b82.6dfec8",
       "type": "mqtt in",
       "z": "53e0326c.92abec",
       "name": "",
       "topic": "/esp_easy32/bmp280/Pressure",
       "qos": "2",
       "broker": "ada9afc8.e86e7",
       "x": 143.1667022705078,
       "y": 416.33335876464844,
       "wires": [
           [
               "69626e2f.ea66b",
               "489fd682.9a5378"
           ]
       ]
   },
   {
       "id": "81831f2e.35142",
       "type": "mqtt in",
       "z": "53e0326c.92abec",
       "name": "",
       "topic": "/esp_easy32/bmp280/Temperature",
       "qos": "2",
       "broker": "ada9afc8.e86e7",
       "x": 148.00006866455078,
       "y": 482.0000705718994,
       "wires": [
           [
               "69626e2f.ea66b",
               "777eddb8.f5d7b4"
           ]
       ]
   },
   {
       "id": "ada9afc8.e86e7",
       "type": "mqtt-broker",
       "z": "",
       "broker": "192.168.1.140",
       "port": "1883",
       "clientid": "",
       "usetls": false,
       "compatmode": true,
       "keepalive": "60",
       "cleansession": true,
       "willTopic": "",
       "willQos": "0",
       "willPayload": "",
       "birthTopic": "",
       "birthQos": "0",
       "birthPayload": ""
   }
]


arduino code for mqtt
Code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// wifi and MQTT broker vars

const char* ssid = "OpenPlotter";              // your network ssid
const char* password = "*******";             // password
const char* mqtt_server = "10.10.10.1";    // your mqtt server
boolean pin1 = false;
boolean pin2 = false;
boolean pin3 = false;                          
boolean pin4 = false;
boolean pin5 = false;
//boolean pin6 = false;
const int   misc_sens_pin = 12;                // temp was after thought 12 was free,. change to pin you like
const int   mqtt_interval = 60000;



WiFiClient espClient;
PubSubClient client(espClient);
OneWire oneWire(misc_sens_pin);
DallasTemperature DS18B20(&oneWire);

long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

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) {
if ( (char)topic[0] == 'A') {
  if ((char)payload[0] == '1') {
    digitalWrite(16, LOW);  // you will need to change pin # if done elswere, it is 16 now thats the onboard led for testing
  }
  if ((char)payload[0] == '0') {
    digitalWrite(16, HIGH);          // and here same as above and for any pin changes
  }
}

if ( (char)topic[0] == 'B') {
  if ((char)payload[0] == '1') {
    digitalWrite(4, LOW);   // Turn the LED on (Note that LOW is the voltage level
  }
  if ((char)payload[0] == '0') {
    digitalWrite(4, HIGH);   // Turn the LED on (Note that LOW is the voltage level
  }
}

if ( (char)topic[0] == 'C') {
  if ((char)payload[0] == '1') {
    digitalWrite(0, LOW);   // Turn the LED on (Note that LOW is the voltage level
  }
  if ((char)payload[0] == '0') {
    digitalWrite(0, HIGH);   // Turn the LED on (Note that LOW is the voltage level
  }
}

if ( (char)topic[0] == 'D') {
  if ((char)payload[0] == '1') {
    digitalWrite(2, LOW);   // Turn the LED on (Note that LOW is the voltage level
  }
  if ((char)payload[0] == '0') {
    digitalWrite(2, HIGH);   // Turn the LED on (Note that LOW is the voltage level
  }
}
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
  Serial.print("Attempting MQTT connection...");
  // Attempt to connect
  //if (client.connect("ESP8266Client5"))
  if (client.connect("esp82661","pi", "*******")){          //Your mqtt password in op*****
    Serial.println("connected");


    // ... and resubscribe
    client.subscribe("A");
    client.subscribe("B");
    client.subscribe("C");
    client.subscribe("D");

  } 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() {

pinMode(16, OUTPUT);
pinMode(4, OUTPUT);
pinMode(0, OUTPUT);                    
pinMode(2, OUTPUT);
pinMode(14, OUTPUT);                    // if you changed temp pin then it needs to be input..
pinMode(12, INPUT);                     //temp pin





Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
float temp;
char tempStr[5];

if (!client.connected()) {
  reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > mqtt_interval) {
  lastMsg = now;
  ++value;
  DS18B20.requestTemperatures();
  temp = DS18B20.getTempCByIndex(0);

  temp = (temp * 9.0) / 5.0 + 32.0;       // temp C to F

  String(temp).toCharArray(tempStr, 2);

  String(temp).toCharArray(tempStr, 5);
  client.publish("outTopictemp", tempStr);
  client.publish("outTopic", "Relay Board OK");
 
}
}

Reply
#3
Adding to this quest to handle MQTT data streams, I (sort of) succeeded using my Android phone as GPS receiver through MQTT, I'm still struggling with converting the data which went from MQTT message to object, to array and to (unwantedly) string, I'm not a dev...

Here below my flow and debug output, it shows my attempt to inject the lat/lon into my dashboard, it works but not as I wish, both strings are still to be stripped/converted.

[Image: owntracks.PNG]

Code:
[{"id":"f01686b2.94c638","type":"mqtt in","z":"217cab7.d842f54","name":"","topic":"owntracks","qos":"2","broker":"47dee4e1.57a214","x":100,"y":600,"wires":[["2069343.0d680cc"]]},{"id":"2069343.0d680cc","type":"function","z":"217cab7.d842f54","name":"splitting","func":"msg.payload = msg.payload.split(\",\");\nreturn msg;","outputs":1,"noerr":0,"x":240,"y":600,"wires":[["c3926ea9.6954d","be4ea282.527cb"]]},{"id":"e8c15157.66d0c","type":"debug","z":"217cab7.d842f54","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":450,"y":680,"wires":[]},{"id":"be4ea282.527cb","type":"function","z":"217cab7.d842f54","name":"routing","func":"var msg8 = msg.payload.map(function (p) {\n    return {payload: p};\n});\nreturn msg8;","outputs":8,"noerr":0,"x":230,"y":680,"wires":[[],[],[],["e8c15157.66d0c","50dd8c03.a0fde8"],["5390235e.c9248c","620f9130.009e9"],[],[],[]]},{"id":"5390235e.c9248c","type":"debug","z":"217cab7.d842f54","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":450,"y":700,"wires":[]},{"id":"c3926ea9.6954d","type":"debug","z":"217cab7.d842f54","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":510,"y":620,"wires":[]},{"id":"47dee4e1.57a214","type":"mqtt-broker","z":"","name":"MQQT","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"willTopic":"","willQos":"0","willRetain":"false","willPayload":"","birthTopic":"","birthQos":"0","birthRetain":"false","birthPayload":""}]

So when OpenPlotter receives GPS coordinates in NMEA0183 through the multiplexer, all works.
This is my attempt with my Android phone as a backup. We're talking about the dashboard, even not SignalK yet, the latter does receive the MQTT message in good order.
On the phone I installed Owntracks and on OpenPlotter I configured MQTT as described elsewhere on this forum.

Jeroen Adam
Reply
#4
Hope you managed to find all the information you needed back then.
But if anyone else who needs to get started with MQTT comes across this topic, I can suggest this mqtt connection guide. It’s the most comprehensive MQTT fundamentals I have found so far. It includes information on how the MQTT connection works. It also thoroughly explains the roles MQTT broker and client play in this process and what parameters the MQTT CONNECT and CONNACK packets include.
It’s written in simple words, and even a nonprofessional would be able to understand it easily."
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)