MQTT Mosquitto and two ESP8266 - arduino

My problem:
I have a Raspberry Pi, and I have installed the Mosquitto MQTT broker on it. My objective is to make 2 MQTT clients communicate over the Mosquitto broker, so I have installed the code below on two ESP8266 (WeMos D1 mini)
and I have created this MQTT command: mosquitto_pub -h 192.168.1.20 -t /wassim/led -m "on".
So, when I connect only one ESP client, I see the message "on" in the serial monitor. But when I connect the second ESP client, I can't see any message on the serial monitor... (But if on the terminal of the Raspberry, then I can see everything. On the clients I can't see anything). The code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <MQTTClient.h>
float temp;
float lm;
String aw="";
const char* host = "192.168.1.20";
const char* ssid = "THOMSON1121";
const char* password = "Wassim";
WiFiClient net;
MQTTClient mqtt;
void connect();
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Booting...");
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
mqtt.begin(host, net);
connect();
if(mqtt.subscribe("/wassim/led")) {
Serial.println("Subscription Valid !");
}
Serial.println("Setup completed...");
}
void loop() {
if (!mqtt.connected()) {
connect();
}
mqtt.loop();
delay(3000);
}
void connect() {
while(WiFi.waitForConnectResult() != WL_CONNECTED) {
WiFi.begin(ssid, password);
Serial.println("WiFi connection failed. Retry.");
}
Serial.print("Wifi connection successful - IP-Address: ");
Serial.println(WiFi.localIP());
while (!mqtt.connect(host)) {
Serial.print(".");
}
Serial.println("MQTT connected!");
}
void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
Serial.print("incoming: ");
Serial.print(topic);
Serial.print(" - ");
Serial.print(payload);
Serial.println();
}
The change from one client to another is if(mqtt.subscribe("/wassim/tmp")).

MQTT is a 'message bus' application....in order to have multiple 'subscribers' receive the same message that is being put on the bus by a 'publisher', they both have to subscribe to the same topic...or at least enough of the topic + wildcard...in order to get sent that published message. You only have one of your two clients listening to the topic that your 'mosquitto_pub' command is sending out. For it to receive, you either specify the full topic (mqtt.subscribe("/wassim/led")), or a wildcard to pick up all the 'wassim' messages sent out (mqtt.subscribe("/wassim/#")).

Related

esp 32 with esp now and mqtt connection

i trying to acheive some home automation with esp 32. my project is like following
i have several end points with esp 8266 acting likes slave switches sending Id datas to an esp 32 who is my gateway.
both slaves (esp8266) and master gateway (esp 32, are communicating
with espnow library
the gateway should be connected to an mqtt server ( rasperry pi) who
dispatches automation command depending on endpoint Id.
For now i succesfully have communication between esp8266 slaves and esp 32 gateway
i also have succesfully setted my rasperry pi as mqtt broker with home automation command
But i'm blocked when i need to add wifi connection and mqtt messaging to my ESP 32 gateway
My code on the esp32 gateway is
#include <esp_now.h>
#include <WiFi.h>
#include <PubSubClient.h>
#define LED 2
int myData;
char ssid[] = "my ssid";
char password[] = "mypass";
char mqtt_server[] = "192.168.1.55";
WiFiClient espClient;
PubSubClient MQTTclient(espClient);
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&myData, incomingData, sizeof(myData));
Serial.print("Bytes received: ");
Serial.println(len);
Serial.print("data: ");
Serial.println(myData);
/*
if(myData == 1){
String reponse="device1";
MQTTclient.publish("homecommand",reponse.c_str());
}
*/
for (int t=0; t<3; t++)
{
digitalWrite(LED,HIGH);
delay(50);
digitalWrite(LED,LOW);
delay(50);
}
}
void MQTTconnect() {
while (!MQTTclient.connected()) {
Serial.print("Attente MQTT connection...");
String clientId = "TestClient-";
clientId += String(random(0xffff), HEX);
// test connexion
if (MQTTclient.connect(clientId.c_str(),"","")) {
Serial.println("connected");
} else { // si echec affichage erreur
Serial.print("ECHEC, rc=");
Serial.print(MQTTclient.state());
Serial.println(" nouvelle tentative dans 5 secondes");
delay(5000);
}
}
}
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
pinMode(LED,OUTPUT);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for recv CB to
// get recv packer info
esp_now_register_recv_cb(OnDataRecv);
/*
Serial.println("Connect to Wifi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected");
MQTTclient.setServer(mqtt_server, 1883);
if (!MQTTclient.connected()) {
MQTTconnect();
}*/
}
void loop() {
// put your main code here, to run repeatedly:
}
The code works well, when i trigger one of my slaves i receive the message print it in serial an blink 3 times
But when i uncomment the part about connecting to my home router and my mqtt broker i lost the 'On DataRecv' callback
So my question is "Is it possible to have an Esp working as espnow gateway to gather messages and at the same time being connected to my home router for mqtt publishing ?"
If yes i would appreciate some help to implement it.
Thanks a lot.
Swap
WiFi.mode(WIFI_STA);
for
WiFi.mode(WIFI_AP_STA);
re:
https://www.electrosoftcloud.com/en/esp32-wifi-and-esp-now-simultaneously/

Connect Arduino + ESP8266 to Azure IoT Hub Device via X509 certificate

I have hard times finding a solution, or writing my own, where I can connect ESP8266 with Azure IoT Hub Device via X509 certificate. Currently, I can connect using the symmetric key connection to my device, but I have devices that I want to authenticate with X509 certificate.
I found a solution, but is for Arduino Nano 33 IoT, which is probably using another chip and it has encryption slot.
I am trying to do this using the Azure IoT SDK C library, but without much success. Here is a code that is using Mqtt and WiFiClientSecure plus BearSSL in order to connect via certificate. Unfortunately, the only solution that I found was to generate ECCX09 certificate with a chip that have encryption and to just use the thumbprint. Here is my try to use the certificate:
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
// C99 libraries
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <cstdlib>
// Libraries for MQTT client, WiFi connection and SAS-token generation.
#include <ESP8266WiFi.h>
#include <ArduinoBearSSL.h>
#include <ArduinoMqttClient.h>
// Additional sample headers
#include "secrets.h"
// Utility macros and defines
#define LED_PIN 2
// Translate iot_configs.h defines into variables used by the sample
static const char* ssid = SECRET_WIFI_SSID;
static const char* password = SECRET_WIFI_PASS;
static const char* host = SECRET_BROKER;
static const String device_id = SECRET_DEVICE_ID;
// Memory allocated for the sample's variables and structures.
static WiFiClientSecure wifi_client;
static BearSSLClient ssl_client(wifi_client);
static MqttClient mqtt_client(ssl_client);
// Auxiliary functions
static void connectToWiFi()
{
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to WIFI SSID ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.print("WiFi connected, IP address: ");
Serial.println(WiFi.localIP());
}
/*
* Establishses connection with the MQTT Broker (IoT Hub)
* Some errors you may receive:
* -- (-.2) Either a connectivity error or an error in the url of the broker
* -- (-.5) Check credentials - has the SAS Token expired? Do you have the right connection string copied into arduino_secrets?
*/
void connectToMQTT() {
Serial.print("Attempting to MQTT broker: ");
Serial.print(host);
Serial.println(" ");
while (!mqtt_client.connect(host, 8883)) {
// failed, retry
Serial.print(".");
Serial.println(mqtt_client.connectError());
delay(5000);
}
Serial.println();
Serial.println("You're connected to the MQTT broker");
Serial.println();
// subscribe to a topic
mqtt_client.subscribe("devices/" + device_id + "/messages/devicebound/#");
}
unsigned long getTime() {
// get the current time from the WiFi module
// return WiFi.getTime();
return time(NULL);
}
static void establishConnection()
{
// Set the username to "<broker>/<device id>/?api-version=2018-06-30"
String username;
// Set the client id used for MQTT as the device id
mqtt_client.setId(device_id);
username += host;
username += "/";
username += device_id;
username += "/api-version=2018-06-30";
mqtt_client.setUsernamePassword(username, "");
if(WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
if (!mqtt_client.connected()) {
// MQTT client is disconnected, connect
connectToMQTT();
}
}
// Arduino setup and loop main functions.
void setup()
{
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Serial.begin(9600);
// Set the X.509 certificate
// ssl_client.setEccCert(CLIENT_CERT);
ssl_client.setEccSlot(0, CLIENT_CERT);
// Set a callback to get the current time
// used to validate the servers certificate
ArduinoBearSSL.onGetTime(getTime);
establishConnection();
}
void loop() {}
This fails on setting the Certificate and to use the ecc slot 0, because I am using ESP8266 that does not have cryptography in it (or at least I do not know). I saw in the library that there is another method in the BearSSL - void setEccCert(br_x509_certificate cert); , but I do not know how to initialize br_x509_certificate (here is the ref).
I decided to try something else, too, reading the certificate with SPIFFS, then adding to WiFiClientSecure. Unfortunately, I cannot load the private key to make client connection.
#include "FS.h" // File system commands to access files stored on flash memory
#include <ESP8266WiFi.h> // WiFi Client to connect to the internet
#include <PubSubClient.h> // MQTT Client to connect to AWS IoT Core
#include <NTPClient.h> // Network Time Protocol Client, used to validate certificates
#include <WiFiUdp.h> // UDP to communicate with the NTP server
#include "secrets.h"
// Utility macros and defines
#define NTP_SERVERS "pool.ntp.org", "time.nist.gov"
// Translate secrets.h defines into variables used by the sample
static const char* ssid = SECRET_WIFI_SSID;
static const char* password = SECRET_WIFI_PASS;
static const char* iot_hub_broker = SECRET_BROKER;
// callback function that will be called when the device receive a message
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
// Memory allocated client variables
static WiFiUDP ntp_UDP;
static NTPClient time_client(ntp_UDP, "pool.ntp.org");
static WiFiClientSecure esp_client;
static PubSubClient mqtt_client(iot_hub_broker, 8883, callback, esp_client);
// Auxiliary functions
static void configureX509CertificateConnection() {
time_client.begin();
while(!time_client.update()) {
time_client.forceUpdate();
}
esp_client.setX509Time(time_client.getEpochTime());
Serial.println("Time client and ESP client are set up.");
// Attempt to mount the file system
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
return;
}
// Load certificate file from file system
File cert = SPIFFS.open("temperature-sensor-1-all.pem", "r");
if (!cert) {
Serial.println("Failed to open certificate from file system");
} else {
Serial.println("Successfully opened certificate file");
}
// Load private key file from file system
File private_key = SPIFFS.open("/temperature-sensor-1-private.pem", "r");
if (!private_key) {
Serial.println("Failed to open private key from file system");
}
else {
Serial.println("Successfully opened private key file");
}
delay(1000);
// Load private key to client connection
if (esp_client.loadPrivateKey(private_key)) {
Serial.println("Private key loaded to client connection");
}
else {
Serial.println("Private key not loaded to client connection");
}
}
static void connectToWiFi() {
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to WiFi: ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("WiFi connected, IP address: ");
Serial.println(WiFi.localIP());
}
/*
* Establishses connection with the MQTT Broker (IoT Hub)
* Some errors you may receive:
* -- (-.2) Either a connectivity error or an error in the url of the broker
* -- (-.5) Check credentials - has the SAS Token expired? Do you have the right connection string copied into arduino_secrets?
*/
void connectToMQTT() {
}
static void establishConnection() {
if (WiFi.status() != WL_CONNECTED) {
connectToWiFi();
}
configureX509CertificateConnection();
}
// Arduino setup and loop main functions.
void setup() {
pinMode(2, OUTPUT);
digitalWrite(2, HIGH);
Serial.begin(115200);
establishConnection();
}
void loop() {}
I will be happy to find a solution, because I am in a hurry for my thesis.
P.S. I have it up and running on Raspberry Pi, but I have to make some experiments using the Arduino and ESP8266.
P.S.2. I am using Arduino with Atmega328P with integrated ESP8266 chip, but working only with the ESP8266. Additionally, I am using Arduino IDE 1.8.19 and installed the Azure IoT SDK C library (and some other required ones).
P.S.3. Additionally, I could find X509 certificate sample, but it is using the Paho Mqtt Client and I am not able reproduce it on Arduino.

Message is not publishing to ESP8266 from IBM Bluemix

I have programmed to my ESP8266 and subscribed one topic to keep listening messages. This is my graphical view of injecting message to IBM Iot node.
This is my settings of inject view
This is my settings of IBM Iot node.
Here are my logs at Serial Monitor, it is connected and subscribed to cmd channel
So far so good, When I am trying to inject a message to my IBM Iot node then it is not publishing a message, as it is not reaching on serial monitor and no log on debug view. here you can see
Here is source code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient/releases/tag/v2.3
const char* ssid = "shiv";
const char* password = "manmohan#12345";
#define ORG "2kafk4"
#define DEVICE_TYPE "ESP8266"
#define DEVICE_ID "5CCF7FEED6F0"
#define TOKEN "opKF7v3#8jRM*mGkb_"
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/cmd/test/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
for (int i = 0; i < payloadLength; i++) {
Serial.print((char)payload[i]);
}
}
PubSubClient client(server, 1883, callback, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
wifiConnect();
mqttConnect();
}
void loop() {
if (!client.loop()) {
mqttConnect();
}
}
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
void mqttConnect() {
if (!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(server);
while (!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
initManagedDevice();
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe(topic)) {
Serial.println("subscribe to cmd OK");
} else {
Serial.println("subscribe to cmd FAILED");
}
}
I tried to check cloud foundry logs using cf command, here it is https://pastebin.com/dfMaS1Gd
Can anyone hint me what I am doing wrong ? Thanks in advance.
Confirm the device type is correctly specified in your node configuration. Currently the screenshot show 0.16.2 which doesn't seem to match the device type you registered and what is specified in your code.

Not able to Receive subscribed Message with PubSubClient.h in Arduino Uno R3

#include "SPI.h"
#include “WiFiEsp.h”
#include <WiFiEspClient.h>
#include “SoftwareSerial.h”
#include <PubSubClient.h>
#include <WiFiEspUdp.h>
float temp=0;
int tempPin = 0;
int isClientConnected = 0;
char data[80];
char ssid[] = “SSID”; // your network SSID (name)
char pass[] = “PASSWORD”; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio’s status
char deviceName = “ArduinoClient1”;
IPAddress server(xxx,xxx,xxx,xxx); //MQTT server IP
IPAddress ip(192,168,43,200);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(“Message arrived [“);
Serial.print(topic);
Serial.print(“] “);
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println("-");
}
// Emulate Serial1 on pins 6/7 if not present
WiFiEspClient espClient;
PubSubClient client(espClient);
SoftwareSerial Serial1(6,7); // RX, TX
void setup(){
Serial.begin(9600);
Serial1.begin(9600);
WiFi.init(&Serial1);
WiFi.config(ip);
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
while ( status != WL_CONNECTED) {
Serial.print("Attemptingonnect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
Serial.print("WiFius : ");
Serial.println(status);
}
//connect to MQTT server
client.setServer(server, 1883);
client.setCallback(callback);
isClientConnected = client.connect(deviceName);
Serial.println("+++++++");
Serial.print("isClientConnected;
Serial.println(isClientConnected);
Serial.print("client.state");
Serial.println(client.state());
if (isClientConnected) {
Serial.println("Connected…..");
client.publish("status","Welcome to ISG");
client.subscribe("isg/demoPublish/rpi/ardTempWarn");
//Not able to recieve for this subscribed topic on Arduino Uno Only if I
//print it returns 1
}
}
void loop() {
temp = (5.0 * analogRead(tempPin) * 100.0) / 1024;
Serial.print(" temp : " );
Serial.println(temp);
Serial.print("client.connected);
Serial.println(client.connected());
if (!client.connected()) {
reconnect();
}
client.publish("isg/demoPublish/ard1/tempLM35",String(temp).c_str());
// able to receive data at other
// clients like RPI,Web using Mosquitto broker
client.loop();
delay(5000);
}
void reconnect() {
Serial.println("Device is trying to connect to server ");
while (!client.connected()) {
if (client.connect(deviceName)) {
} else {
delay(5000);
}
}
}
I am using Arduino Uno R3 and ESP8266-01 as wifi connector.
I have to read temperature data and send to Mosquitto ,MongoDB and Raspberry Pi and receive a data on specific condition for that i have subscribed a topic in Arduino.
I am able to receive data from Arduino to all other clients but I am not able to receive data on Subscribed topic in Arduino. But all other deviced like MongoDB able to receive data from Raspberry Pi.
I have used Arduino Uno R3, ESP8266-01 devices and liberary for to connect and send/receive data WiFiEsp.h, WiFiEspClient.h, WiFiEspUdp.h, SoftwareSerial.h, PubSubClient.h
client.subscribe("topic"); returns 1
Also callback function implemented but not able to get call.
So can any one help me why I am not getting subscribed topic message in Arduino?
I have follow https://sonyarouje.com/2016/03/15/mqtt-communication-with-arduino-using-esp8266-esp-01/#comment-111773
The library that you are using has bug in callback hence it would be better that you use other library my preference would be
https://github.com/vshymanskyy/TinyGSM
this library include almost all variants of SIM800(A,C,L,H,808), variants of SIM900(A,D,908,968), ESP8266 (mounted on arduino), Ethernet shield etc. It worked for me, as same issue bugged me for almost 1-2 weeks but latter was able to receive all subscribed message irrespective of mode of communication(GSM,Ethernet,WiFi)

MQTT on Arduino not working

I'm using Arduino Uno and Wi-Fi shield. I'm trying to implement MQTT protocol for communication and I tried two libraries for Arduino. First one is Knolleary's PubSubClient: http://pubsubclient.knolleary.net/ . I modified original example a little bit to use WiFi module instead of ethernet. Sending works but not every time (sometimes, the message is sent and sometimes not). But receiving via callback function doesn't work at all.
Here is my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the desired topic
- subscribes to the desired topic
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// If you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
As you can see, I'm using http://test.mosquitto.org/ for testing. I'm also using mosquitto on Ubuntu where I'm subscribed to the same topic and from where (another terminal window) I'm publishing to the same topic. Here is the picture of both windows:
As you can see, "hello world" message from Arduino is received successfully (but not every time), and when I publish "bla" message from another window, it's successfully received on mosquitto (on image) but NOT on Arduino. Is there something wrong with my code or? I found similar problem here: Arduino Knolleary PubSubClient will publish messages but can't receive them
It's worth noticing that it keeps getting reconnected all the time. As you can see, in loop() I put a part of code which will connect and subscribe again if connection is lost. On Serial Monitor I get "INFO: Reconnected!" message every 2-3 seconds.
Adafruit library
Then I tried the Adafruit library, but it won't connect at all! I tried with test.mosquitto.org and with io.adafruit.com from their example, but I just keep getting "Connection failed!" error. I tried making many changes and combinations but no luck so far. Once I managed to get "Failed to subscribe" instead of "Connection failed" but this was only once and next time with the same code I get "Connection failed" again.
Here's my code:
/*
Basic MQTT example with Authentication
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
#include <WiFi.h>
#include <PubSubClient.h>
char ssid[] = "[DELETED]"; // your network SSID (name)
char pass[] = "[DELETED]"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
// Update these with values suitable for your network.
IPAddress server(85, 119, 83, 194);
WiFiClient WifiClient;
void callbackFunc(char* topic, byte* payload, unsigned int length) {
Serial.println("test message received");
/*Serial.println();
Serial.println("=============== MESSAGE RECEIVED ================================");
Serial.print("Topic: ");
Serial.print(topic);
Serial.println();
Serial.println((const char *) payload);*/
}
PubSubClient client(server, 1883, callbackFunc, WifiClient);
void setup()
{
delay(2000);
Serial.begin(9600);
Serial.println("Starting....");
Serial.println("Initializing Wifi...");
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
}
// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if (status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// Ff you are connected, print out success message
else
Serial.println("Connected to network");
if (client.connect("arduinoClient")) {
Serial.println("Connected to server! Sending message...");
client.publish("randy/test","hello world");
client.subscribe("randy/test");
Serial.println("Sent!");
}
else
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
}
void loop()
{
client.loop();
delay(1000);
if (!client.connected())
{
if(!client.connect("arduinoClient"))
{
Serial.println("ERROR: Cannot connect to MQTT server!");
Serial.println(client.state());
}
else
{
client.subscribe("randy/test");
Serial.println("INFO: reconnected!");
}
}
}
Any idea what's wrong with those libraries or my code?
As mentioned in the comments
When using example code on public brokers make sure you change the client id to something random as the odds of clashing with somebody else are pretty high. Because client ids have to be unique else they will cause a reconnection storm

Resources