alexCajas / EmbeddedMqttBroker

This is a Mqtt broker for embedded devices, developed in C++, FreeRTOS to use advanced multitasking capabilities, and arduino core. Tested in an Esp32 and esp8266.
https://github.com/alexCajas/EmbeddedMqttBroker
MIT License
77 stars 15 forks source link

Example for use with PubSubClient #15

Closed vanhcm20 closed 1 year ago

vanhcm20 commented 1 year ago

Hi @alexCajas can you give me the example use with PubSubClient library, i dont know what server domain or use ip address. Thanks.

alexCajas commented 1 year ago

yes of course, if you don't use a fixed local ip, you can get your dinamyc ip using WiFi.localIP() here an example:

#include <WiFi.h> 
#include <PubSubClient.h>
#include "EmbeddedMqttBroker.h"
using namespace mqttBrokerName;

uint16_t mqttPort = 1883;
MqttBroker broker(mqttPort);

// mqtt client initialization
WiFiClient espClient;
PubSubClient clientMqtt(espClient);

void callback(char *topic, byte *payload, unsigned int length);

void setup(){

  Serial.begin(115200);
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.println("simple mqtt broker");
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    WiFi.begin(ssid, password);
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");

  // Start the mqtt broker
  broker.setMaxNumClients(9); // set according to your system.
  broker.startBroker();
  Serial.println("broker started");

  // Print the IP address
  Serial.print("Use this ip: ");
  Serial.println(WiFi.localIP());
  Serial.print("and this port: ");
  Serial.println(mqttPort);
  Serial.println("To connect to mqtt broker");

 // conect mqtt client to broker
  IPAddress ip = WiFi.localIP();
  clientMqtt.setServer(ip, mqtt_server_port);
  clientMqtt.setCallback(callback);
}

void callback(char *topic, byte *payload, unsigned int length)
{ 
  Serial.println("topic recived!");
}