Skip to content

Instantly share code, notes, and snippets.

@igrr
Created January 6, 2015 23:44
Show Gist options
  • Save igrr/7f7e7973366fc01d6393 to your computer and use it in GitHub Desktop.
Save igrr/7f7e7973366fc01d6393 to your computer and use it in GitHub Desktop.
PubSubClient sample for ESP8266 Arduino
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
const char* ssid = ".................";
const char* password = "................";
char* topic = "esp8266_arduino_out";
char* server = "iot.eclipse.org";
WiFiClient wifiClient;
PubSubClient client(server, 1883, callback, wifiClient);
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
String macToStr(const uint8_t* mac)
{
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5)
result += ':';
}
return result;
}
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
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());
// Generate client name based on MAC address and last 8 bits of microsecond counter
String clientName;
clientName += "esp8266-";
uint8_t mac[6];
WiFi.macAddress(mac);
clientName += macToStr(mac);
clientName += "-";
clientName += String(micros() & 0xff, 16);
Serial.print("Connecting to ");
Serial.print(server);
Serial.print(" as ");
Serial.println(clientName);
if (client.connect((char*) clientName.c_str())) {
Serial.println("Connected to MQTT broker");
Serial.print("Topic is: ");
Serial.println(topic);
if (client.publish(topic, "hello from ESP8266")) {
Serial.println("Publish ok");
}
else {
Serial.println("Publish failed");
}
}
else {
Serial.println("MQTT connect failed");
Serial.println("Will reset and try again...");
abort();
}
}
void loop() {
static int counter = 0;
String payload = "{\"micros\":";
payload += micros();
payload += ",\"counter\":";
payload += counter;
payload += "}";
if (client.connected()){
Serial.print("Sending payload: ");
Serial.println(payload);
if (client.publish(topic, (char*) payload.c_str())) {
Serial.println("Publish ok");
}
else {
Serial.println("Publish failed");
}
}
++counter;
delay(5000);
}
@bjoernhoefer
Copy link

Thanks for sharing this example - helped me a lot.

But if somebody experience the same problems I've did - maybe (s)he will find this information useful:

This sketch above does not contain a subscribe function - not a big deal, you just have to add a few lines to get it running

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.println("Received some data")
}

But then you think - ok, lets remove the constant noise on the mqtt bus and you remove the "client.publish" section.

Now things get interesting, because your mqtt broker (mosquito in my case) will throw you out, because you're beeing idle and your not commiting messages...

Why is that?

As mentioned on the site of nick o'leary (http://knolleary.net/arduino-client-for-mqtt/api/#loop) you have to do the "loop" constantly.

So if you add the following lines to your sketch, you should be able to subscribe to topics without the need to constantly publish stuff.

After the client.connect you should add this

if (client.subscribe("my_esp8266_subscription")){
  Serial.println("Successfully subscribed");
}

My main loop looks pretty easy:

void loop()
{
  client.loop();
}

For a proper handling of the callback-section of pubsubclient take a look at: http://m2mio.tumblr.com/post/30048662088/a-simple-example-arduino-mqtt-m2m-io - they provide a good code example.

Cheers

Björn

@scargill
Copy link

scargill commented Apr 6, 2015

Has anyone done any work on this to make it resilient. I think I'm right in saying that if you lose the connection for any reason (issue with MQTT broker, WIFI issue) thats' it, end of story. Would save some R&D if someone has already done this. In a remote situation, an error message is no good :-)

@alport
Copy link

alport commented Apr 9, 2015

Surely exercising the WDT is the way to go?
I am not yet seeing any WDT examples for the ESP under the Arduino IDE - anyone?

@CptanPanic
Copy link

if you want to just use watchdog, I think a call to abort() if not (client.connected()){ should do the trick.

@biohazardxxx
Copy link

it worked for me when putting the folder PubSubClient from https://github.com/knolleary/pubsubclient into arduino-1.6.1\hardware\esp8266com\esp8266\libraries

@dogrocker
Copy link

I have use this example it work find but some thing make me confuse, when I use callback

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  String payloads = String((char*)payload);
  Serial.println(payloads);
}

I publish testtest to the topic but when the callback run it return with some old buffer string or memory leaks?
like this testtestno_out{"micros":208547852,"counter":40}
The no_out{"micros":208547852,"counter":40}.
I think it comfrom char* topic = "esp8266_arduino_out"; and payload {"micros":208547852,"counter":40}

full serial print

Sending payload: {"micros":208547852,"counter":40}
Publish ok
testtestno_out{"micros":208547852,"counter":40}
Sending payload: {"micros":213675151,"counter":41}
Publish ok
testtestno_out{"micros":213675151,"counter":41}
Sending payload: {"micros":218811991,"counter":42}

@4refr0nt
Copy link

With latest build (installed via Boards Manager) I have PROGMEM incompatible issue with PubSubClient library. After some patches (deleting PROGMEM from PubSubClient.h and PubSubClient.cpp) working well.

@Blastersky
Copy link

Hi,

I've tried on both Arduino IDE's (1.6.1 & the latest 1.6.4), and I still see the same error:

In file included from esp8266_pubsubclient.ino:1:0:
C:\Users\Blastersky\Documents\Arduino\libraries\PubSubClient/PubSubClient.h:72:46: error: section attribute not allowed for ''
boolean publish_P(char , uint8_t PROGMEM *, unsigned int, boolean);
^
esp8266_pubsubclient.ino:7:15: warning: deprecated conversion from string constant to 'char
' [-Wwrite-strings]
esp8266_pubsubclient.ino:8:16: warning: deprecated conversion from string constant to 'char_' [-Wwrite-strings]
esp8266_pubsubclient.ino: In function 'void setup()':
esp8266_pubsubclient.ino:69:51: warning: deprecated conversion from string constant to 'char_' [-Wwrite-strings]

  • Any clues?

@parrotface
Copy link

Hi
I am looking for a working example of subscribe.
The above works great for Publish to mosquito
The suggestions above I can't get to work, I would apreciate a link to a working example
Thanks

@parrotface
Copy link

Subscribe Problems
bjoernhoefer commented on 5 Apr sketch above does not contain a subscribe function.
Code was post but I can't get it to work.
Please could you explain again or better still copy of working sketch would be nice.
Many Thanks getting very fed up as I have been trying for more than a week and just about to give up.
Please help
Thanks again

@rolpal
Copy link

rolpal commented May 31, 2015

@dogrocker, "String payloads = String((char_)payload);" will not work since payload is a byte_ and not null terminated, that's why it sends so much, until it runs into a null or max chars.
Try this:
// create character buffer with ending null terminator (string)
char message_buff[100];
for(i=0; i<length; i++) {message_buff[i] = payload[i]; }
message_buff[i] = '\0';
String msgString = String(message_buff);

@ parrotface, this would help you to I guess...
Source : http://m2mio.tumblr.com/post/30048662088/a-simple-example-arduino-mqtt-m2m-io

@parrotface
Copy link

Thanks for info I will try as soon as I get time

@rolpal
Copy link

rolpal commented Jun 6, 2015

I've got mine working fine now so just leave a reply if you get stuck.

@4ishops
Copy link

4ishops commented Jul 5, 2015

Arduino: 1.6.5 (Windows 7), Board: "Generic ESP8266 Module, 80 MHz, 115200, 512K (64K SPIFFS)"

Build options changed, rebuilding all

In file included from sketch_jul05a.ino:1:0:
D:\temp\arduino-1.6.5-r2\libraries\PubSubClient/PubSubClient.h:68:46: error: section attribute not allowed for ''
boolean publish_P(char , uint8_t PROGMEM *, unsigned int, boolean);
^
sketch_jul05a.ino:7:15: warning: deprecated conversion from string constant to 'char
' [-Wwrite-strings]
sketch_jul05a.ino:8:16: warning: deprecated conversion from string constant to 'char_' [-Wwrite-strings]
sketch_jul05a.ino: In function 'void setup()':
sketch_jul05a.ino:69:51: warning: deprecated conversion from string constant to 'char_' [-Wwrite-strings]
Error compiling.

Always has error above, any suggestions?

@Naish21
Copy link

Naish21 commented Aug 4, 2015

For the example above I had to use this PubSubClient library:
https://codeload.github.com/Imroy/pubsubclient/zip/master

But I had to change the call from the main program so it looked like this:
PubSubClient client(wifiClient, server, 1883);

And then... it worked.

@indystar1
Copy link

Naish21~ Thanks a lot^^

@frode
Copy link

frode commented Dec 21, 2015

Compilation failed with arduino ide, had to move the void callback above PubSubClient, but it should be fine as Naish21 mentioned above aswell..

@AdamMiltonBarker
Copy link

Has anyone got this working with connection to port 8883 with username/pass/TLS etc ?

@jvannor
Copy link

jvannor commented Mar 31, 2016

@AdamMiltonBarker - I've been trying and keep getting
"Attempting MQTT connection...failed, rc=-2 try again in 5 seconds"

@brian58
Copy link

brian58 commented Apr 2, 2016

Thanks Naish21 for your advice.

I downloaded my version of Mosquitto (v0.15) direct from the rasperian wheezy library & it was failing. When I wised up and downloaded Mosquitto from the Debian library (Latest version) all was goodness.

So if you have followed the instructions above and are still not connecting, try checking your Mosquitto version - you need the latest as the old ones done work

Instructions here
[(http://mosquitto.org/2013/01/mosquitto-debian-repository/)]

@SAKTHIVELKARUPPAIYAN
Copy link

i have used esp 12e pubsub client. i will sent the message through mqtt using ardunio ide 1,6.5.once upload my code with iot.eclipse.org mqtt server url means data will send . so i change my own mqtt server means message not send it show the error
WiFi connected
IP address:
192.168.100.49
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

give me any suggestion pls?

@PavelDorofeev
Copy link

Thank you. It works good.
Mosquitto Mqtt broker is on Ubuntu 12.04
I monitor the esp8266 through COM port /dev/ttyUSB0.
I have changed just this:
const char* ssid = "ququ2";
const char* password = "george34";
char* topic = "home/motions/Holl";
char* server = "192.168.1.19";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment