Giter Site home page Giter Site logo

adafruit_mqtt_library's Introduction

Adafruit MQTT Library Build Status

Arduino library for MQTT support, including access to Adafruit IO. Works with the Adafruit FONA, Arduino Yun, ESP8266 Arduino platforms, and anything that supports Arduino's Client interface (like Ethernet shield).

See included examples for how to use the library to access an MQTT service to publish and subscribe to feeds. Note that this does not support the full MQTT spec but is intended to support enough for QoS 0 and 1 publishing.

Depends on the following other libraries depending on the target platform:

Future todos:

  • Subscription callbacks

  • remove watchdog

Compatibility

MCU Tested Works Doesn't Work Not Tested Notes
Atmega328 @ 16MHz X
Atmega328 @ 12MHz X
Atmega32u4 @ 16MHz X
Atmega32u4 @ 8MHz X
ESP8266 X
Atmega2560 @ 16MHz X
ATSAM3X8E X
ATSAM21D X
ATSAMD51J20 X
ATtiny85 @ 16MHz X
ATtiny85 @ 8MHz X
Intel Curie @ 32MHz X
STM32F2 X
  • ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini
  • ATmega328 @ 12MHz : Adafruit Pro Trinket 3V
  • ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0
  • ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro
  • ESP8266 : Adafruit Huzzah
  • ATmega2560 @ 16MHz : Arduino Mega
  • ATSAM3X8E : Arduino Due
  • ATSAM21D : Arduino Zero, M0 Pro
  • ATSAMD51J20: Adafruit PyPortal
  • ATtiny85 @ 16MHz : Adafruit Trinket 5V
  • ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V

adafruit_mqtt_library's People

Contributors

abachman avatar ace1046 avatar andydoro avatar ben-willmore avatar brentru avatar cmumford avatar dlizotte-uwo avatar evaherrada avatar fapiko avatar flavio-fernandes avatar fpistm avatar frederikheld avatar jerryneedell avatar jmue avatar jwcooper avatar karlduino avatar ladyada avatar malachib avatar matthijskooijman avatar microbuilder avatar mxwinters avatar per1234 avatar petersimonsson avatar rgorosito avatar stuthedew avatar tapiralec avatar tdicola avatar toddtreece avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adafruit_mqtt_library's Issues

Callback and subscription to sub-topics

I switched to Adafruit MQTT from pubsubclient only for the purpose of SSL with esp8266, but I am unable to subscribe to subtopics using topic/+/+ as it was possible in PubSubClient and the callback function is a much needed feature... even though the library contains

void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackType cb) {
  callback = cb;
}

void Adafruit_MQTT_Subscribe::removeCallback(void) {
  callback = 0;

using mqtt.setCallback results in error:
* mqtt.setCallback();
^
exit status 1
'class Adafruit_MQTT_Client' has no member named 'setCallback'
*

Do not publish NaN floats

  • Arduino board: Adafruit Feather M0 WiFi
  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.6.10
  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too): LIST REPRO STEPS BELOW
  • Create a NaN float (e.g. divide-by-zero)
  • Pass it to a Adafruit_MQTT_Publish.publish((float) f)
  • Literal "NaN" characters published to float (due to munching by dtostrf)

PR opened: #57

#define MAXSUBSCRIPTIONS 5 --> cannot be increased?

I tried subscribing to 6 topics, and only 5 connected. Increased MAXSUBSCRIPTIONS to 10 in the .h file. No luck. Turned on MQTT_DEBUG to see what was happening. Saw that the sixth subscription packet got "sendPacket returned: 0". Wah!

Can't keep connection open with 2+ MQTT devices

Hello,

I've been working on several guides for Adafruit using Adafruit IO with this MQTT library.

This morning I was working on my latest guide, and I found something strange.

I first configured a device based on an Arduino Uno + CC3000 chip, which will simply publish data to a feed when a sensor reads some given value. This works just fine.

Then, I configured another device, based on the ESP8266, that just subscribes to another feed, and will act on a relay depending on this feed.

Both devices works fine on their own, but I had problems when I put them both together: I can't get the whole project working. I confirmed that by plugging the Arduino first, watching the Serial monitor, and then powering the ESP8266: both just can't keep the MQTT connection open with Adafruit IO.

Is that something you already encountered before, or am I doing something wrong? Thanks!

WDT Soft Reset when Not using SSL (port 1883)

Ok, this is really weird but I'm able to reproduce this....

I'm porting code from using the PubSubClient library to this library. As you can imagine I had a few incompatibility issues. Nonetheless, I pressed on and but I was foxed with this one issue and couldn't figure out what I was doing wrong. So eventually, I use one of the Example sketches in order to provide a minimum reproducible case.

`// This example uses an Adafruit Huzzah ESP8266
// to connect to shiftr.io.
//
// You can check on your device after a successful
// connection here: https://shiftr.io/try.
//
// by Joël Gähwiler
// https://github.com/256dpi/arduino-mqtt

include <ESP8266WiFi.h>

include <MQTTClient.h>

const char *ssid = "ssis";
const char *pass = "pass";

WiFiClientSecure net;
MQTTClient client;

unsigned long lastMillis = 0;

void connect(); // <- predefine connect() for setup()

void setup() {
Serial.begin(9600);
WiFi.begin(ssid, pass);
client.begin("iot.eclipse.org", 1883, net); // MQTT brokers usually use port 8883 for secure connections

connect();
}

void connect() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}

Serial.print("\nconnecting...");
while (!client.connect("arduino")) {
Serial.print(".");
}

Serial.println("\nconnected!");

client.subscribe("/example");
// client.unsubscribe("/example");
}

void loop() {
client.loop();
delay(10); // <- fixes some issues with WiFi stability

if(!client.connected()) {
connect();
}

// publish a message roughly every second.
if(millis() - lastMillis > 1000) {
lastMillis = millis();
client.publish("/hello", "world");
}
}

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 changes I've made are:

  1. I'm not using SSL, so I've changed the port to 1883
  2. I'm using iot.eclispe.org as the MQTT broker
  3. I'm using the connect method's overload that takes just the clientId parameter.

Now I have other cases (different code) where when I use a clientId of "NestEyeESP8266", I get the same soft WDT reset. However, if I change the clientId to "NestEyeESP826" or "NestEyeESP82A66" everything works as expected. I don't mind sharing this code privately if needed.

No reconnection

If there is a failure or to perform a manual reset on the sim800 pin reset, the module is not reconnected, and enters an infinite loop...

Connection failed
---> AT+CIPSTATUS
<--- AT+CIPSTATUS
---> AT+CIPCLOSE
<--- AT+CIPCLOSE
---> AT+CIPSHUT
<--- AT+CIPSHUT
Connection failed
---> AT+CIPSTATUS
<--- AT+CIPSTATUS
---> AT+CIPCLOSE
<--- AT+CIPCLOSE
---> AT+CIPSHUT
<--- AT+CIPSHUT
.............

Watchdog is enabled, but the restart is not happening in this cycle. Elsewhere delay reset works fine.

Last will message qos & retention examples

I'm attempting to add a last will message with retention but i can't seem to be able to find any example.

The retain flag can presumably be added by using :
mqtt.will("sweethome/sensors/status", "Disconnected", 0, 1); // where parameters are presumably "topic","message", Qos, retain`

Should QOS 1 then be set by
mqtt.will("sweethome/sensors/status", "Disconnected", 1, 0); // where parameters are presumably "topic","message", Qos, retain`
?

Issues with Multiple Subscriptions

Please see my Adafruit forum post for more:
https://forums.adafruit.com/viewtopic.php?f=56&t=96262&p=483586

I have 2 toggle switches in my dashboard. The first switch works as expected, but the second seems to send the ON or OFF message TWICE with a split second time between.

The Arduino MQTT Library reads ON and OFF correctly as the first subscribed topic, however, the second subscription is getting ON1 or OFF1 from the second toggle switch subscription. If I test in MQTT.fx the second toggle does indeed send the same message twice.

For example, I toggle ON, and ON is sent once at: 14-05-2016__03/53/25.14005532
then again almost instantly at: 14-05-2016__03/53/25.14005533

In the arduino serial monitor, not only does it add the 1 to the OFF / ON being sent, but it also adds blank characters. (I finally discovered this by serial printing the char count of the received message) so for example, OFF1 was reporting 5 characters and not the expected 4. That's when I realised that there is the ESCAPE character ( \x1B ) being sent after ON1, and \x1C being sent after OFF1.

That finally explains why my 0 == strcmp was failing even when I had what I though was being returned - strcmp(OFF1,OFF1).

Issue working with Interrupts. Reseting

Exception (9):
epc1=0x40104fd0 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000003 depc=0x00000000

ctx: sys
sp: 3ffffbf0 end: 3fffffb0 offset: 01a0

stack>>>
3ffffd90: 3fff061c 3fff0cc4 00100400 3fff0c94
3ffffda0: 401051fc 019789c5 3ffeec48 00000000
3ffffdb0: 3ffedd20 3ffeec48 3fff0d24 0000001f
3ffffdc0: 00000000 017fb241 40201098 00001388
3ffffdd0: 3ffeec48 00000000 00000001 0000000b
3ffffde0: 00000000 0000000b 3fff0c6c 402026b6
3ffffdf0: 3ffeeb3c 0000000b 00000000 402026e0
3ffffe00: 3ffe83b8 3ffefe9c 3ffe9478 4020397d
3ffffe10: 3ffeeb5e 3ffed6d0 3ffffed0 00000001
3ffffe20: 00000000 3ffeeb5e 3ffeeb3c 40202d1c
3ffffe30: e0033025 3ffeeb3c 00000000 40202d9c
3ffffe40: 4022f888 3ffe83b8 4020fc0d 3ffffed0
3ffffe50: 0034694d 0000000e 00000000 40202f0a
3ffffe60: 7fffffff 3ffe93a0 3ffe93a0 40201c0f
3ffffe70: 40106988 0000002c 00000008 401069d6
3ffffe80: ffffffff 00000020 3ffefeb4 00000000
3ffffe90: 00000000 00000000 0000001f 00000022
3ffffea0: 3fffc200 40106950 3fffc258 4000050c
3ffffeb0: 40000f68 00000030 00000011 ffffffff
3ffffec0: 40000f58 00000000 00000020 00000000
3ffffed0: 00000007 40201010 3ffe8954 00000003
3ffffee0: 00000009 3ffed584 3ffe8954 3fffdab0
3ffffef0: 00000000 3fffdcb0 3ffedd40 00000030
3fffff00: 00000000 00000000 3ffe9446 3ffe9490
3fffff10: 401051fc 0180268f 3ffe8954 00000000
3fffff20: 3ffedd20 3ffe8954 00000036 00000000
3fffff30: 00000000 017fac7d 40204dcf 3ffe8954
3fffff40: 3ffedd20 04cc24ba 60000600 00000001
3fffff50: 40204e38 3ffe8954 3ffedd20 04cc24ba
3fffff60: 40104f6e 017fb6aa 40205853 40201018
3fffff70: 40219c68 3ffeec48 3ffedd20 04cc24ba
3fffff80: 40219c8e 3fffdab0 00000000 3fffdcb0
3fffff90: 3ffedd40 3fffdad0 3ffeed30 402034ff
3fffffa0: 40000f49 40000f49 3fffdab0 40000f49
<<<stack<<<

ets Jan 8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1264, room 16
tail 0
chksum 0x0f
csum 0x0f
~ld

So what should i do to use interrupts?
I was integrating this interrupt code with your MQTT ESP8266 example and code was like this:

/***************************************************
Adafruit MQTT Library ESP8266 Example

Must use ESP8266 Arduino from:
https://github.com/esp8266/Arduino

Works great with Adafruit's Huzzah ESP board & Feather
----> https://www.adafruit.com/product/2471
----> https://www.adafruit.com/products/2821

Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!

Written by Tony DiCola for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/

include <ESP8266WiFi.h>

include "Adafruit_MQTT.h"

include "Adafruit_MQTT_Client.h"

/************************* WiFi Access Point *********************************/

define WLAN_SSID "ssid"

define WLAN_PASS "psk"

/************************* Adafruit.io Setup *********************************/

define AIO_SERVER "192.168.43.14"

define AIO_SERVERPORT 1883 // use 8883 for SSL

define AIO_USERNAME ""

define AIO_KEY ""

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM = AIO_KEY;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);

/****************************** Feeds ***************************************/

// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: /feeds/
const char PHOTOCELL_FEED[] PROGMEM = AIO_USERNAME "test";
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, PHOTOCELL_FEED);

// Setup a feed called 'onoff' for subscribing to changes.
const char ONOFF_FEED[] PROGMEM = AIO_USERNAME "onoff";
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, ONOFF_FEED);

/*************************** Sketch Code ************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

void Reset()
{
photocell.publish("hii");
}

void setup() {
Serial.begin(115200);
delay(10);

Serial.println(F("Adafruit MQTT demo"));

// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();

Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());

// Setup MQTT subscription for onoff feed.
mqtt.subscribe(&onoffbutton);
pinMode(D5, INPUT_PULLUP);
attachInterrupt(D5, Reset, FALLING);

}

uint32_t x=0;

void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();

// this is our 'wait for incoming subscription packets' busy subloop
// try to spend your time here

Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(5000))) {
if (subscription == &onoffbutton) {
Serial.print(F("Got: "));
Serial.println((char *)onoffbutton.lastread);
}
}

// Now we can publish stuff!
Serial.print(F("\nSending photocell val "));
Serial.print(x);
Serial.print("...");
// if (! photocell.publish(x++)) {
// Serial.println(F("Failed"));
// } else {
// Serial.println(F("OK!"));
// }

// ping the server to keep the mqtt connection alive
// NOT required if you are publishing once every KEEPALIVE seconds
/*
if(! mqtt.ping()) {
mqtt.disconnect();
}
*/
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;

// Stop if already connected.
if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT... ");

uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}

  • Arduino board: NodeMCU
  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.6.9

Issues with MQTT Failed to Subscribe using Mosquitto 1.4.7

There is an issue subscribing to MQTT topics using the Adafruit MQTT Library across Bridge on the Arduino Yun.

I have isolated the line of troublesome code down to line 248 of Adafruit_MQTT.cpp, inside of Adafruit_MQTT::readFullPacket

if (multiplier > 128*128*128) { DEBUG_PRINT(F("Malformed packet len\n")); return 0; }

Activating the debug mode and adding an additional PRINT statement reveals that the value of multiplier is 128 when the code fails and returns, which doesnt seem to make a whole lot of sense, as this code should not run in that case.

Commenting this block out has resolved the issue.

Retained messages

Hello,

Thanks for a great library. It has been running great for quite a while, but I have recently run into a problem.

I have several topics with retained messages. As long as I only subscribe to one topic at a time everything is working fine. If I however subscribe to two topics (both with retained messages) the second topic will experience a "Failed to subscribe" during connect().

Is this known?

Thanks again for all the work that has went into this library.

MQTT library to node-red instead of adafruit i/o

Can anyone provide suggestions about how one could use the esp8266 examples but instead use a local node-red mqtt/mosquitto broker instead of adafruit io. My setup needs to be stand-alone.

Could it be as simple as pointing to the local node-red address instead of io.adafruit.com in the AIO_SERVER definition?

Thanks for any advice,
Chris.

Configurable SUBSCRIPTIONDATALEN

Setting in the library:

#define SUBSCRIPTIONDATALEN 20

means the data length cannot be increased without having to modify the Adafruit_MQTT.h file.

Would it be possible to make that configurable, either by passing the value in the constructor or preventing redefinition of SUBSCRIPTIONDATALEN if it is already defined?

Default client ID set by examples is truncated to non-unique value

We noticed when running two instances of an example that they're colliding over the same client ID. Right now the logic is to concat AIO key + compile date & time to get a unique value for the user, however if two examples compiled on the same day run then one of them will knock the other off the broker. Likely the client ID is being truncated on the server side and only the first xx chars are being used (before the date). Let's consider a quick fix to swap the order so date and time come first and then AIO key, and a longer term fix to make this more robust on the server side.

io.adafruit.com SSL Certificate Expiry

Please consider using a self-signed cert for MQTTS. The current third-party io.adafruit.com cert is going to expire on July 2017.
Due to limitations, cert fingerprint needs to be hard-coded in the microcontroller (for cert verification to work) and therefore it needs update everytime io.adafruit.com cert is re-issued . This is unreasonable for IoT devices.

Not authorized MQTT connection related to //#define MQTT_DEBUG

  • Arduino board: UNO R3 SMD and FONA800
  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.6.9 (programming via Visual Studio/vMicro)
  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too):

Attempting to connect to io.adafruit.com via MQTT on port 1883 using a FONA 800. Receive "Not authorized to connect" response.

In attempting to find the source of this problem I uncommented #define MQTT_DEBUG in line 37 of Adafruit_MQTT.h. I was then able to connect. Recommenting it prevented connection, so I am confident this is the source of the problem.

Please would you investigate and fix this problem? I'm afraid my c++ skills are not up to the job.

Thanks

Dynamic group names

I'm trying to use the MQTT library with the adafruit IO service, though it could be used anywhere. I need to group my feeds by device, and, therefore, I need unique group names to keep all of the feeds separate. I do this by pulling a serial number from a flash chip and appending it to a common group name. The problem is that PROGMEM doesn't like variables and your library forces me to store the group name in PROGMEM. How can I create a group name made up of a constant and a variable so I don't have to manually insert a serial number and upload separate code to 100000 devices?

Please see this thread for more information: https://forums.adafruit.com/viewtopic.php?f=56&t=83145&p=420493

Publish data value with a historical timestamp?

Hi there,

I'm combining a Huzzah esp8266 with a HDC1008 and a photoresistor.

WiFi uses lots of battery so my hope was to be able to store on the esp8266 a series of data points with timestamps and then when the memory was running low or the chip's battery voltage appears to be dropping too low, publish the data points with their historical timestamps to Adafruit IO feeds.

Publish() seems to only take one value. Is there any way to do what I'm describing?

Please provide a library.json for platformio

It would be nice if a library.json for platformio could be included.

platformio currently finds the following Adafruit libraries:

$> pio lib search adafruit
Found 37 libraries:

[ ID  ] Name             Compatibility         "Authors": Description
--------------------------------------------------------------------------------
[ 12  ] Adafruit-ST7735  arduino, atmelavr     "Adafruit Industries": A library for the Adafruit 1.8" SPI display
[ 14  ] Adafruit-9DOF-Unified arduino, atmelavr     "Adafruit Industries": Unified sensor driver for the Adafruit 9DOF Breakout (L3GD20 / LSM303)
[ 16  ] Adafruit-BMP085-Unified arduino, atmelavr     "Adafruit Industries": Unified sensor driver for Adafruit's BMP085 & BMP180 breakouts (Barometric Pressure Sensor)
[ 22  ] Adafruit-HX8357  arduino, atmelavr     "Adafruit Industries": A library for the Adafruit HX8357 SPI display
[ 24  ] Adafruit-L3GD20  arduino, atmelavr     "Adafruit Industries": Driver for Adafruit's L3GD20 I2C Gyroscope Breakout
[ 26  ] Adafruit-LSM303DLHC-Unified arduino, atmelavr     "Adafruit Industries": Unified sensor driver for Adafruit's LSM303 Breakout (Accelerometer + Magnetometer)
[ 27  ] Adafruit-Motor-Shield arduino, atmelavr     "Adafruit Industries": Adafruit Motor shield V1 firmware with basic Microstepping support
[ 30  ] Adafruit-PWM-Servo arduino, atmelavr     "Adafruit Industries": A library for Adafruit 16-channel PWM & Servo driver
[ 31  ] Adafruit-Unified-Sensor arduino, atmelavr     "Adafruit Industries": Adafruit Unified Sensor Driver
[ 33  ] Adafruit-TMP006  arduino, atmelavr     "Adafruit Industries": A library for the Adafruit TMP006 Infrared Thermopile Sensor

Sending JSON with Adafruit Publish

I am trying to send JSON trough to my adafruit feed. I feel like this is blocked.

components_feed.publish(output.c_str()); // Some valid json string
components_feed.publish("Hi");
components_feed.publish("{ \ "hi\ ":\ "test\ "}");

OUTPUT:

2017-05-08 05:36:05 pm components: Hi
2017-05-08 05:36:05 pm errors: failed to publish value: data missing required value
2017-05-08 05:36:06 pm errors: failed to publish value: data missing required value

Am I doing anything wrong?

  • Arduino board: ESP 8266 12-F NodeMCU

  • Arduino IDE version (found in Arduino -> About Arduino menu): Windows Store 1.8.3.0

Issue with Feather Huzza

Hi and thanks for this great lib

Regarding Adafruit_MQTT::readSubscription, and IDE 1.6.9
I'm using feather huzza. and CloudMQTT to send GPS data

IDE ver Adafruit_MQTT::readSubscription

I have notice that I get response from this function only in rare cases:

I dig down with DEBUD_MTQQ and notices that topiclen offset is sometimes different from 3.

sometimes the vlaue is 4 somethimes smaller than 3. have you noticed this issue? when this happen ofcourse the function cannot parse further.

I checked the data from the server using websocket UI and its all correct.

BTW I had to enlarge SUBSCRIPTIONDATALEN and MAXBUFFERSIZE as the messge that comes from CloudMQTT somethimes is >125B length.

Allow new subscriptions after connect

Hi,
Looking at the source of Adafruit_MQTT::connect(), I see that it's the only place where the actual subscription is being performed.

I would like to be able to subscribe to topics after connection too, like unsubscribe.

I'm using this library with an Adafruit Fona.

Duplicate messages received by Adafruit MQTT Library and ESP8266

I'm using the ESP8266 with the Arduino IDE and this Adafruit MQTT Library and receiving duplicate messages.

After subscribing to a topic and receiving the first correct message, the MQTT library then receives extra messages which are duplicates of the first real message. The last time I tested there were 6 duplicates over a 45 minute period.

THE MQTT sub loop is from the Adafruit example code in mqtt_esp8266.ino:

// this is our 'wait for incoming subscription packets' busy subloop
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(1000))) {
if (subscription == &onoffbutton) {
Serial.print(F("Got: "));
Serial.println((char *)onoffbutton.lastread);
}
}

I tried this same test with three different MQTT brokers (test.mosquitto.org, cloudmqtt.com, and my own server running Ponte), and the problem appears with each of the brokers.

I tried two other MQTT clients (nodemcu and Debian mosquitto_sub) against the cloudmqtt.com and ponte brokers, and the problem does NOT appear.

connecting to mqtt failed (after requesting DHCP failed)

Hi,

I have a big problem with cc3000 wifi shield.
I succeed connect to wifi network but when I am trying connect to mqtt by the library - it failed.

mqtt error

before the connection failed I have problem with the IP address (request DHCP) as you can see it here.
If I run web client of adafruit cc3000, I can connect to wifi and do GET http and all is good.

please tell me what is wrong and what I can do.

Thanks.

mqtt.connect() throws Exception (3) rst cause:2, boot mode:(1,6)

Hi,

I'm using my good old Adafruit Huzzah ESP8266 to connect to a mqtt broker via wifi.
The strange thing is, it used to work! But i left the project alone for 3 - 4 months, and
after coming back / updating the Arduino IDE to 1.6.6 it stopped working.
The mqtt.connect suddenly throws the exception below.
Anything changed on the Adafruit Mqtt end? I now use Adafruit MQTT Libray 0.16.2
Maybe i need to update the firmware on the ESP8266 ?

Connecting to MQTT... 

Exception (3):
epc1=0x4000bf3c epc2=0x00000000 epc3=0x00000000 excvaddr=0x402341ec depc=0x00000000

ctx: cont 
sp: 3fff0440 end: 3fff0660 offset: 01a0

>>>stack>>>
3fff05e0:  3fffdad0 0000001c 3ffef578 4020654d  
3fff05f0:  3ffe88c1 3ffeeab8 3ffeeab8 402060ce  
3fff0600:  3ffe85e5 00000000 3ffef578 40206578  
3fff0610:  3ffeea78 3ffeea7c 3ffef578 3ffef634  
3fff0620:  00000003 3ffeeab8 3ffef578 40202690  
3fff0630:  3fffdad0 00000000 3ffef62c 402026cd  
3fff0640:  3fffdad0 00000000 3ffef62c 40207074  
3fff0650:  feefeffe feefeffe 3ffef640 40100718  
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)


 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

This is my sketch

/**
   Get temperature and humidity from DHT-11 sensor (every xx-seconds) and publish it to an MQTT topic via wifi.
   @Author: Rino van Wijngaarden
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <DHT.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#define WLAN_SSID         "<ssid_here>"
#define WLAN_PASS         "<password_here>"
#define MQTT_MY_SERVER    "<ip_of_mqtt_broker_here>""
#define MQTT_SERVERPORT  1883
#define MQTT_MY_USERNAME    ""
#define MQTT_MY_PASSWORD    ""
#define DHTTYPE DHT11
#define DHTPIN  2

// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char PROGMEM MQTT_SERVER[]  = MQTT_MY_SERVER;
const char PROGMEM MQTT_USERNAME[] = MQTT_MY_USERNAME;
const char PROGMEM MQTT_PASSWORD[] = MQTT_MY_PASSWORD;
const char PROGMEM MQTT_DHT11_TEMP_FEED[] = "/home/bg/tuinhuis/temperature";
const char PROGMEM MQTT_DHT11_HUMIDITY_FEED[] = "/home/bg/tuinhuis/humidity";
const char PROGMEM MQTT_BATTERY_VOLTAGE_FEED[] = "/home/bg/tuinhuis/battery";

// ADC_MODE(ADC_VCC);
WiFiClient wifiClient;
Adafruit_MQTT_Client mqtt(&wifiClient, MQTT_SERVER, MQTT_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);
Adafruit_MQTT_Publish dht11TempPublish = Adafruit_MQTT_Publish(&mqtt, MQTT_DHT11_TEMP_FEED);
Adafruit_MQTT_Publish dht11HumidityPublish = Adafruit_MQTT_Publish(&mqtt, MQTT_DHT11_HUMIDITY_FEED);
Adafruit_MQTT_Publish batteryVoltagePublish = Adafruit_MQTT_Publish(&mqtt, MQTT_BATTERY_VOLTAGE_FEED);

// Initialize DHT sensor
// NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
// you need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// This is for the ESP8266 processor on ESP-01
DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266

void connectToMQTT();
void connectToWifi();
boolean getSensorData();
void publishDataToMQTT();

float humidity, tempC, hic;  // Values read from sensor
float voltage;
String webString = "";   // String to display
// Generally, you should use "unsigned long" for variables that hold time
unsigned long dhtPreviousMillis = 0;        // will store last temp was read
const long dhtInterval = 2000;              // interval at which to read sensor


void setup(void)
{  
  // You can open the Arduino IDE Serial Monitor window to see what the code is doing
  Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable
  delay(2);
  dht.begin();           // initialize temperature sensor
  connectToWifi();
}

void loop(void)
{
  if (getSensorData()) {
    // Ensure the connection to the MQTT server is alive (this will make the first
    // connection and automatically reconnect when disconnected).
    connectToMQTT();

    publishDataToMQTT();
    
    Serial.print("Publish done. Sleeping now");
    ESP.deepSleep(60000000, WAKE_RF_DEFAULT); // Sleep for 60 seconds// note:  (GPIO16 needs to be tied to RST (and 5v) to wake from deepSleep.)
  }

}


void publishDataToMQTT()  {
  if (mqtt.connected()) {
    Serial.print("Trying to publish data to mqtt ...");
    if (!batteryVoltagePublish.publish(voltage)) {
      Serial.println(F("Publish to mqtt/battery failed"));
    } else {
      if (!dht11TempPublish.publish(hic)) {
        Serial.println(F("Publish to mqtt/temp failed"));
      } else {
        if (!dht11HumidityPublish.publish(humidity)) {
          Serial.println(F("Publish to mqtt/humidity failed"));
        }
      }
    }
  }
}

boolean getSensorData() {
  // Wait at least 2 seconds seconds between measurements.
  // if the difference between the current time and last time you read
  // the sensor is bigger than the interval you set, read the sensor
  // Works better than delay for things happening elsewhere also
  unsigned long currentMillis = millis();

  if (currentMillis - dhtPreviousMillis >= dhtInterval) {
    // save the last time you read the sensor
    dhtPreviousMillis = currentMillis;

    // Reading temperature for humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
    humidity = dht.readHumidity();          // Read humidity (percent)
    tempC = dht.readTemperature(false);     // Read temperature as Celsius
    // Check if any reads failed and exit early (to try again).
    if (isnan(humidity) || isnan(tempC)) {
      Serial.println("Failed to read from DHT sensor!");
      return false;
    }
    // Compute heat index in Celsius (isFahreheit = false)
    hic = dht.computeHeatIndex(tempC, humidity, false);

    voltage = (ESP.getVcc()) / 1000.0;
    return true;
  }
  return false;
}


void connectToWifi(void) {
  // Connect to WiFi network
  WiFi.persistent(false);
  WiFi.disconnect(true);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
  Serial.print("\n\r \n\rConnecting to wifi ....");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(WLAN_SSID);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void connectToMQTT() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    Serial.print("Already connected to MQTT");
    return;
  }

  Serial.print("Connecting to MQTT... ");
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);
    retries--;
    if (retries == 0) {
       // basically die and wait for WDT to reset me
       while (1);
    }           
    if (WiFi.status() != WL_CONNECTED) {
      connectToWifi();
    }
  }
  Serial.println("MQTT Connected!");
}

MOVED: getting compiler error with CC3000 & Arduino Uno & MQTT Library, can't get connected to Adafruit IO site

@mtneco48

Have used cc3000 before many times, and have reviewed CC3000 shield startup again today. All of my example CC3000 programs work with the CC3000 wifi and make connections to sites functioning properly, but when I try to run the Adafruit IO Basics: Digital Outputs to get familiarized with the new system and software, I am running into a problem with a compiler error using the prescribed Adafruit IO Basic Sketches/Adafruit CC3000/digital_output.ino and the loading the 3 required libraries(CC3000, MQTT and SleepyDog) .

Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
COMPILER ERROR CODE RECEIVED:

digital_out.cpp.o: In function connect()': C:\Program Files (x86)\Arduino/digital_out.ino:162: undefined reference toCC3000connect(char const, char const, unsigned char)'
digital_out.cpp.o: In function setup': C:\Program Files (x86)\Arduino/digital_out.ino:95: undefined reference toCC3000connect(char const, char const, unsigned char)'

When I run the example, mqtt_cc3k.ino, in the MQTT Library , the cc3000 says that it makes a connection to the router, but can not get a DHCP and keeps resetting.

OUTPUT Dialog:

Adafruit MQTT demo
Free RAM: 865

Init the CC3000...Firmware V. : 1.24

Deleting old connection profiles

Attempting to connect to Wasted48...Connected!
Requesting DHCP
Retrying WiFi
Firmware V. : 1.24

Deleting old connection profiles

Attempting to connect to Wasted48...Connected!
Requesting DHCP
Retrying WiFi
Firmware V. : 1.24

Deleting old connection profiles

Attempting to connect to Wasted48...Connected!
Requesting DHCP
Retrying WiFi
Firmware V. : 1.24

Deleting old connection profiles

Attempting to connect to Wasted48...Connected!
Requesting DHCP
Retrying WiFi
Firmware V. : 1.24

Deleting old connection profiles

What is the correct CC3000 firmware version and driverpatch version are working with the cc3000 to make the connection to Adafruit IO? I have reloaded my CC3000 Library and it still does not work? I went back to the older version of the Arduino IDE 1.0.6 and that doesn't help???
ANY THING ELSE I SHOULD BE TRYING??

subscription problem using readSubscription function (SOLVED)

I'm using a nodeMCU board and I tried to subscribe a MQTT topic by using the "readSubscription" function from this library. Everything works fine if the mqtt packet length does not exceed 127 byte. In case of longer packet I got NULL from the function. Debugging the readSubscription function I saw that it looks for the topic length (the topiclen variable) into the forth cell of the array, called "buffer", (buffer[3]). It is like this only if the packet lenght is less than 127 byte. Whereas if it is longer, the mqtt broker adds further bytes to code the overall packet lenght, so that the "topiclen" field is no more in the forth cell of the acquired "buffer" but it results in one of the next cells of the array. To solve this problem I made some changes in the readFullPacket function that is called by the readSubscription function to acquire the new packet from the mqtt broker.
This is the code of the function:

uint16_t Adafruit_MQTT::readFullPacket(uint8_t * buffer, uint16_t maxsize, uint16_t timeout) {
// will read a packet and Do The Right Thing with length
uint8_t * pbuff = buffer;
uint8_t rlen;
// read the packet type:
rlen = readPacket(pbuff, 1, timeout);
if (rlen != 1) return 0;
DEBUG_PRINT(F("Packet Type:\t")); DEBUG_PRINTBUFFER(pbuff, rlen);
pbuff++;

uint32_t value = 0;
uint32_t multiplier = 1;
uint8_t encodedByte;

do {
rlen = readPacket(pbuff, 1, timeout);
if (rlen != 1) return 0;
encodedByte = pbuff[0]; // save the last read val
pbuff++; // get ready for reading the next byte
uint32_t intermediate = encodedByte & 0x7F;
intermediate * = multiplier;
value + = intermediate;
multiplier * = 128;
if (multiplier > (128UL * 128UL * 128UL)) {
DEBUG_PRINT(F("Malformed packet len\n"));
return 0;
}
} while (encodedByte & 0x80);

DEBUG_PRINT(F("Packet Length:\t")); DEBUG_PRINTLN(value);

if (multiplier == (128UL * 128UL)) pbuff --;
else if (multiplier == (128UL * 128UL * 128UL)) pbuff -=2;

if (value > (maxsize - (pbuff-buffer) - 1)) {
DEBUG_PRINTLN(F("Packet too big for buffer"));
rlen = readPacket(pbuff, (maxsize - (pbuff-buffer) - 1), timeout);
} else {
rlen = readPacket(pbuff, value, timeout);
}
//DEBUG_PRINT(F("Remaining packet:\t")); DEBUG_PRINTBUFFER(pbuff, rlen);

return ((pbuff - buffer)+rlen);
}

The lines I added are the two lines in bold italic. In other words I overwrite the extra bytes that the mqtt broker adds to code the packet lenght so that the packet header keep always the same lenght and the "topiclen" field is always in the forth cell of the buffer (buffer[3]). This is possible since the overall packet length is one of the output of the readSubscription function and thus it has not to be recomputed.

In this way it works even if the packet is longer than 127 bytes.

Support connecting to AWS IoT with Fona

I bought 2 Feathers M0 RFM69 and a Fona 808 breakout to send data to the AWS IoT, just to discover that it can't actually connect to AWS :-(
Before buying I've seen that it has MQTT support, but I didn't think there was anything special required for AWS.
Not sure what to do now, if there's any chance for this to happen or if I should just return the Fona and look for another solution.

Support Retain for Publish

One useful pattern to track device up/down status is to have a will set to .../status with value '0' and retain, and when the device comes up to publish to the .../status with value '1' with retain. The retain allows the status to be interrogated at anytime by a client. The library has retain flag for will, but not for publish. Of course, it would be useful for lots of other things too, but thought I would point out one very valuable one...

Adafruit_SleepyDog.h No such file or directory

Tried running this via the compiler from arduino.org on a macintosh El Capitan, and get this error for the mqtt_cc3k example. Note, the chip works perfectly using the buildtest from the CC3000 breakout board's library:

cc3000helper.cpp:1:32: fatal error: Adafruit_SleepyDog.h: No such file or directory
#include <Adafruit_SleepyDog.h>
^
compilation terminated.
Error compiling.

Unable to compile mqtt_esp8266 example.

When I try to compile, I get the following error. I am using the latest Arduino IDE (1.6.5) as well as the latest versions of the libraries. (Adafruit IO - 1.0.0, Adafruit MQTT Library - 0.10.0)

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

Adafruit MQTT Library\Adafruit_MQTT.cpp.o:(.text+0x0): undefined reference to strnlen_P' Adafruit MQTT Library\Adafruit_MQTT.cpp.o:(.text+0x4): undefined reference tostrncpy_P'
Adafruit MQTT Library\Adafruit_MQTT.cpp.o: In function stringprint_P(unsigned char*, char const*, unsigned short)': Adafruit_MQTT.cpp:(.text+0x22): undefined reference tostrnlen_P'
Adafruit_MQTT.cpp:(.text+0x42): undefined reference to strncpy_P' Adafruit MQTT Library\Adafruit_MQTT.cpp.o: In functionAdafruit_MQTT::subscribe(Adafruit_MQTT_Subscribe*)':
Adafruit_MQTT.cpp:(.text+0xfc): undefined reference to strncasecmp_P' Adafruit MQTT Library\Adafruit_MQTT.cpp.o: In functionAdafruit_MQTT::readSubscription(short)':
Adafruit_MQTT.cpp:(.text+0x156): undefined reference to strnlen_P' Adafruit_MQTT.cpp:(.text+0x16a): undefined reference tostrncasecmp_P'
collect2.exe: error: ld returned 1 exit status
Error compiling.

This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.

Allow Anonymous Auth

Currently this lib requires a MQTT username and pass to connect to a server. It would be good to support non-authenticated connections too for subscribing to public AIO feeds.

Packet size limited to 127 bytes in connect and subscribe

  • Arduino board: Feather Huzzah

  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.8.0

  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too):

I'm experiencing this same issue:

#17 (comment)

This issue is in byte 2 of the packet:

https://github.com/adafruit/Adafruit_MQTT_Library/blob/master/Adafruit_MQTT.cpp#L628

The variable length encoding scheme uses a single byte for messages up to 127 bytes long. Longer messages are handled as follows. Seven bits of each byte encode the Remaining Length data, and the eighth bit indicates any following bytes in the representation. Each byte encodes 128 values and a "continuation bit". For example, the number 64 decimal is encoded as a single byte, decimal value 64, hex 0x40. The number 321 decimal (= 65 + 2*128) is encoded as two bytes, least significant first. The first byte 65+128 = 193. Note that the top bit is set to indicate at least one following byte. The second byte is 2.

This issue was fixed in Publish ( in issue #17), but not in Connect or Subscribe. In both you are limited to 127 bytes.

No been able to publish into adafruit IO using ESP8266

Hello,

I'm using ESP8266 ESP07 and I can't seem do be able to publish on my feed. I am able to receive data from the feed. On the serial port it say's it was successfully publish, but nothing appears on the IO page:

Sending photocell val 300...OK!

Sending photocell val 301...OK!

Sending photocell val 302...OK!

Sending photocell val 303...OK!

At the IO page the following error is displayed:

2015-12-22 19:34:43 - ERROR - feed photocell: undefined method `feeds' for nil:NilClass

What is the problem?

0.16 broke my ESP8266 app

Thank you for opening an issue on an Adafruit Arduino library repository. To
improve the speed of resolution please review the following guidelines and
common troubleshooting steps below before creating the issue:

  • Do not use GitHub issues for troubleshooting projects and issues. Instead use
    the forums at http://forums.adafruit.com to ask questions and troubleshoot why
    something isn't working as expected. In many cases the problem is a common issue
    that you will more quickly receive help from the forum community. GitHub issues
    are meant for known defects in the code. If you don't know if there is a defect
    in the code then start with troubleshooting on the forum first.
  • If following a tutorial or guide be sure you didn't miss a step. Carefully
    check all of the steps and commands to run have been followed. Consult the
    forum if you're unsure or have questions about steps in a guide/tutorial.
  • For Arduino projects check these very common issues to ensure they don't apply:
    • For uploading sketches or communicating with the board make sure you're using
      a USB data cable and not a USB charge-only cable. It is sometimes
      very hard to tell the difference between a data and charge cable! Try using the
      cable with other devices or swapping to another cable to confirm it is not
      the problem.
    • Be sure you are supplying adequate power to the board. Check the specs of
      your board and plug in an external power supply. In many cases just
      plugging a board into your computer is not enough to power it and other
      peripherals.
    • Double check all soldering joints and connections. Flakey connections
      cause many mysterious problems. See the guide to excellent soldering for examples of good solder joints.
    • Ensure you are using an official Arduino or Adafruit board. We can't
      guarantee a clone board will have the same functionality and work as expected
      with this code and don't support them.

If you're sure this issue is a defect in the code and checked the steps above
please fill in the following fields to provide enough troubleshooting information.
You may delete the guideline and text above to just leave the following details:

  • Arduino board: Feather HUZZAH
  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.6.9
  • List the steps to reproduce the problem below (if possible attach a sketch or
    copy the sketch code in too): LIST REPRO STEPS BELOW

Sketch resets during setup in call to ConnectAdafruitMQTT();
Reverting to 0.15 fixes the problem
Foundry_Temperature_v4.zip

Multiple ESP8266 - Adafruit Huzzah

Both of my feeds on two different PCs were down each of the last two Fridays. Checking in on Saturdays in the PMs, both times they had not recovered. The guages show a read that hasn't moved since I saw them Friday, and the charts say "no data." I reset one of my devices to see if it made any difference... And yes it did, but looking in the IDE (I got tired of trying to compile under IDE 1.6.6 with no luck)

The IDE Serial monitor read:
"Failed to publish temperature.
Failed to publish humidity"

I am running just the stock standard Huzzah ESP8266 connected to a DHT22... all vanilla and hooked, from the project posting on the main Adafruit website for the Huzzah. They are connected to PC for power. All seems to check out from my end.

What I learned is that when one started working, it kicked the other off Adafruit.io. So only one works at a time. They were fine for nearly 2 months before the last 2 weekends without a glitch.
I am operating with the load from IDE 1.6.5 which compiles fines without a glitch (unlike 1.6.6). ... All was fine but all of the sudden, the last two weeks have been really flakey.

Jwcooper suggested the upgrade to the new MQTT code, but that won't compile in IDE 1.6.5, and it's a lot to go through to put 1.6.6 if I am going to have the same problems (won't compile) as I had when I last had it installed over the weekend.

Thoughts??? BTW: We were working on this on another Adafruit.IO thread called "Is Adafruit.io Down?... you can get caught up here... https://forums.adafruit.com/viewtopic.php?f=56&t=83943

Subscribe to multiple feeds

The example code is meant to subscribe to multiple feeds of a slider and on/off button. It fails
with "Failed to subscribe"

include <ESP8266WiFi.h>

include "Adafruit_MQTT.h"

include "Adafruit_MQTT_Client.h"

/************************* WiFi Access Point *********************************/

define WLAN_SSID "******"

define WLAN_PASS "******"

/*******/
const int FAN_PIN = 13;
/**
* Adafruit.io Setup *********************************/

define AIO_SERVER "io.adafruit.com"

define AIO_SERVERPORT 1883

define AIO_USERNAME "*****"

define AIO_KEY "*****"

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;

// Store the MQTT server, client ID, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM = AIO_SERVER;
// Set a unique MQTT client ID using the AIO key + the date and time the sketch
// was compiled (so this should be unique across multiple devices for a user,
// alternatively you can manually set this to a GUID or other random value).
const char MQTT_CLIENTID[] PROGMEM = TIME AIO_USERNAME;
const char MQTT_USERNAME[] PROGMEM = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM = AIO_KEY;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_CLIENTID, MQTT_USERNAME, MQTT_PASSWORD);

/****************************** Feeds ***************************************/

// Setup a feed called 'onoff' for subscribing to changes.
const char ONOFF_FEED[] PROGMEM = AIO_USERNAME "/feeds/onoff";
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, ONOFF_FEED);

const char SLIDER_FEED[] PROGMEM = AIO_USERNAME "/feeds/slidel";
Adafruit_MQTT_Subscribe slider = Adafruit_MQTT_Subscribe(&mqtt, SLIDER_FEED);

/*************************** Sketch Code ************************************/

void setup() {
Serial.begin(115200);
delay(10);

Serial.println(F("Adafruit MQTT demo"));

pinMode(FAN_PIN, OUTPUT);

// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);

WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();

Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());

// Setup MQTT subscription for onoff feed.
mqtt.subscribe(&onoffbutton);
mqtt.subscribe(&slider);
}

void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();

// Try to ping the MQTT server
/*
if (! mqtt.ping(3) ) {
// MQTT pings failed, lets reconnect
Serial.println("Ping fail!");
}
*/

// this is our 'wait for incoming subscription packets' busy subloop
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(1000))) {
if (subscription == &onoffbutton) {
Serial.print(F("Got: "));
Serial.println((char *)onoffbutton.lastread);
}

}

delay(1000);
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;

// Stop if already connected.
if (mqtt.connected()) {
return;
}

Serial.print("Connecting to MQTT... ");

while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
}
Serial.println("MQTT Connected!");
}

Sending Float/Double values result in empty payload

When trying to send a float/double value (for example temperature), the payload on the subscriber is empty. Even though the library supports float/double values, it doesn't seem to work. Sending strings/chars work fine on the other hand.

Publishing to broker crashes the ESP8266

  • Arduino board: WeMos D1 Mini power over USB cable with a OLED (D1/D2 pins) and a DHT22 (D3 pin) attached
  • Arduino IDE version (found in Arduino -> About Arduino menu): 1.6.13
  • List the steps to reproduce the problem below (if possible attach a sketch or copy the sketch code in too):

When using Adafruit_MQTT_Library 0.16.0 or higher (working just fine with 0.15.0), the D1 crashes when publishing to MQTT broker (Mosquitto on a RPi).

Sketch attached with reduced code. Call stack and exception traced using Adafruit_MQTT_Libraryr 0.16.2.

D1Mini-BuggedMQTT.ino.txt

Call stack:
3ffef730: 3ffe86b8 1a00a8c0 3ffe86b8 1a00a8c0 3ffef740: 40230984 0000000c 00000003 4020376e 3ffef750: 346e776f 3ffee56a 3ffee548 40202ec8 3ffef760: feefeffe 3ffee56a 3ffee548 4020315a 3ffef770: 00000000 00000001 3ffe86bd 00000000 3ffef780: ffffffc0 0000001c 402307d5 3ffee7e4 3ffef790: 3fffdad0 3ffee548 3ffee728 40202070 3ffef7a0: 3ffe86bc 003fcebe 3ffee668 3ffee7e4 3ffef7b0: 3fffdad0 00000000 3ffee548 402020d4 3ffef7c0: 3fffdad0 00000000 3ffee728 3ffee7e4 3ffef7d0: 3fffdad0 00000000 3ffee7dc 40202162 3ffef7e0: 3fffdad0 00000000 3ffee7dc 4020217b 3ffef7f0: feefeffe 00000000 3ffee7dc 40203cb0 3ffef800: feefeffe feefeffe 3ffee7f0 40100718

ESP Exception Decoder output
Decoding 11 results 0x40230984: sleep_reset_analog_rtcreg_8266 at ?? line ? 0x4020376e: Print::print(unsigned long, int) at C:\Users\shut\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/Print.cpp line 64 0x40202ec8: Adafruit_MQTT::connectPacket(unsigned char*) at C:\Users\shut\Documents\Arduino\libraries\Adafruit_MQTT_Library/Adafruit_MQTT.cpp line 768 0x4020315a: Adafruit_MQTT::connect() at C:\Users\shut\Documents\Arduino\libraries\Adafruit_MQTT_Library/Adafruit_MQTT.cpp line 768 0x402307d5: sleep_reset_analog_rtcreg_8266 at ?? line ? 0x40202070: connect() at C:\Users\shut\Documents\Arduino\D1Mini-BuggedMQTT/D1Mini-BuggedMQTT.ino line 189 (discriminator 1) 0x402020d4: publishDHT() at C:\Users\shut\Documents\Arduino\D1Mini-BuggedMQTT/D1Mini-BuggedMQTT.ino line 175 0x40202162: loopDHT() at C:\Users\shut\Documents\Arduino\D1Mini-BuggedMQTT/D1Mini-BuggedMQTT.ino line 159 0x4020217b: loop at C:\Users\shut\Documents\Arduino\D1Mini-BuggedMQTT/D1Mini-BuggedMQTT.ino line 100 0x40203cb0: loop_wrapper at C:\Users\shut\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/core_esp8266_main.cpp line 56 0x40100718: cont_norm at C:\Users\shut\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\cores\esp8266/cont.S line 109

Probelms with Adafruit_MQTT_Publish::publish

The Adafruit_MQTT_Publish::publish(int32_t) and Adafruit_MQTT_Publish::publish(uint32_t i) already rollover after 32768 (because they use the itoa function).
The Adafruit_MQTT_Publish::publish(double f.... could potentially have a buffer problem (because of unsuffiient room for a terminating zero).

I think this will fix it:

bool Adafruit_MQTT_Publish::publish(int32_t i) {
  char payload[12];  // Need to technically hold int32 max: 10 digits, minus sign and terminating zero.
  ltoa(i, payload, 10); // // Changed itoa to ltoa, int32_t => long
  return mqtt->publish(topic, payload, qos);
}

bool Adafruit_MQTT_Publish::publish(double f, uint8_t precision) {
  char payload[41];  // Need to technically hold float max, 39 digits, minus sign and terminating zero.
  dtostrf(f, 0, precision, payload);
  return mqtt->publish(topic, payload, qos);
}

bool Adafruit_MQTT_Publish::publish(uint32_t i) {
  char payload[11];  // Need to technically hold uint32 max: 10 digits and terminating zero.
  ultoa(i, payload, 10); // Changed itoa to ultoa, uint32_t => unsigned long
  return mqtt->publish(topic, payload, qos);
}

Issue with Adafruit_MQTT_FONA.h

I update my Adafruit_MQTT library this morning and compile as few days ago. Now in my sketch I see this compiling error. I use SAMD21 for this!!!

cannot declare variable 'mqtt' to be of abstract type 'Adafruit_MQTT_FONA'

It referes to this line:

Adafruit_MQTT_FONA mqtt(&fona, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);

Is the same code I always use, I just "update" your library. Testing if I have something wrong I try to compile your mqtt_fona example include with the library, selecting Arduino UNO board, and I got the same error.

Something helpfull could be this errors with the library and debug redefinitions:

In file included from ~/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_fona/mqtt_fona.ino:23:0: ~/sketchbook/libraries/Adafruit_MQTT_Library/Adafruit_MQTT.h:45:0: warning: "DEBUG_PRINT" redefined [enabled by default] #define DEBUG_PRINT(...) {} ^ In file included from ~/sketchbook/libraries/Adafruit_FONA/Adafruit_FONA.h:22:0, from ~/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_fona/mqtt_fona.ino:22: ~/sketchbook/libraries/Adafruit_FONA/includes/platform/FONAPlatform.h:38:0: note: this is the location of the previous definition #define DEBUG_PRINT(...) ^ In file included from ~/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_fona/mqtt_fona.ino:23:0: ~/sketchbook/libraries/Adafruit_MQTT_Library/Adafruit_MQTT.h:46:0: warning: "DEBUG_PRINTLN" redefined [enabled by default] #define DEBUG_PRINTLN(...) {} ^ In file included from ~/sketchbook/libraries/Adafruit_FONA/Adafruit_FONA.h:22:0, from ~/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_fona/mqtt_fona.ino:22: ~/sketchbook/libraries/Adafruit_FONA/includes/platform/FONAPlatform.h:39:0: note: this is the location of the previous definition #define DEBUG_PRINTLN(...) ^ mqtt_fona:62: error: cannot declare variable 'mqtt' to be of abstract type 'Adafruit_MQTT_FONA' Adafruit_MQTT_FONA mqtt(&fona, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD); ^ In file included from ~/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_fona/mqtt_fona.ino:24:0: ~/sketchbook/libraries/Adafruit_MQTT_Library/Adafruit_MQTT_FONA.h:36:7: note: because the following virtual functions are pure within 'Adafruit_MQTT_FONA': class Adafruit_MQTT_FONA : public Adafruit_MQTT { ^ In file included from ~/sketchbook/libraries/Adafruit_MQTT_Library/examples/mqtt_fona/mqtt_fona.ino:23:0: ~/sketchbook/libraries/Adafruit_MQTT_Library/Adafruit_MQTT.h:204:20: note: virtual uint16_t Adafruit_MQTT::readPacket(uint8_t*, uint8_t, int16_t) virtual uint16_t readPacket(uint8_t *buffer, uint8_t maxlen, int16_t timeout) = 0;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.