MQTT Pubsubclient example

For devices supporting the Auto Discovery feature. Like ZWaveJS2MQTT, Zigbee2MQTT.

Moderator: leecollings

Post Reply
MarsaultP
Posts: 34
Joined: Wednesday 27 November 2019 13:31
Target OS: Linux
Domoticz version: 2024.7
Location: France
Contact:

MQTT Pubsubclient example

Post by MarsaultP »

Here is a tested example of use MQTT with a Wemos
Wemos => Domoticz (temperature sensor)
Domoticz => Wemos (switch)

Code: Select all

//========================================================================
// DOMOTICZ MQTT JSON Publish / subcribe sensor and switch
// Example
//
// 2024-04-28 Philippe Marsault
//========================================================================

#include <ESP8266WiFi.h>			// Gestion de base des connections WiFi

#define MQTT_MAX_PACKET_SIZE 1024			// https://www.domoticz.com/wiki/MQTT
#include <PubSubClient.h>			// bibliotheque MQTT
#include <ESP8266WebServer.h>		// Manage web server
#include <ArduinoJson.h>			// JSON, Benoît Blanchon library

#include <SPI.h>					// Serial Peripheral Interface (SPI)
#include <SoftwareSerial.h>			// Gestion des communications serie par emulation logicielle

#define MY_BAUD_RATE 9600					// serial port board <-> PC for debug

#define ssid           "myssid"				// votre ssid   
#define password       "mypassword"			// votre mdp
#define mqtt_server    "192.168.y.xx"		// ip of Mosquitto MQTT server
#define mqtt_username  "Dalton"				// your mqtt login
#define mqtt_password  "Rantanplan"			// your mqtt password

#define mqtt_clientID	"Arduino"

#define IDXT1 203                     // idx of your device test

char mqttbuffer[60]; // buffer for MQTT
float Temperature;

WiFiClient Myboard;					// create WiFiClient object
// PubSubClient client(mqtt_server, 1883, callback, Myboard);
PubSubClient client(Myboard);

void callback(char* topic, byte* payload, unsigned int length) {
//==============================================================
// Callback function
//==============================================================
	// In order to republish this payload, a copy must be made
	// as the orignal payload buffer will be overwritten whilst
	// constructing the PUBLISH packet.

	// Allocate the correct amount of memory for the payload copy
	byte* p = (byte*)malloc(length);
	//
	String msgEntry="";
	Serial.print("[callback()] Input message [");
	Serial.print(topic);
	Serial.print("] ");
	for (int i = 0; i < length; i++) {     // input to msgEntry
		msgEntry+=((char)payload[i]); 
	}  
	Serial.print(msgEntry); 
	// Copy the payload to the new buffer
	memcpy(p,payload,length);
	client.publish("outTopic", p, length); // to verify 
	// Free the memory
	free(p);
  
	// identify "Myswitch" and read state
    JsonDocument jsonBuffer;
    DeserializationError error = deserializeJson(jsonBuffer, msgEntry);    
    if (error) {
      Serial.print(F("[callback()] deserializeJson() --> Failed : "));
      Serial.println(error.f_str());
      return;
    }
    String switch_name = jsonBuffer["name"];
    String valeur = jsonBuffer["nvalue"];
    if ( switch_name == "Myswitch") {                
      if( valeur == "1") { 
        Serial.printf("[callback()] Myswitch ON");   
        Serial.println();
      } else {
        Serial.printf("[callback()] Myswitch OFF");   
        Serial.println();
      }           
    }
    delay(5000);
}

void connexion_WiFi(){
//==============================================================
// WiFi Connexion
//==============================================================
  Serial.println(); 
  Serial.print("[setup()] Connexion to WIFI -> ");  
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  // loop until connexion
  while (WiFi.status() != WL_CONNECTED) {
	Serial.println("Waiting WiFi");   
  delay(5000);
  }  
  Serial.println("OK");
  Serial.print("Adresse ip : ");
  Serial.println(WiFi.localIP());   
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  Serial.println("[setup()] Initialisation OK");
  Serial.println(); 
}

void reconnect(){
//==============================================================
// MQTT Connexion
//==============================================================
  while (!client.connected()) {
    Serial.println("Connect to MQTT server ...");
    if (client.connect(mqtt_clientID, mqtt_username, mqtt_password)) {
      Serial.println("MQTT connected");
      client.publish("outTopic","hello world");
    }
    else {
      Serial.print("Failed, error code = ");
      Serial.println(client.state());
      Serial.println("new test in 2s");
    delay(2000);
    }
  }

  if (!client.subscribe("domoticz/out/+")) {   // Domoticz => Arduino	/ + sign to accept all topics
    Serial.println("subscribe FAILED");
  }
}

void setup() {

	Serial.begin(MY_BAUD_RATE);     			// Serial port board <-> PC for debug
	connexion_WiFi();	// connect to WiFi
	reconnect();		// connect to MQTT
	// Adjust buffer size for MQTT payload
	Serial.print("[Buffer size before [");
	Serial.print(client.getBufferSize ());
	Serial.print("] ");
	if (client.setBufferSize (MQTT_MAX_PACKET_SIZE)) {
		Serial.print("[Buffer size after [");
		Serial.print(client.getBufferSize ());
		Serial.print("] ");
	}
	else {
		Serial.print("[Buffer size non modifiable");
	}
}

void loop()
{
	// example : simulate temperature and send to Domoticz
	Temperature = random(10, 20);  
	sprintf(mqttbuffer, "{ \"idx\" : %d, \"nvalue\" : 0, \"svalue\" : \"%.1f\" }", IDXT1, Temperature); 
	Serial.print("MQTT --> ");
	Serial.print(mqttbuffer);
	if (client.publish("domoticz/in", mqttbuffer) ) Serial.println(" OK"); 
	else Serial.println(" KO"); 
	
	delay(2000);
	
	client.loop();
}

Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests