├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── githubci.yml ├── .gitignore ├── Adafruit_MQTT.cpp ├── Adafruit_MQTT.h ├── Adafruit_MQTT_Client.cpp ├── Adafruit_MQTT_Client.h ├── Adafruit_MQTT_FONA.h ├── LICENSE ├── README.md ├── examples ├── adafruitio_anon_time_esp8266 │ ├── .zero.test.skip │ └── adafruitio_anon_time_esp8266.ino ├── adafruitio_errors_esp8266 │ ├── .zero.test.skip │ └── adafruitio_errors_esp8266.ino ├── adafruitio_secure_airlift │ ├── .esp8266.test.skip │ ├── .zero.test.skip │ └── adafruitio_secure_airlift.ino ├── adafruitio_secure_esp32 │ ├── .esp8266.test.skip │ ├── .zero.test.skip │ └── adafruitio_secure_esp32.ino ├── adafruitio_secure_esp8266 │ ├── .zero.test.skip │ └── adafruitio_secure_esp8266.ino ├── adafruitio_time_esp8266 │ ├── .zero.test.skip │ └── adafruitio_time_esp8266.ino ├── mqtt_2subs_esp8266 │ ├── .due.test.skip │ ├── .leonardo.test.skip │ ├── .uno.test.skip │ ├── .zero.test.skip │ └── mqtt_2subs_esp8266.ino ├── mqtt_arbitrary_data │ ├── .due.test.skip │ ├── .leonardo.test.skip │ ├── .uno.test.skip │ ├── .zero.test.skip │ ├── README.md │ ├── mqtt_arbitrary_data.ino │ └── python_subscriber │ │ ├── mqtt_figure.png │ │ ├── requirements.txt │ │ └── subscriber.py ├── mqtt_esp8266 │ ├── .due.test.skip │ ├── .leonardo.test.skip │ ├── .uno.test.skip │ ├── .zero.test.skip │ └── mqtt_esp8266.ino ├── mqtt_esp8266_callback │ ├── .esp8266.test.skip │ ├── .zero.test.skip │ └── mqtt_esp8266_callback.ino ├── mqtt_ethernet │ ├── .due.test.skip │ ├── .esp8266.test.skip │ ├── .zero.test.skip │ └── mqtt_ethernet.ino ├── mqtt_fona │ ├── .due.test.skip │ ├── .esp8266.test.skip │ ├── .zero.test.skip │ ├── fonahelper.cpp │ └── mqtt_fona.ino ├── mqtt_retain │ ├── .due.test.skip │ ├── .leonardo.test.skip │ ├── .uno.test.skip │ ├── .zero.test.skip │ └── mqtt_retain.ino ├── mqtt_winc1500 │ ├── .esp8266.test.skip │ └── mqtt_winc1500.ino └── mqtt_yun │ ├── .due.test.skip │ ├── .esp8266.test.skip │ ├── .leonardo.test.skip │ ├── .uno.test.skip │ ├── .zero.test.skip │ └── mqtt_yun.ino ├── keywords.txt └── library.properties /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for opening an issue on an Adafruit Arduino library repository. To 2 | improve the speed of resolution please review the following guidelines and 3 | common troubleshooting steps below before creating the issue: 4 | 5 | - **Do not use GitHub issues for troubleshooting projects and issues.** Instead use 6 | the forums at http://forums.adafruit.com to ask questions and troubleshoot why 7 | something isn't working as expected. In many cases the problem is a common issue 8 | that you will more quickly receive help from the forum community. GitHub issues 9 | are meant for known defects in the code. If you don't know if there is a defect 10 | in the code then start with troubleshooting on the forum first. 11 | 12 | - **If following a tutorial or guide be sure you didn't miss a step.** Carefully 13 | check all of the steps and commands to run have been followed. Consult the 14 | forum if you're unsure or have questions about steps in a guide/tutorial. 15 | 16 | - **For Arduino projects check these very common issues to ensure they don't apply**: 17 | 18 | - For uploading sketches or communicating with the board make sure you're using 19 | a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes 20 | very hard to tell the difference between a data and charge cable! Try using the 21 | cable with other devices or swapping to another cable to confirm it is not 22 | the problem. 23 | 24 | - **Be sure you are supplying adequate power to the board.** Check the specs of 25 | your board and plug in an external power supply. In many cases just 26 | plugging a board into your computer is not enough to power it and other 27 | peripherals. 28 | 29 | - **Double check all soldering joints and connections.** Flakey connections 30 | cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints. 31 | 32 | - **Ensure you are using an official Arduino or Adafruit board.** We can't 33 | guarantee a clone board will have the same functionality and work as expected 34 | with this code and don't support them. 35 | 36 | If you're sure this issue is a defect in the code and checked the steps above 37 | please fill in the following fields to provide enough troubleshooting information. 38 | You may delete the guideline and text above to just leave the following details: 39 | 40 | - Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE** 41 | 42 | - Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO 43 | VERSION HERE** 44 | 45 | - List the steps to reproduce the problem below (if possible attach a sketch or 46 | copy the sketch code in too): **LIST REPRO STEPS BELOW** 47 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thank you for creating a pull request to contribute to Adafruit's GitHub code! 2 | Before you open the request please review the following guidelines and tips to 3 | help it be more easily integrated: 4 | 5 | - **Describe the scope of your change--i.e. what the change does and what parts 6 | of the code were modified.** This will help us understand any risks of integrating 7 | the code. 8 | 9 | - **Describe any known limitations with your change.** For example if the change 10 | doesn't apply to a supported platform of the library please mention it. 11 | 12 | - **Please run any tests or examples that can exercise your modified code.** We 13 | strive to not break users of the code and running tests/examples helps with this 14 | process. 15 | 16 | Thank you again for contributing! We will try to test and integrate the change 17 | as soon as we can, but be aware we have many GitHub repositories to manage and 18 | can't immediately respond to every request. There is no need to bump or check in 19 | on a pull request (it will clutter the discussion of the request). 20 | 21 | Also don't be worried if the request is closed or not integrated--sometimes the 22 | priorities of Adafruit's GitHub code (education, ease of use) might not match the 23 | priorities of the pull request. Don't fret, the open source community thrives on 24 | forks and GitHub makes it easy to keep your changes in a forked repo. 25 | 26 | After reviewing the guidelines above you can delete this text from the pull request. 27 | -------------------------------------------------------------------------------- /.github/workflows/githubci.yml: -------------------------------------------------------------------------------- 1 | name: Arduino Library CI 2 | 3 | on: [pull_request, push, repository_dispatch] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/setup-python@v4 11 | with: 12 | python-version: '3.x' 13 | - uses: actions/checkout@v3 14 | - uses: actions/checkout@v3 15 | with: 16 | repository: adafruit/ci-arduino 17 | path: ci 18 | 19 | - name: pre-install 20 | run: bash ci/actions_install.sh 21 | 22 | - name: test platforms 23 | run: python3 ci/build_platform.py esp8266 zero 24 | 25 | - name: clang 26 | run: python3 ci/run-clang-format.py -e "ci/*" -e "bin/*" -r . 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.bts* 3 | -------------------------------------------------------------------------------- /Adafruit_MQTT.cpp: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // 3 | // Copyright (c) 2015 Adafruit Industries 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | // SOFTWARE. 22 | #include "Adafruit_MQTT.h" 23 | 24 | #if defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || \ 25 | defined(ARDUINO_SAMD_MKR1010) || defined(ARDUINO_ARCH_SAMD) 26 | static char *dtostrf(double val, signed char width, unsigned char prec, 27 | char *sout) { 28 | char fmt[20]; 29 | sprintf(fmt, "%%%d.%df", width, prec); 30 | sprintf(sout, fmt, val); 31 | return sout; 32 | } 33 | #endif 34 | 35 | #if defined(ESP8266) 36 | int strncasecmp(const char *str1, const char *str2, int len) { 37 | int d = 0; 38 | while (len--) { 39 | int c1 = tolower(*str1++); 40 | int c2 = tolower(*str2++); 41 | if (((d = c1 - c2) != 0) || (c2 == '\0')) { 42 | return d; 43 | } 44 | } 45 | return 0; 46 | } 47 | #endif 48 | 49 | void printBuffer(uint8_t *buffer, uint16_t len) { 50 | DEBUG_PRINTER.print('\t'); 51 | for (uint16_t i = 0; i < len; i++) { 52 | if (isprint(buffer[i])) 53 | DEBUG_PRINTER.write(buffer[i]); 54 | else 55 | DEBUG_PRINTER.print(" "); 56 | DEBUG_PRINTER.print(F(" [0x")); 57 | if (buffer[i] < 0x10) 58 | DEBUG_PRINTER.print("0"); 59 | DEBUG_PRINTER.print(buffer[i], HEX); 60 | DEBUG_PRINTER.print("], "); 61 | if (i % 8 == 7) { 62 | DEBUG_PRINTER.print("\n\t"); 63 | } 64 | } 65 | DEBUG_PRINTER.println(); 66 | } 67 | 68 | /* Not used now, but might be useful in the future 69 | static uint8_t *stringprint(uint8_t *p, char *s) { 70 | uint16_t len = strlen(s); 71 | p[0] = len >> 8; p++; 72 | p[0] = len & 0xFF; p++; 73 | memmove(p, s, len); 74 | return p+len; 75 | } 76 | */ 77 | 78 | static uint8_t *stringprint(uint8_t *p, const char *s, uint16_t maxlen = 0) { 79 | // If maxlen is specified (has a non-zero value) then use it as the maximum 80 | // length of the source string to write to the buffer. Otherwise write 81 | // the entire source string. 82 | uint16_t len = strlen(s); 83 | if (maxlen > 0 && len > maxlen) { 84 | len = maxlen; 85 | } 86 | /* 87 | for (uint8_t i=0; i> 8; 92 | p++; 93 | p[0] = len & 0xFF; 94 | p++; 95 | strncpy((char *)p, s, len); 96 | return p + len; 97 | } 98 | 99 | // packetAdditionalLen is a helper function used to figure out 100 | // how bigger the payload needs to be in order to account for 101 | // its variable length field. As per 102 | // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Table_2.4_Size 103 | // See also readFullPacket 104 | static uint16_t packetAdditionalLen(uint32_t currLen) { 105 | /* Increase length field based on current length */ 106 | if (currLen < 128) // 7-bits 107 | return 0; 108 | if (currLen < 16384) // 14-bits 109 | return 1; 110 | if (currLen < 2097152) // 21-bits 111 | return 2; 112 | return 3; 113 | } 114 | 115 | // Adafruit_MQTT Definition //////////////////////////////////////////////////// 116 | 117 | Adafruit_MQTT::Adafruit_MQTT(const char *server, uint16_t port, const char *cid, 118 | const char *user, const char *pass) { 119 | servername = server; 120 | portnum = port; 121 | clientid = cid; 122 | username = user; 123 | password = pass; 124 | 125 | // reset subscriptions 126 | for (uint8_t i = 0; i < MAXSUBSCRIPTIONS; i++) { 127 | subscriptions[i] = 0; 128 | } 129 | 130 | will_topic = 0; 131 | will_payload = 0; 132 | will_qos = 0; 133 | will_retain = 0; 134 | 135 | packet_id_counter = 1; // MQTT spec forbids packet id of 0 if QOS=1 136 | keepAliveInterval = MQTT_CONN_KEEPALIVE; 137 | } 138 | 139 | Adafruit_MQTT::Adafruit_MQTT(const char *server, uint16_t port, 140 | const char *user, const char *pass) { 141 | servername = server; 142 | portnum = port; 143 | clientid = ""; 144 | username = user; 145 | password = pass; 146 | 147 | // reset subscriptions 148 | for (uint8_t i = 0; i < MAXSUBSCRIPTIONS; i++) { 149 | subscriptions[i] = 0; 150 | } 151 | 152 | will_topic = 0; 153 | will_payload = 0; 154 | will_qos = 0; 155 | will_retain = 0; 156 | 157 | packet_id_counter = 1; // MQTT spec forbids packet id of 0 if QOS=1 158 | keepAliveInterval = MQTT_CONN_KEEPALIVE; 159 | } 160 | 161 | int8_t Adafruit_MQTT::connect() { 162 | // Connect to the server. 163 | if (!connectServer()) 164 | return -1; 165 | 166 | // Construct and send connect packet. 167 | uint8_t len = connectPacket(buffer); 168 | if (!sendPacket(buffer, len)) 169 | return -1; 170 | 171 | // Read connect response packet and verify it 172 | len = readFullPacket(buffer, MAXBUFFERSIZE, CONNECT_TIMEOUT_MS); 173 | if (len != 4) { 174 | return -1; 175 | } 176 | if ((buffer[0] != (MQTT_CTRL_CONNECTACK << 4)) || (buffer[1] != 2)) { 177 | return -1; 178 | } 179 | if (buffer[3] != 0) 180 | return buffer[3]; 181 | 182 | // Setup subscriptions once connected. 183 | for (uint8_t i = 0; i < MAXSUBSCRIPTIONS; i++) { 184 | // Ignore subscriptions that aren't defined. 185 | if (subscriptions[i] == 0) 186 | continue; 187 | 188 | boolean success = false; 189 | for (uint8_t retry = 0; (retry < 3) && !success; 190 | retry++) { // retry until we get a suback 191 | // Construct and send subscription packet. 192 | uint8_t len = subscribePacket(buffer, subscriptions[i]->topic, 193 | subscriptions[i]->qos); 194 | if (!sendPacket(buffer, len)) 195 | return -1; 196 | 197 | if (MQTT_PROTOCOL_LEVEL < 3) // older versions didn't suback 198 | break; 199 | 200 | // Check for SUBACK if using MQTT 3.1.1 or higher 201 | // TODO: The Server is permitted to start sending PUBLISH packets matching 202 | // the Subscription before the Server sends the SUBACK Packet. (will 203 | // really need to use callbacks - ada) 204 | 205 | if (processPacketsUntil(buffer, MQTT_CTRL_SUBACK, SUBACK_TIMEOUT_MS)) { 206 | success = true; 207 | break; 208 | } 209 | } 210 | if (!success) 211 | return -2; // failed to sub for some reason 212 | } 213 | 214 | return 0; 215 | } 216 | 217 | int8_t Adafruit_MQTT::connect(const char *user, const char *pass) { 218 | username = user; 219 | password = pass; 220 | return connect(); 221 | } 222 | 223 | void Adafruit_MQTT::processSubscriptionPacket(Adafruit_MQTT_Subscribe *sub) { 224 | if (sub->callback_uint32t != NULL) { 225 | // execute callback in integer mode 226 | uint32_t data = 0; 227 | data = atoi((char *)sub->lastread); 228 | sub->callback_uint32t(data); 229 | } else if (sub->callback_double != NULL) { 230 | // execute callback in doublefloat mode 231 | double data = 0; 232 | data = atof((char *)sub->lastread); 233 | sub->callback_double(data); 234 | } else if (sub->callback_buffer != NULL) { 235 | // execute callback in buffer mode 236 | sub->callback_buffer((char *)sub->lastread, sub->datalen); 237 | } else if (sub->callback_io != NULL) { 238 | // execute callback in io mode 239 | ((sub->io_mqtt)->*(sub->callback_io))((char *)sub->lastread, sub->datalen); 240 | } else { 241 | DEBUG_PRINTLN( 242 | "ERROR: Subscription packet did not have an associated callback"); 243 | return; 244 | } 245 | // mark subscription message as "read"" 246 | sub->new_message = false; 247 | } 248 | 249 | uint16_t Adafruit_MQTT::processPacketsUntil(uint8_t *buffer, 250 | uint8_t waitforpackettype, 251 | uint16_t timeout) { 252 | uint16_t len; 253 | 254 | while (true) { 255 | len = readFullPacket(buffer, MAXBUFFERSIZE, timeout); 256 | 257 | if (len == 0) { 258 | break; 259 | } 260 | 261 | uint8_t packetType = (buffer[0] >> 4); 262 | if (packetType == waitforpackettype) { 263 | return len; 264 | } else { 265 | if (packetType == MQTT_CTRL_PUBLISH) { 266 | Adafruit_MQTT_Subscribe *sub = handleSubscriptionPacket(len); 267 | if (sub) 268 | processSubscriptionPacket(sub); 269 | } else { 270 | ERROR_PRINTLN(F("Dropped a packet")); 271 | } 272 | } 273 | } 274 | return 0; 275 | } 276 | 277 | uint16_t Adafruit_MQTT::readFullPacket(uint8_t *buffer, uint16_t maxsize, 278 | uint16_t timeout) { 279 | // will read a packet and Do The Right Thing with length 280 | uint8_t *pbuff = buffer; 281 | 282 | uint16_t rlen; 283 | 284 | // read the packet type: 285 | rlen = readPacket(pbuff, 1, timeout); 286 | if (rlen != 1) 287 | return 0; 288 | 289 | DEBUG_PRINT(F("Packet Type:\t")); 290 | DEBUG_PRINTBUFFER(pbuff, rlen); 291 | pbuff++; 292 | 293 | uint32_t value = 0; 294 | uint32_t multiplier = 1; 295 | uint8_t encodedByte; 296 | 297 | do { 298 | rlen = readPacket(pbuff, 1, timeout); 299 | if (rlen != 1) 300 | return 0; 301 | encodedByte = pbuff[0]; // save the last read val 302 | pbuff++; // get ready for reading the next byte 303 | uint32_t intermediate = encodedByte & 0x7F; 304 | intermediate *= multiplier; 305 | value += intermediate; 306 | multiplier *= 128; 307 | if (multiplier > (128UL * 128UL * 128UL)) { 308 | DEBUG_PRINT(F("Malformed packet len\n")); 309 | return 0; 310 | } 311 | } while (encodedByte & 0x80); 312 | 313 | DEBUG_PRINT(F("Packet Length:\t")); 314 | DEBUG_PRINTLN(value); 315 | 316 | // maxsize is limited to 65536 by 16-bit unsigned 317 | if (value > uint32_t(maxsize - (pbuff - buffer) - 1)) { 318 | DEBUG_PRINTLN(F("Packet too big for buffer")); 319 | rlen = readPacket(pbuff, (maxsize - (pbuff - buffer) - 1), timeout); 320 | } else { 321 | rlen = readPacket(pbuff, value, timeout); 322 | } 323 | // DEBUG_PRINT(F("Remaining packet:\t")); DEBUG_PRINTBUFFER(pbuff, rlen); 324 | 325 | return ((pbuff - buffer) + rlen); 326 | } 327 | 328 | const __FlashStringHelper *Adafruit_MQTT::connectErrorString(int8_t code) { 329 | switch (code) { 330 | case 1: 331 | return F( 332 | "The Server does not support the level of the MQTT protocol requested"); 333 | case 2: 334 | return F( 335 | "The Client identifier is correct UTF-8 but not allowed by the Server"); 336 | case 3: 337 | return F("The MQTT service is unavailable"); 338 | case 4: 339 | return F("The data in the user name or password is malformed"); 340 | case 5: 341 | return F("Not authorized to connect"); 342 | case 6: 343 | return F("Exceeded reconnect rate limit. Please try again later."); 344 | case 7: 345 | return F("You have been banned from connecting. Please contact the MQTT " 346 | "server administrator for more details."); 347 | case -1: 348 | return F("Connection failed"); 349 | case -2: 350 | return F("Failed to subscribe"); 351 | default: 352 | return F("Unknown error"); 353 | } 354 | } 355 | 356 | bool Adafruit_MQTT::disconnect() { 357 | 358 | // Construct and send disconnect packet. 359 | uint8_t len = disconnectPacket(buffer); 360 | if (!sendPacket(buffer, len)) 361 | DEBUG_PRINTLN(F("Unable to send disconnect packet")); 362 | 363 | return disconnectServer(); 364 | } 365 | 366 | bool Adafruit_MQTT::publish(const char *topic, const char *data, uint8_t qos, 367 | bool retain) { 368 | return publish(topic, (uint8_t *)(data), strlen(data), qos, retain); 369 | } 370 | 371 | bool Adafruit_MQTT::publish(const char *topic, uint8_t *data, uint16_t bLen, 372 | uint8_t qos, bool retain) { 373 | // Construct and send publish packet. 374 | uint16_t len = publishPacket(buffer, topic, data, bLen, qos, 375 | (uint16_t)sizeof(buffer), retain); 376 | 377 | if (!sendPacket(buffer, len)) 378 | return false; 379 | 380 | // If QOS level is high enough verify the response packet. 381 | if (qos > 0) { 382 | len = processPacketsUntil(buffer, MQTT_CTRL_PUBACK, PUBLISH_TIMEOUT_MS); 383 | 384 | DEBUG_PRINT(F("Publish QOS1+ reply:\t")); 385 | DEBUG_PRINTBUFFER(buffer, len); 386 | if (len != 4) 387 | return false; 388 | 389 | uint16_t packnum = buffer[2]; 390 | packnum <<= 8; 391 | packnum |= buffer[3]; 392 | 393 | // we increment the packet_id_counter right after publishing so inc here too 394 | // to match 395 | packnum = packnum + 1 + (packnum + 1 == 0); // Skip zero 396 | if (packnum != packet_id_counter) 397 | return false; 398 | } 399 | 400 | return true; 401 | } 402 | 403 | bool Adafruit_MQTT::will(const char *topic, const char *payload, uint8_t qos, 404 | uint8_t retain) { 405 | 406 | if (connected()) { 407 | DEBUG_PRINT(F("Will defined after connect")); 408 | return false; 409 | } 410 | 411 | will_topic = topic; 412 | will_payload = payload; 413 | will_qos = qos; 414 | will_retain = retain; 415 | 416 | return true; 417 | } 418 | 419 | /***************************************************************************/ 420 | /*! 421 | @brief Sets the connect packet's KeepAlive Interval, in seconds. This 422 | function MUST be called prior to connect(). 423 | @param keepAlive 424 | Maximum amount of time without communication between the 425 | client and the MQTT broker, in seconds. 426 | @returns True if called prior to connect(), False otherwise. 427 | */ 428 | /***************************************************************************/ 429 | bool Adafruit_MQTT::setKeepAliveInterval(uint16_t keepAlive) { 430 | if (connected()) { 431 | DEBUG_PRINT(F("keepAlive defined after connection established.")); 432 | return false; 433 | } 434 | keepAliveInterval = keepAlive; 435 | return true; 436 | } 437 | 438 | bool Adafruit_MQTT::subscribe(Adafruit_MQTT_Subscribe *sub) { 439 | uint8_t i; 440 | // see if we are already subscribed 441 | for (i = 0; i < MAXSUBSCRIPTIONS; i++) { 442 | if (subscriptions[i] == sub) { 443 | DEBUG_PRINTLN(F("Already subscribed")); 444 | return true; 445 | } 446 | } 447 | if (i == MAXSUBSCRIPTIONS) { // add to subscriptionlist 448 | for (i = 0; i < MAXSUBSCRIPTIONS; i++) { 449 | if (subscriptions[i] == 0) { 450 | DEBUG_PRINT(F("Added sub ")); 451 | DEBUG_PRINTLN(i); 452 | subscriptions[i] = sub; 453 | return true; 454 | } 455 | } 456 | } 457 | 458 | DEBUG_PRINTLN(F("no more subscription space :(")); 459 | return false; 460 | } 461 | 462 | bool Adafruit_MQTT::unsubscribe(Adafruit_MQTT_Subscribe *sub) { 463 | uint8_t i; 464 | 465 | // see if we are already subscribed 466 | for (i = 0; i < MAXSUBSCRIPTIONS; i++) { 467 | 468 | if (subscriptions[i] == sub) { 469 | 470 | DEBUG_PRINTLN( 471 | F("Found matching subscription and attempting to unsubscribe.")); 472 | 473 | // Construct and send unsubscribe packet. 474 | uint8_t len = unsubscribePacket(buffer, subscriptions[i]->topic); 475 | 476 | // sending unsubscribe failed 477 | if (!sendPacket(buffer, len)) 478 | return false; 479 | 480 | // if QoS for this subscription is 1 or 2, we need 481 | // to wait for the unsuback to confirm unsubscription 482 | if (subscriptions[i]->qos > 0 && MQTT_PROTOCOL_LEVEL > 3) { 483 | 484 | // wait for UNSUBACK 485 | len = readFullPacket(buffer, MAXBUFFERSIZE, CONNECT_TIMEOUT_MS); 486 | DEBUG_PRINT(F("UNSUBACK:\t")); 487 | DEBUG_PRINTBUFFER(buffer, len); 488 | 489 | if ((len != 5) || (buffer[0] != (MQTT_CTRL_UNSUBACK << 4))) { 490 | return false; // failure to unsubscribe 491 | } 492 | } 493 | 494 | subscriptions[i] = 0; 495 | return true; 496 | } 497 | } 498 | 499 | // subscription not found, so we are unsubscribed 500 | return true; 501 | } 502 | 503 | void Adafruit_MQTT::processPackets(int16_t timeout) { 504 | 505 | uint32_t elapsed = 0, endtime, starttime = millis(); 506 | 507 | while (elapsed < (uint32_t)timeout) { 508 | Adafruit_MQTT_Subscribe *sub = readSubscription(timeout - elapsed); 509 | if (sub) 510 | processSubscriptionPacket(sub); 511 | // keep track over elapsed time 512 | endtime = millis(); 513 | if (endtime < starttime) { 514 | starttime = endtime; // looped around!") 515 | } 516 | elapsed += (endtime - starttime); 517 | } 518 | } 519 | Adafruit_MQTT_Subscribe *Adafruit_MQTT::readSubscription(int16_t timeout) { 520 | 521 | // Sync or Async subscriber with message 522 | Adafruit_MQTT_Subscribe *s = 0; 523 | 524 | // Check if are unread messages 525 | for (uint8_t i = 0; i < MAXSUBSCRIPTIONS; i++) { 526 | if (subscriptions[i] && subscriptions[i]->new_message) { 527 | s = subscriptions[i]; 528 | break; 529 | } 530 | } 531 | 532 | // not unread message 533 | if (!s) { 534 | // Check if data is available to read. 535 | uint16_t len = readFullPacket(buffer, MAXBUFFERSIZE, 536 | timeout); // return one full packet 537 | s = handleSubscriptionPacket(len); 538 | } 539 | 540 | // it there is a message, mark it as not pending 541 | if (s) { 542 | s->new_message = false; 543 | } 544 | 545 | return s; 546 | } 547 | 548 | Adafruit_MQTT_Subscribe *Adafruit_MQTT::handleSubscriptionPacket(uint16_t len) { 549 | uint16_t i, topiclen, datalen; 550 | 551 | if (!len) { 552 | return NULL; // No data available, just quit. 553 | } 554 | DEBUG_PRINT("Packet len: "); 555 | DEBUG_PRINTLN(len); 556 | DEBUG_PRINTBUFFER(buffer, len); 557 | 558 | if (len < 3) { 559 | return NULL; 560 | } 561 | if ((buffer[0] & 0xF0) != (MQTT_CTRL_PUBLISH) << 4) { 562 | return NULL; 563 | } 564 | 565 | // Parse out length of packet. 566 | // NOTE: This includes data in the variable header and the payload. 567 | uint16_t remainingLen = len - 4; // subtract the 4 header bytes 568 | uint16_t const topicoffset = packetAdditionalLen(remainingLen); 569 | uint16_t const topicstart = topicoffset + 4; 570 | 571 | topiclen = int((buffer[2 + topicoffset]) << 8 | buffer[3 + topicoffset]); 572 | DEBUG_PRINT(F("Looking for subscription len ")); 573 | DEBUG_PRINTLN(topiclen); 574 | 575 | // Find subscription associated with this packet. 576 | for (i = 0; i < MAXSUBSCRIPTIONS; i++) { 577 | if (subscriptions[i]) { 578 | // Skip this subscription if its name length isn't the same as the 579 | // received topic name. 580 | if (strlen(subscriptions[i]->topic) != topiclen) 581 | continue; 582 | // Stop if the subscription topic matches the received topic. Be careful 583 | // to make comparison case insensitive. 584 | if (strncasecmp((char *)buffer + topicstart, subscriptions[i]->topic, 585 | topiclen) == 0) { 586 | DEBUG_PRINT(F("Found sub #")); 587 | DEBUG_PRINTLN(i); 588 | if (subscriptions[i]->new_message) { 589 | DEBUG_PRINTLN(F("Lost previous message")); 590 | } else { 591 | subscriptions[i]->new_message = true; 592 | } 593 | 594 | break; 595 | } 596 | } 597 | } 598 | if (i == MAXSUBSCRIPTIONS) 599 | return NULL; // matching sub not found ??? 600 | 601 | uint8_t packet_id_len = 0; 602 | uint16_t packetid = 0; 603 | // Check if it is QoS 1, TODO: we dont support QoS 2 604 | if ((buffer[0] & 0x6) == 0x2) { 605 | packet_id_len = 2; 606 | packetid = buffer[topiclen + topicstart]; 607 | packetid <<= 8; 608 | packetid |= buffer[topiclen + topicstart + 1]; 609 | } 610 | 611 | // zero out the old data 612 | memset(subscriptions[i]->lastread, 0, SUBSCRIPTIONDATALEN); 613 | 614 | datalen = len - topiclen - packet_id_len - topicstart; 615 | if (datalen > SUBSCRIPTIONDATALEN) { 616 | datalen = SUBSCRIPTIONDATALEN - 1; // cut it off 617 | } 618 | // extract out just the data, into the subscription object itself 619 | memmove(subscriptions[i]->lastread, 620 | buffer + topicstart + topiclen + packet_id_len, datalen); 621 | subscriptions[i]->datalen = datalen; 622 | DEBUG_PRINT(F("Data len: ")); 623 | DEBUG_PRINTLN(datalen); 624 | DEBUG_PRINT(F("Data: ")); 625 | DEBUG_PRINTLN((char *)subscriptions[i]->lastread); 626 | 627 | if ((MQTT_PROTOCOL_LEVEL > 3) && (buffer[0] & 0x6) == 0x2) { 628 | uint8_t ackpacket[4]; 629 | 630 | // Construct and send puback packet. 631 | uint8_t len = pubackPacket(ackpacket, packetid); 632 | if (!sendPacket(ackpacket, len)) 633 | DEBUG_PRINT(F("Failed")); 634 | } 635 | 636 | // return the valid matching subscription 637 | return subscriptions[i]; 638 | } 639 | 640 | void Adafruit_MQTT::flushIncoming(uint16_t timeout) { 641 | // flush input! 642 | DEBUG_PRINTLN(F("Flushing input buffer")); 643 | while (readPacket(buffer, MAXBUFFERSIZE, timeout)) 644 | ; 645 | } 646 | 647 | bool Adafruit_MQTT::ping(uint8_t num) { 648 | // flushIncoming(100); 649 | 650 | while (num--) { 651 | // Construct and send ping packet. 652 | uint8_t len = pingPacket(buffer); 653 | if (!sendPacket(buffer, len)) 654 | continue; 655 | 656 | // Process ping reply. 657 | len = processPacketsUntil(buffer, MQTT_CTRL_PINGRESP, PING_TIMEOUT_MS); 658 | if (buffer[0] == (MQTT_CTRL_PINGRESP << 4)) 659 | return true; 660 | } 661 | 662 | return false; 663 | } 664 | 665 | // Packet Generation Functions ///////////////////////////////////////////////// 666 | 667 | // The current MQTT spec is 3.1.1 and available here: 668 | // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028 669 | // However this connect packet and code follows the MQTT 3.1 spec here (some 670 | // small differences in the protocol): 671 | // http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#connect 672 | uint8_t Adafruit_MQTT::connectPacket(uint8_t *packet) { 673 | uint8_t *p = packet; 674 | uint16_t len; 675 | 676 | // fixed header, connection messsage no flags 677 | p[0] = (MQTT_CTRL_CONNECT << 4) | 0x0; 678 | p += 2; 679 | // fill in packet[1] last 680 | 681 | #if MQTT_PROTOCOL_LEVEL == 3 682 | p = stringprint(p, "MQIsdp"); 683 | #elif MQTT_PROTOCOL_LEVEL == 4 684 | p = stringprint(p, "MQTT"); 685 | #else 686 | #error "MQTT level not supported" 687 | #endif 688 | 689 | p[0] = MQTT_PROTOCOL_LEVEL; 690 | p++; 691 | 692 | // always clean the session 693 | p[0] = MQTT_CONN_CLEANSESSION; 694 | 695 | // set the will flags if needed 696 | if (will_topic && pgm_read_byte(will_topic) != 0) { 697 | 698 | p[0] |= MQTT_CONN_WILLFLAG; 699 | 700 | if (will_qos == 1) 701 | p[0] |= MQTT_CONN_WILLQOS_1; 702 | else if (will_qos == 2) 703 | p[0] |= MQTT_CONN_WILLQOS_2; 704 | 705 | if (will_retain == 1) 706 | p[0] |= MQTT_CONN_WILLRETAIN; 707 | } 708 | 709 | if (pgm_read_byte(username) != 0) 710 | p[0] |= MQTT_CONN_USERNAMEFLAG; 711 | if (pgm_read_byte(password) != 0) 712 | p[0] |= MQTT_CONN_PASSWORDFLAG; 713 | p++; 714 | 715 | p[0] = keepAliveInterval >> 8; 716 | p++; 717 | p[0] = keepAliveInterval & 0xFF; 718 | p++; 719 | 720 | if (MQTT_PROTOCOL_LEVEL == 3) { 721 | p = stringprint(p, clientid, 23); // Limit client ID to first 23 characters. 722 | } else { 723 | if (pgm_read_byte(clientid) != 0) { 724 | p = stringprint(p, clientid); 725 | } else { 726 | p[0] = 0x0; 727 | p++; 728 | p[0] = 0x0; 729 | p++; 730 | DEBUG_PRINTLN(F("SERVER GENERATING CLIENT ID")); 731 | } 732 | } 733 | 734 | if (will_topic && pgm_read_byte(will_topic) != 0) { 735 | p = stringprint(p, will_topic); 736 | p = stringprint(p, will_payload); 737 | } 738 | 739 | if (pgm_read_byte(username) != 0) { 740 | p = stringprint(p, username); 741 | } 742 | if (pgm_read_byte(password) != 0) { 743 | p = stringprint(p, password); 744 | } 745 | 746 | len = p - packet; 747 | 748 | packet[1] = len - 2; // don't include the 2 bytes of fixed header data 749 | DEBUG_PRINTLN(F("MQTT connect packet:")); 750 | DEBUG_PRINTBUFFER(buffer, len); 751 | return len; 752 | } 753 | 754 | // as per 755 | // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718040 756 | uint16_t Adafruit_MQTT::publishPacket(uint8_t *packet, const char *topic, 757 | uint8_t *data, uint16_t bLen, uint8_t qos, 758 | uint16_t maxPacketLen, bool retain) { 759 | uint8_t *p = packet; 760 | uint16_t len = 0; 761 | 762 | // calc length of non-header data 763 | len += 2; // two bytes to set the topic size 764 | len += strlen(topic); // topic length 765 | if (qos > 0) { 766 | len += 2; // qos packet id 767 | } 768 | // Calculate additional bytes for length field (if any) 769 | uint16_t additionalLen = packetAdditionalLen(len + bLen); 770 | 771 | // Payload remaining length. When maxPacketLen provided is 0, let's 772 | // assume buffer is big enough. Fingers crossed. 773 | // 2 + additionalLen: header byte + remaining length field (from 1 to 4 bytes) 774 | // len = topic size field + value (string) 775 | // bLen = buffer size 776 | if (!(maxPacketLen == 0 || 777 | (len + bLen + 2 + additionalLen <= maxPacketLen))) { 778 | // If we make it here, we got a pickle: the payload is not going 779 | // to fit in the packet buffer. Instead of corrupting memory, let's 780 | // do something less damaging by reducing the bLen to what we are 781 | // able to accomodate. Alternatively, consider using a bigger 782 | // maxPacketLen. 783 | bLen = maxPacketLen - (len + 2 + packetAdditionalLen(maxPacketLen)); 784 | } 785 | len += bLen; // remaining len excludes header byte & length field 786 | 787 | // Now you can start generating the packet! 788 | p[0] = MQTT_CTRL_PUBLISH << 4 | qos << 1 | (retain ? 1 : 0); 789 | p++; 790 | 791 | // fill in packet[1] last 792 | do { 793 | uint8_t encodedByte = len % 128; 794 | len /= 128; 795 | // if there are more data to encode, set the top bit of this byte 796 | if (len > 0) { 797 | encodedByte |= 0x80; 798 | } 799 | p[0] = encodedByte; 800 | p++; 801 | } while (len > 0); 802 | 803 | // topic comes before packet identifier 804 | p = stringprint(p, topic); 805 | 806 | // add packet identifier. used for checking PUBACK in QOS > 0 807 | if (qos > 0) { 808 | p[0] = (packet_id_counter >> 8) & 0xFF; 809 | p[1] = packet_id_counter & 0xFF; 810 | p += 2; 811 | 812 | // increment the packet id, skipping 0 813 | packet_id_counter = packet_id_counter + 1 + (packet_id_counter + 1 == 0); 814 | } 815 | 816 | memmove(p, data, bLen); 817 | p += bLen; 818 | len = p - packet; 819 | DEBUG_PRINTLN(F("MQTT publish packet:")); 820 | DEBUG_PRINTBUFFER(buffer, len); 821 | return len; 822 | } 823 | 824 | uint8_t Adafruit_MQTT::subscribePacket(uint8_t *packet, const char *topic, 825 | uint8_t qos) { 826 | uint8_t *p = packet; 827 | uint16_t len; 828 | 829 | p[0] = MQTT_CTRL_SUBSCRIBE << 4 | MQTT_QOS_1 << 1; 830 | // fill in packet[1] last 831 | p += 2; 832 | 833 | // packet identifier. used for checking SUBACK 834 | p[0] = (packet_id_counter >> 8) & 0xFF; 835 | p[1] = packet_id_counter & 0xFF; 836 | p += 2; 837 | 838 | // increment the packet id, skipping 0 839 | packet_id_counter = packet_id_counter + 1 + (packet_id_counter + 1 == 0); 840 | 841 | p = stringprint(p, topic); 842 | 843 | p[0] = qos; 844 | p++; 845 | 846 | len = p - packet; 847 | packet[1] = len - 2; // don't include the 2 bytes of fixed header data 848 | DEBUG_PRINTLN(F("MQTT subscription packet:")); 849 | DEBUG_PRINTBUFFER(buffer, len); 850 | return len; 851 | } 852 | 853 | uint8_t Adafruit_MQTT::unsubscribePacket(uint8_t *packet, const char *topic) { 854 | 855 | uint8_t *p = packet; 856 | uint16_t len; 857 | 858 | p[0] = MQTT_CTRL_UNSUBSCRIBE << 4 | 0x1; 859 | // fill in packet[1] last 860 | p += 2; 861 | 862 | // packet identifier. used for checking UNSUBACK 863 | p[0] = (packet_id_counter >> 8) & 0xFF; 864 | p[1] = packet_id_counter & 0xFF; 865 | p += 2; 866 | 867 | // increment the packet id, skipping 0 868 | packet_id_counter = packet_id_counter + 1 + (packet_id_counter + 1 == 0); 869 | 870 | p = stringprint(p, topic); 871 | 872 | len = p - packet; 873 | packet[1] = len - 2; // don't include the 2 bytes of fixed header data 874 | DEBUG_PRINTLN(F("MQTT unsubscription packet:")); 875 | DEBUG_PRINTBUFFER(buffer, len); 876 | return len; 877 | } 878 | 879 | uint8_t Adafruit_MQTT::pingPacket(uint8_t *packet) { 880 | packet[0] = MQTT_CTRL_PINGREQ << 4; 881 | packet[1] = 0; 882 | DEBUG_PRINTLN(F("MQTT ping packet:")); 883 | DEBUG_PRINTBUFFER(buffer, 2); 884 | return 2; 885 | } 886 | 887 | uint8_t Adafruit_MQTT::pubackPacket(uint8_t *packet, uint16_t packetid) { 888 | packet[0] = MQTT_CTRL_PUBACK << 4; 889 | packet[1] = 2; 890 | packet[2] = packetid >> 8; 891 | packet[3] = packetid; 892 | DEBUG_PRINTLN(F("MQTT puback packet:")); 893 | DEBUG_PRINTBUFFER(buffer, 4); 894 | return 4; 895 | } 896 | 897 | uint8_t Adafruit_MQTT::disconnectPacket(uint8_t *packet) { 898 | packet[0] = MQTT_CTRL_DISCONNECT << 4; 899 | packet[1] = 0; 900 | DEBUG_PRINTLN(F("MQTT disconnect packet:")); 901 | DEBUG_PRINTBUFFER(buffer, 2); 902 | return 2; 903 | } 904 | 905 | // Adafruit_MQTT_Publish Definition //////////////////////////////////////////// 906 | 907 | Adafruit_MQTT_Publish::Adafruit_MQTT_Publish(Adafruit_MQTT *mqttserver, 908 | const char *feed, uint8_t q) { 909 | mqtt = mqttserver; 910 | topic = feed; 911 | qos = q; 912 | } 913 | 914 | bool Adafruit_MQTT_Publish::publish(int32_t i, bool retain) { 915 | char payload[12]; 916 | ltoa(i, payload, 10); 917 | return mqtt->publish(topic, payload, qos, retain); 918 | } 919 | 920 | bool Adafruit_MQTT_Publish::publish(uint32_t i, bool retain) { 921 | char payload[11]; 922 | ultoa(i, payload, 10); 923 | return mqtt->publish(topic, payload, qos, retain); 924 | } 925 | 926 | bool Adafruit_MQTT_Publish::publish(double f, uint8_t precision, bool retain) { 927 | char payload[41]; // Need to technically hold float max, 39 digits and minus 928 | // sign. 929 | dtostrf(f, 0, precision, payload); 930 | return mqtt->publish(topic, payload, qos, retain); 931 | } 932 | 933 | bool Adafruit_MQTT_Publish::publish(const char *payload, bool retain) { 934 | return mqtt->publish(topic, payload, qos, retain); 935 | } 936 | 937 | // publish buffer of arbitrary length 938 | bool Adafruit_MQTT_Publish::publish(uint8_t *payload, uint16_t bLen, 939 | bool retain) { 940 | return mqtt->publish(topic, payload, bLen, qos, retain); 941 | } 942 | 943 | // Adafruit_MQTT_Subscribe Definition ////////////////////////////////////////// 944 | 945 | Adafruit_MQTT_Subscribe::Adafruit_MQTT_Subscribe(Adafruit_MQTT *mqttserver, 946 | const char *feed, uint8_t q) { 947 | mqtt = mqttserver; 948 | topic = feed; 949 | qos = q; 950 | datalen = 0; 951 | callback_uint32t = 0; 952 | callback_buffer = 0; 953 | callback_double = 0; 954 | callback_io = 0; 955 | io_mqtt = 0; 956 | new_message = false; 957 | } 958 | 959 | void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackUInt32Type cb) { 960 | callback_uint32t = cb; 961 | } 962 | 963 | void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackDoubleType cb) { 964 | callback_double = cb; 965 | } 966 | 967 | void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackBufferType cb) { 968 | callback_buffer = cb; 969 | } 970 | 971 | void Adafruit_MQTT_Subscribe::setCallback(AdafruitIO_MQTT *io, 972 | SubscribeCallbackIOType cb) { 973 | callback_io = cb; 974 | io_mqtt = io; 975 | } 976 | 977 | void Adafruit_MQTT_Subscribe::removeCallback(void) { 978 | callback_uint32t = 0; 979 | callback_buffer = 0; 980 | callback_double = 0; 981 | callback_io = 0; 982 | io_mqtt = 0; 983 | } 984 | -------------------------------------------------------------------------------- /Adafruit_MQTT.h: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // 3 | // Copyright (c) 2015 Adafruit Industries 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | // SOFTWARE. 22 | #ifndef _ADAFRUIT_MQTT_H_ 23 | #define _ADAFRUIT_MQTT_H_ 24 | 25 | #include "Arduino.h" 26 | 27 | #if defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_STM32_FEATHER) 28 | #define strncpy_P(dest, src, len) strncpy((dest), (src), (len)) 29 | #define strncasecmp_P(f1, f2, len) strncasecmp((f1), (f2), (len)) 30 | #endif 31 | 32 | #define ADAFRUIT_MQTT_VERSION_MAJOR 0 33 | #define ADAFRUIT_MQTT_VERSION_MINOR 17 34 | #define ADAFRUIT_MQTT_VERSION_PATCH 0 35 | 36 | // Uncomment/comment to turn on/off debug output messages. 37 | // #define MQTT_DEBUG 38 | // Uncomment/comment to turn on/off error output messages. 39 | #define MQTT_ERROR 40 | 41 | // Set where debug messages will be printed. 42 | #define DEBUG_PRINTER Serial 43 | // If using something like Zero or Due, change the above to SerialUSB 44 | 45 | // Define actual debug output functions when necessary. 46 | #ifdef MQTT_DEBUG 47 | #define DEBUG_PRINT(...) \ 48 | { DEBUG_PRINTER.print(__VA_ARGS__); } 49 | #define DEBUG_PRINTLN(...) \ 50 | { DEBUG_PRINTER.println(__VA_ARGS__); } 51 | #define DEBUG_PRINTBUFFER(buffer, len) \ 52 | { printBuffer(buffer, len); } 53 | #else 54 | #define DEBUG_PRINT(...) \ 55 | {} 56 | #define DEBUG_PRINTLN(...) \ 57 | {} 58 | #define DEBUG_PRINTBUFFER(buffer, len) \ 59 | {} 60 | #endif 61 | 62 | #ifdef MQTT_ERROR 63 | #define ERROR_PRINT(...) \ 64 | { DEBUG_PRINTER.print(__VA_ARGS__); } 65 | #define ERROR_PRINTLN(...) \ 66 | { DEBUG_PRINTER.println(__VA_ARGS__); } 67 | #define ERROR_PRINTBUFFER(buffer, len) \ 68 | { printBuffer(buffer, len); } 69 | #else 70 | #define ERROR_PRINT(...) \ 71 | {} 72 | #define ERROR_PRINTLN(...) \ 73 | {} 74 | #define ERROR_PRINTBUFFER(buffer, len) \ 75 | {} 76 | #endif 77 | 78 | // Use 3 (MQTT 3.0) or 4 (MQTT 3.1.1) 79 | #define MQTT_PROTOCOL_LEVEL 4 80 | 81 | #define MQTT_CTRL_CONNECT 0x1 82 | #define MQTT_CTRL_CONNECTACK 0x2 83 | #define MQTT_CTRL_PUBLISH 0x3 84 | #define MQTT_CTRL_PUBACK 0x4 85 | #define MQTT_CTRL_PUBREC 0x5 86 | #define MQTT_CTRL_PUBREL 0x6 87 | #define MQTT_CTRL_PUBCOMP 0x7 88 | #define MQTT_CTRL_SUBSCRIBE 0x8 89 | #define MQTT_CTRL_SUBACK 0x9 90 | #define MQTT_CTRL_UNSUBSCRIBE 0xA 91 | #define MQTT_CTRL_UNSUBACK 0xB 92 | #define MQTT_CTRL_PINGREQ 0xC 93 | #define MQTT_CTRL_PINGRESP 0xD 94 | #define MQTT_CTRL_DISCONNECT 0xE 95 | 96 | #define MQTT_QOS_1 0x1 97 | #define MQTT_QOS_0 0x0 98 | 99 | #define CONNECT_TIMEOUT_MS 6000 100 | #define PUBLISH_TIMEOUT_MS 500 101 | #define PING_TIMEOUT_MS 500 102 | #define SUBACK_TIMEOUT_MS 500 103 | 104 | // Adjust as necessary, in seconds. Default to 5 minutes. 105 | #define MQTT_CONN_KEEPALIVE 300 106 | 107 | // Largest full packet we're able to send. 108 | // Need to be able to store at least ~90 chars for a connect packet with full 109 | // 23 char client ID. 110 | // Future TODO: This should be replaced by the ability to dynamically allocate a 111 | // buffer as needed. 112 | #if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) || \ 113 | defined(ARDUINO_ARCH_RP2040) || defined(ARDUINO_ARCH_SAMD) 114 | #define MAXBUFFERSIZE (512) 115 | #else 116 | #define MAXBUFFERSIZE (150) 117 | #endif 118 | 119 | #define MQTT_CONN_USERNAMEFLAG 0x80 120 | #define MQTT_CONN_PASSWORDFLAG 0x40 121 | #define MQTT_CONN_WILLRETAIN 0x20 122 | #define MQTT_CONN_WILLQOS_1 0x08 123 | #define MQTT_CONN_WILLQOS_2 0x18 124 | #define MQTT_CONN_WILLFLAG 0x04 125 | #define MQTT_CONN_CLEANSESSION 0x02 126 | 127 | // how much data we save in a subscription object 128 | // and how many subscriptions we want to be able to track. 129 | #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega328P__) 130 | #define MAXSUBSCRIPTIONS 5 131 | #define SUBSCRIPTIONDATALEN 20 132 | #else 133 | #define MAXSUBSCRIPTIONS 15 134 | #define SUBSCRIPTIONDATALEN MAXBUFFERSIZE 135 | #endif 136 | 137 | class AdafruitIO_MQTT; // forward decl 138 | 139 | // Function pointer that returns an int 140 | typedef void (*SubscribeCallbackUInt32Type)(uint32_t); 141 | // returns a double 142 | typedef void (*SubscribeCallbackDoubleType)(double); 143 | // returns a chunk of raw data 144 | typedef void (*SubscribeCallbackBufferType)(char *str, uint16_t len); 145 | // returns an io data wrapper instance 146 | typedef void (AdafruitIO_MQTT::*SubscribeCallbackIOType)(char *str, 147 | uint16_t len); 148 | 149 | extern void printBuffer(uint8_t *buffer, uint16_t len); 150 | 151 | class Adafruit_MQTT_Subscribe; // forward decl 152 | 153 | class Adafruit_MQTT { 154 | public: 155 | Adafruit_MQTT(const char *server, uint16_t port, const char *cid, 156 | const char *user, const char *pass); 157 | 158 | Adafruit_MQTT(const char *server, uint16_t port, const char *user = "", 159 | const char *pass = ""); 160 | virtual ~Adafruit_MQTT() {} 161 | 162 | // Connect to the MQTT server. Returns 0 on success, otherwise an error code 163 | // that indicates something went wrong: 164 | // -1 = Error connecting to server 165 | // 1 = Wrong protocol 166 | // 2 = ID rejected 167 | // 3 = Server unavailable 168 | // 4 = Bad username or password 169 | // 5 = Not authenticated 170 | // 6 = Failed to subscribe 171 | // Use connectErrorString() to get a printable string version of the 172 | // error. 173 | int8_t connect(); 174 | int8_t connect(const char *user, const char *pass); 175 | 176 | // Return a printable string version of the error code returned by 177 | // connect(). This returns a __FlashStringHelper*, which points to a 178 | // string stored in flash, but can be directly passed to e.g. 179 | // Serial.println without any further processing. 180 | const __FlashStringHelper *connectErrorString(int8_t code); 181 | 182 | // Sends MQTT disconnect packet and calls disconnectServer() 183 | bool disconnect(); 184 | 185 | // Return true if connected to the MQTT server, otherwise false. 186 | virtual bool connected() = 0; // Subclasses need to fill this in! 187 | 188 | // Set MQTT last will topic, payload, QOS, and retain. This needs 189 | // to be called before connect() because it is sent as part of the 190 | // connect control packet. 191 | bool will(const char *topic, const char *payload, uint8_t qos = 0, 192 | uint8_t retain = 0); 193 | 194 | // Sets the KeepAlive Interval, in seconds. 195 | bool setKeepAliveInterval(uint16_t keepAlive); 196 | 197 | // Publish a message to a topic using the specified QoS level. Returns true 198 | // if the message was published, false otherwise. 199 | bool publish(const char *topic, const char *payload, uint8_t qos = 0, 200 | bool retain = false); 201 | bool publish(const char *topic, uint8_t *payload, uint16_t bLen, 202 | uint8_t qos = 0, bool retain = false); 203 | 204 | // Add a subscription to receive messages for a topic. Returns true if the 205 | // subscription could be added or was already present, false otherwise. 206 | // Must be called before connect(), subscribing after the connection 207 | // is made is not currently supported. 208 | bool subscribe(Adafruit_MQTT_Subscribe *sub); 209 | 210 | // Unsubscribe from a previously subscribed MQTT topic. 211 | bool unsubscribe(Adafruit_MQTT_Subscribe *sub); 212 | 213 | // Check if any subscriptions have new messages. Will return a reference to 214 | // an Adafruit_MQTT_Subscribe object which has a new message. Should be 215 | // called in the sketch's loop function to ensure new messages are recevied. 216 | // Note that subscribe should be called first for each topic that receives 217 | // messages! 218 | Adafruit_MQTT_Subscribe *readSubscription(int16_t timeout = 0); 219 | 220 | // Handle any data coming in for subscriptions 221 | Adafruit_MQTT_Subscribe *handleSubscriptionPacket(uint16_t len); 222 | 223 | // Execute a subscription packet's associated callback and mark as "read" 224 | void processSubscriptionPacket(Adafruit_MQTT_Subscribe *sub); 225 | 226 | void processPackets(int16_t timeout); 227 | 228 | // Ping the server to ensure the connection is still alive. 229 | bool ping(uint8_t n = 1); 230 | 231 | protected: 232 | // Interface that subclasses need to implement: 233 | 234 | // Connect to the server and return true if successful, false otherwise. 235 | virtual bool connectServer() = 0; 236 | 237 | // Disconnect from the MQTT server. Returns true if disconnected, false 238 | // otherwise. 239 | virtual bool disconnectServer() = 0; // Subclasses need to fill this in! 240 | 241 | // Send data to the server specified by the buffer and length of data. 242 | virtual bool sendPacket(uint8_t *buffer, uint16_t len) = 0; 243 | 244 | // Read MQTT packet from the server. Will read up to maxlen bytes and store 245 | // the data in the provided buffer. Waits up to the specified timeout (in 246 | // milliseconds) for data to be available. 247 | virtual uint16_t readPacket(uint8_t *buffer, uint16_t maxlen, 248 | int16_t timeout) = 0; 249 | 250 | // Read a full packet, keeping note of the correct length 251 | uint16_t readFullPacket(uint8_t *buffer, uint16_t maxsize, uint16_t timeout); 252 | // Properly process packets until you get to one you want 253 | uint16_t processPacketsUntil(uint8_t *buffer, uint8_t waitforpackettype, 254 | uint16_t timeout); 255 | 256 | // Shared state that subclasses can use: 257 | const char *servername; 258 | int16_t portnum; 259 | const char *clientid; 260 | const char *username; 261 | const char *password; 262 | const char *will_topic; 263 | const char *will_payload; 264 | uint8_t will_qos; 265 | uint8_t will_retain; 266 | uint16_t keepAliveInterval; // MQTT KeepAlive time interval, in seconds 267 | uint8_t buffer[MAXBUFFERSIZE]; // one buffer, used for all incoming/outgoing 268 | uint16_t packet_id_counter; 269 | 270 | private: 271 | Adafruit_MQTT_Subscribe *subscriptions[MAXSUBSCRIPTIONS]; 272 | 273 | void flushIncoming(uint16_t timeout); 274 | 275 | // Functions to generate MQTT packets. 276 | uint8_t connectPacket(uint8_t *packet); 277 | uint8_t disconnectPacket(uint8_t *packet); 278 | uint16_t publishPacket(uint8_t *packet, const char *topic, uint8_t *payload, 279 | uint16_t bLen, uint8_t qos, uint16_t maxPacketLen = 0, 280 | bool retain = false); 281 | uint8_t subscribePacket(uint8_t *packet, const char *topic, uint8_t qos); 282 | uint8_t unsubscribePacket(uint8_t *packet, const char *topic); 283 | uint8_t pingPacket(uint8_t *packet); 284 | uint8_t pubackPacket(uint8_t *packet, uint16_t packetid); 285 | }; 286 | 287 | class Adafruit_MQTT_Publish { 288 | public: 289 | Adafruit_MQTT_Publish(Adafruit_MQTT *mqttserver, const char *feed, 290 | uint8_t qos = 0); 291 | 292 | bool publish(const char *s, bool retain = false); 293 | bool publish( 294 | double f, 295 | uint8_t precision = 296 | 2, // Precision controls the minimum number of digits after decimal. 297 | // This might be ignored and a higher precision value sent. 298 | bool retain = false); 299 | bool publish(int32_t i, bool retain = false); 300 | bool publish(uint32_t i, bool retain = false); 301 | bool publish(uint8_t *b, uint16_t bLen, bool retain = false); 302 | 303 | private: 304 | Adafruit_MQTT *mqtt; 305 | const char *topic; 306 | uint8_t qos; 307 | }; 308 | 309 | class Adafruit_MQTT_Subscribe { 310 | public: 311 | Adafruit_MQTT_Subscribe(Adafruit_MQTT *mqttserver, const char *feedname, 312 | uint8_t q = 0); 313 | 314 | void setCallback(SubscribeCallbackUInt32Type callb); 315 | void setCallback(SubscribeCallbackDoubleType callb); 316 | void setCallback(SubscribeCallbackBufferType callb); 317 | void setCallback(AdafruitIO_MQTT *io, SubscribeCallbackIOType callb); 318 | void removeCallback(void); 319 | 320 | const char *topic; 321 | uint8_t qos; 322 | 323 | uint8_t lastread[SUBSCRIPTIONDATALEN]; 324 | // Number valid bytes in lastread. Limited to SUBSCRIPTIONDATALEN-1 to 325 | // ensure nul terminating lastread. 326 | uint16_t datalen; 327 | 328 | SubscribeCallbackUInt32Type callback_uint32t; 329 | SubscribeCallbackDoubleType callback_double; 330 | SubscribeCallbackBufferType callback_buffer; 331 | SubscribeCallbackIOType callback_io; 332 | 333 | AdafruitIO_MQTT *io_mqtt; 334 | 335 | bool new_message; 336 | 337 | private: 338 | Adafruit_MQTT *mqtt; 339 | }; 340 | 341 | #endif -------------------------------------------------------------------------------- /Adafruit_MQTT_Client.cpp: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // 3 | // Copyright (c) 2015 Adafruit Industries 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | // SOFTWARE. 22 | #include "Adafruit_MQTT_Client.h" 23 | 24 | bool Adafruit_MQTT_Client::connectServer() { 25 | // Grab server name from flash and copy to buffer for name resolution. 26 | memset(buffer, 0, sizeof(buffer)); 27 | strcpy((char *)buffer, servername); 28 | DEBUG_PRINT(F("Connecting to: ")); 29 | DEBUG_PRINTLN((char *)buffer); 30 | // Connect and check for success (0 result). 31 | int r = client->connect((char *)buffer, portnum); 32 | DEBUG_PRINT(F("Connect result: ")); 33 | DEBUG_PRINTLN(r); 34 | return r != 0; 35 | } 36 | 37 | bool Adafruit_MQTT_Client::disconnectServer() { 38 | // Stop connection if connected and return success (stop has no indication of 39 | // failure). 40 | if (client->connected()) { 41 | client->stop(); 42 | } 43 | return true; 44 | } 45 | 46 | bool Adafruit_MQTT_Client::connected() { 47 | // Return true if connected, false if not connected. 48 | return client->connected(); 49 | } 50 | 51 | uint16_t Adafruit_MQTT_Client::readPacket(uint8_t *buffer, uint16_t maxlen, 52 | int16_t timeout) { 53 | /* Read data until either the connection is closed, or the idle timeout is 54 | * reached. */ 55 | uint16_t len = 0; 56 | int16_t t = timeout; 57 | 58 | if (maxlen == 0) { // handle zero-length packets 59 | return 0; 60 | } 61 | 62 | while (client->connected() && (timeout >= 0)) { 63 | // DEBUG_PRINT('.'); 64 | while (client->available()) { 65 | // DEBUG_PRINT('!'); 66 | char c = client->read(); 67 | timeout = t; // reset the timeout 68 | buffer[len] = c; 69 | // DEBUG_PRINTLN((uint8_t)c, HEX); 70 | len++; 71 | 72 | if (len == maxlen) { // we read all we want, bail 73 | DEBUG_PRINT(F("Read data:\t")); 74 | DEBUG_PRINTBUFFER(buffer, len); 75 | return len; 76 | } 77 | } 78 | timeout -= MQTT_CLIENT_READINTERVAL_MS; 79 | delay(MQTT_CLIENT_READINTERVAL_MS); 80 | } 81 | return len; 82 | } 83 | 84 | bool Adafruit_MQTT_Client::sendPacket(uint8_t *buffer, uint16_t len) { 85 | uint16_t ret = 0; 86 | uint16_t offset = 0; 87 | while (len > 0) { 88 | if (client->connected()) { 89 | // send 250 bytes at most at a time, can adjust this later based on Client 90 | 91 | uint16_t sendlen = len > 250 ? 250 : len; 92 | // Serial.print("Sending: "); Serial.println(sendlen); 93 | ret = client->write(buffer + offset, sendlen); 94 | DEBUG_PRINT(F("Client sendPacket returned: ")); 95 | DEBUG_PRINTLN(ret); 96 | len -= ret; 97 | offset += ret; 98 | 99 | if (ret != sendlen) { 100 | DEBUG_PRINTLN("Failed to send packet."); 101 | return false; 102 | } 103 | } else { 104 | DEBUG_PRINTLN(F("Connection failed!")); 105 | return false; 106 | } 107 | } 108 | return true; 109 | } 110 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Client.h: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // 3 | // Copyright (c) 2015 Adafruit Industries 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | // SOFTWARE. 22 | #ifndef _ADAFRUIT_MQTT_CLIENT_H_ 23 | #define _ADAFRUIT_MQTT_CLIENT_H_ 24 | 25 | #include "Adafruit_MQTT.h" 26 | #include "Client.h" 27 | 28 | // How long to delay waiting for new data to be available in readPacket. 29 | #define MQTT_CLIENT_READINTERVAL_MS 10 30 | 31 | // MQTT client implementation for a generic Arduino Client interface. Can work 32 | // with almost all Arduino network hardware like ethernet shield, wifi shield, 33 | // and even other platforms like ESP8266. 34 | class Adafruit_MQTT_Client : public Adafruit_MQTT { 35 | public: 36 | Adafruit_MQTT_Client(Client *client, const char *server, uint16_t port, 37 | const char *cid, const char *user, const char *pass) 38 | : Adafruit_MQTT(server, port, cid, user, pass), client(client) {} 39 | 40 | Adafruit_MQTT_Client(Client *client, const char *server, uint16_t port, 41 | const char *user = "", const char *pass = "") 42 | : Adafruit_MQTT(server, port, user, pass), client(client) {} 43 | 44 | bool connected() override; 45 | 46 | protected: 47 | bool connectServer() override; 48 | bool disconnectServer() override; 49 | uint16_t readPacket(uint8_t *buffer, uint16_t maxlen, 50 | int16_t timeout) override; 51 | bool sendPacket(uint8_t *buffer, uint16_t len) override; 52 | 53 | private: 54 | Client *client; 55 | }; 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /Adafruit_MQTT_FONA.h: -------------------------------------------------------------------------------- 1 | // The MIT License (MIT) 2 | // 3 | // Copyright (c) 2015 Adafruit Industries 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | // SOFTWARE. 22 | #ifndef _ADAFRUIT_MQTT_FONA_H_ 23 | #define _ADAFRUIT_MQTT_FONA_H_ 24 | 25 | #include "Adafruit_MQTT.h" 26 | #include 27 | 28 | #define MQTT_FONA_INTERAVAILDELAY 100 29 | #define MQTT_FONA_QUERYDELAY 500 30 | 31 | // FONA-specific version of the Adafruit_MQTT class. 32 | // Note that this is defined as a header-only class to prevent issues with using 33 | // the library on non-FONA platforms (since Arduino will include all .cpp files 34 | // in the compilation of the library). 35 | class Adafruit_MQTT_FONA : public Adafruit_MQTT { 36 | public: 37 | Adafruit_MQTT_FONA(Adafruit_FONA *f, const char *server, uint16_t port, 38 | const char *cid, const char *user, const char *pass) 39 | : Adafruit_MQTT(server, port, cid, user, pass), fona(f) {} 40 | 41 | Adafruit_MQTT_FONA(Adafruit_FONA *f, const char *server, uint16_t port, 42 | const char *user = "", const char *pass = "") 43 | : Adafruit_MQTT(server, port, user, pass), fona(f) {} 44 | 45 | bool connected() { 46 | // Return true if connected, false if not connected. 47 | return fona->TCPconnected(); 48 | } 49 | 50 | protected: 51 | bool connectServer() override { 52 | char server[40]; 53 | strncpy(server, servername, 40); 54 | #ifdef ADAFRUIT_SLEEPYDOG_H 55 | Watchdog.reset(); 56 | #endif 57 | 58 | // connect to server 59 | DEBUG_PRINTLN(F("Connecting to TCP")); 60 | return fona->TCPconnect(server, portnum); 61 | } 62 | 63 | bool disconnectServer() override { return fona->TCPclose(); } 64 | 65 | uint16_t readPacket(uint8_t *buffer, uint16_t maxlen, 66 | int16_t timeout) override { 67 | uint8_t *buffp = buffer; 68 | DEBUG_PRINTLN(F("Reading data..")); 69 | 70 | if (!fona->TCPconnected()) 71 | return 0; 72 | 73 | /* Read data until either the connection is closed, or the idle timeout is 74 | * reached. */ 75 | uint16_t len = 0; 76 | int16_t t = timeout; 77 | uint16_t avail; 78 | 79 | while (fona->TCPconnected() && (timeout >= 0)) { 80 | // DEBUG_PRINT('.'); 81 | while (avail = fona->TCPavailable()) { 82 | // DEBUG_PRINT('!'); 83 | 84 | if (len + avail > maxlen) { 85 | avail = maxlen - len; 86 | if (avail == 0) 87 | return len; 88 | } 89 | 90 | // try to read the data into the end of the pointer 91 | if (!fona->TCPread(buffp, avail)) 92 | return len; 93 | 94 | // read it! advance pointer 95 | buffp += avail; 96 | len += avail; 97 | timeout = t; // reset the timeout 98 | 99 | // DEBUG_PRINTLN((uint8_t)c, HEX); 100 | 101 | if (len == maxlen) { // we read all we want, bail 102 | DEBUG_PRINT(F("Read:\t")); 103 | DEBUG_PRINTBUFFER(buffer, len); 104 | return len; 105 | } 106 | } 107 | #ifdef ADAFRUIT_SLEEPYDOG_H 108 | Watchdog.reset(); 109 | #endif 110 | timeout -= MQTT_FONA_INTERAVAILDELAY; 111 | timeout -= MQTT_FONA_QUERYDELAY; // this is how long it takes to query the 112 | // FONA for avail() 113 | delay(MQTT_FONA_INTERAVAILDELAY); 114 | } 115 | 116 | return len; 117 | } 118 | 119 | bool sendPacket(uint8_t *buffer, uint16_t len) override { 120 | DEBUG_PRINTLN(F("Writing packet")); 121 | if (fona->TCPconnected()) { 122 | boolean ret = fona->TCPsend((char *)buffer, len); 123 | // DEBUG_PRINT(F("sendPacket returned: ")); DEBUG_PRINTLN(ret); 124 | if (!ret) { 125 | DEBUG_PRINTLN("Failed to send packet."); 126 | return false; 127 | } 128 | } else { 129 | DEBUG_PRINTLN(F("Connection failed!")); 130 | return false; 131 | } 132 | return true; 133 | } 134 | 135 | private: 136 | uint32_t serverip; 137 | Adafruit_FONA *fona; 138 | }; 139 | 140 | #endif 141 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Adafruit Industries 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Adafruit MQTT Library [![Build Status](https://github.com/adafruit/Adafruit_MQTT_Library/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_MQTT_Library/actions) 2 | 3 | Arduino library for MQTT support, including access to Adafruit IO. Works with 4 | the Adafruit FONA, Arduino Yun, ESP8266 Arduino platforms, and anything that supports 5 | Arduino's Client interface (like Ethernet shield). 6 | 7 | See included examples for how to use the library to access an MQTT service to 8 | publish and subscribe to feeds. Note that this does not support the full MQTT 9 | spec but is intended to support enough for QoS 0 and 1 publishing. 10 | 11 | Depends on the following other libraries depending on the target platform: 12 | 13 | - [Adafruit SleepyDog](https://github.com/adafruit/Adafruit_SleepyDog), watchdog 14 | library used by FONA code for reliability. 15 | 16 | - [Adafruit FONA](https://github.com/adafruit/Adafruit_FONA_Library), required for 17 | the FONA hardware. 18 | 19 | Future todos: 20 | 21 | - Subscription callbacks 22 | 23 | - remove watchdog 24 | 25 | 26 | 27 | ## Compatibility 28 | 29 | MCU | Tested Works | Doesn't Work | Not Tested | Notes 30 | ------------------ | :----------: | :----------: | :---------: | ----- 31 | Atmega328 @ 16MHz | | | X | 32 | Atmega328 @ 12MHz | | | X | 33 | Atmega32u4 @ 16MHz | | | X | 34 | Atmega32u4 @ 8MHz | | | X | 35 | ESP8266 | | | X | 36 | Atmega2560 @ 16MHz | | | X | 37 | ATSAM3X8E | | | X | 38 | ATSAM21D | | | X | 39 | ATSAMD51J20 | | | X | 40 | ATtiny85 @ 16MHz | | | X | 41 | ATtiny85 @ 8MHz | | | X | 42 | Intel Curie @ 32MHz | | | X | 43 | STM32F2 | | | X | 44 | 45 | * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini 46 | * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V 47 | * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 48 | * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro 49 | * ESP8266 : Adafruit Huzzah 50 | * ATmega2560 @ 16MHz : Arduino Mega 51 | * ATSAM3X8E : Arduino Due 52 | * ATSAM21D : Arduino Zero, M0 Pro 53 | * ATSAMD51J20: Adafruit PyPortal 54 | * ATtiny85 @ 16MHz : Adafruit Trinket 5V 55 | * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V 56 | 57 | 58 | -------------------------------------------------------------------------------- /examples/adafruitio_anon_time_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_anon_time_esp8266/adafruitio_anon_time_esp8266.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library ESP8266 Adafruit IO Anonymous Time Query 3 | 4 | Must use the latest version of ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board & Feather 8 | ----> https://www.adafruit.com/product/2471 9 | ----> https://www.adafruit.com/products/2821 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Adafruit Industries. 16 | MIT license, all text above must be included in any redistribution 17 | ****************************************************/ 18 | #include 19 | #include "Adafruit_MQTT.h" 20 | #include "Adafruit_MQTT_Client.h" 21 | 22 | /************************* WiFi Access Point *********************************/ 23 | #define WLAN_SSID "network" 24 | #define WLAN_PASS "password" 25 | 26 | /************************* Adafruit.io Setup *********************************/ 27 | #define AIO_SERVER "io.adafruit.com" 28 | #define AIO_SERVERPORT 8883 29 | 30 | WiFiClientSecure client; 31 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT); 32 | 33 | Adafruit_MQTT_Subscribe timefeed = Adafruit_MQTT_Subscribe(&mqtt, "time/seconds"); 34 | 35 | // set timezone offset from UTC 36 | int timeZone = -4; // UTC - 4 eastern daylight time (nyc) 37 | int interval = 4; // trigger every X hours 38 | 39 | int last_min = -1; 40 | 41 | void timecallback(uint32_t current) { 42 | // adjust to local time zone 43 | current += (timeZone * 60 * 60); 44 | int curr_hour = (current / 60 / 60) % 24; 45 | int curr_min = (current / 60 ) % 60; 46 | int curr_sec = (current) % 60; 47 | 48 | Serial.print("Time: "); 49 | Serial.print(curr_hour); Serial.print(':'); 50 | Serial.print(curr_min); Serial.print(':'); 51 | Serial.println(curr_sec); 52 | 53 | // only trigger on minute change 54 | if(curr_min != last_min) { 55 | last_min = curr_min; 56 | 57 | Serial.println("This will print out every minute!"); 58 | } 59 | } 60 | 61 | void setup() { 62 | 63 | Serial.begin(115200); 64 | delay(10); 65 | 66 | Serial.print(F("\nAdafruit IO anonymous Time Demo")); 67 | 68 | WiFi.begin(WLAN_SSID, WLAN_PASS); 69 | while (WiFi.status() != WL_CONNECTED) { 70 | delay(500); 71 | Serial.print(F(".")); 72 | } 73 | Serial.println(F(" WiFi connected.")); 74 | 75 | timefeed.setCallback(timecallback); 76 | mqtt.subscribe(&timefeed); 77 | 78 | } 79 | 80 | void loop() { 81 | 82 | // Ensure the connection to the MQTT server is alive (this will make the first 83 | // connection and automatically reconnect when disconnected). See the MQTT_connect 84 | // function definition further below. 85 | MQTT_connect(); 86 | 87 | // wait 10 seconds for subscription messages 88 | // since we have no other tasks in this example. 89 | mqtt.processPackets(10000); 90 | 91 | // keep the connection alive 92 | mqtt.ping(); 93 | 94 | } 95 | 96 | // Function to connect and reconnect as necessary to the MQTT server. 97 | // Should be called in the loop function and it will take care if connecting. 98 | void MQTT_connect() { 99 | int8_t ret; 100 | 101 | // Stop if already connected. 102 | if (mqtt.connected()) { 103 | return; 104 | } 105 | 106 | Serial.print("Connecting to MQTT... "); 107 | 108 | uint8_t retries = 3; 109 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 110 | Serial.println(mqtt.connectErrorString(ret)); 111 | Serial.println("Retrying MQTT connection in 5 seconds..."); 112 | mqtt.disconnect(); 113 | delay(5000); // wait 5 seconds 114 | retries--; 115 | if (retries == 0) { 116 | // basically die and wait for WDT to reset me 117 | while (1); 118 | } 119 | } 120 | 121 | Serial.println("MQTT Connected!"); 122 | } -------------------------------------------------------------------------------- /examples/adafruitio_errors_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_errors_esp8266/adafruitio_errors_esp8266.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library ESP8266 Example 3 | 4 | Must use ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board & Feather 8 | ----> https://www.adafruit.com/product/2471 9 | ----> https://www.adafruit.com/products/2821 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Tony DiCola for Adafruit Industries. 16 | Error examples by Todd Treece for Adafruit Industries. 17 | MIT license, all text above must be included in any redistribution 18 | ****************************************************/ 19 | #include 20 | #include "Adafruit_MQTT.h" 21 | #include "Adafruit_MQTT_Client.h" 22 | 23 | /************************* WiFi Access Point *********************************/ 24 | 25 | #define WLAN_SSID "...your SSID..." 26 | #define WLAN_PASS "...your password..." 27 | 28 | /************************* Adafruit.io Setup *********************************/ 29 | 30 | #define AIO_SERVER "io.adafruit.com" 31 | #define AIO_SERVERPORT 1883 // 8883 for MQTTS 32 | #define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..." 33 | #define AIO_KEY "...your AIO key..." 34 | 35 | /************ Global State (you don't need to change this!) ******************/ 36 | 37 | // Create an ESP8266 WiFiClient class to connect to the MQTT server. 38 | WiFiClient client; 39 | // or... use WiFiFlientSecure for SSL 40 | //WiFiClientSecure client; 41 | 42 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 43 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 44 | 45 | /****************************** Feeds ***************************************/ 46 | 47 | // Setup a feed called 'photocell' for publishing. 48 | // Notice MQTT paths for AIO follow the form: /feeds/ 49 | Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell"); 50 | 51 | // Setup a feed called 'onoff' for subscribing to changes. 52 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff"); 53 | 54 | /*************************** Error Reporting *********************************/ 55 | 56 | Adafruit_MQTT_Subscribe errors = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/errors"); 57 | Adafruit_MQTT_Subscribe throttle = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/throttle"); 58 | 59 | /*************************** Sketch Code ************************************/ 60 | 61 | // Bug workaround for Arduino 1.6.6, it seems to need a function declaration 62 | // for some reason (only affects ESP8266, likely an arduino-builder bug). 63 | void MQTT_connect(); 64 | 65 | void setup() { 66 | Serial.begin(115200); 67 | delay(10); 68 | 69 | Serial.println(F("Adafruit MQTT demo")); 70 | 71 | // Connect to WiFi access point. 72 | Serial.println(); Serial.println(); 73 | Serial.print("Connecting to "); 74 | Serial.println(WLAN_SSID); 75 | 76 | WiFi.begin(WLAN_SSID, WLAN_PASS); 77 | while (WiFi.status() != WL_CONNECTED) { 78 | delay(500); 79 | Serial.print("."); 80 | } 81 | Serial.println(); 82 | 83 | Serial.println("WiFi connected"); 84 | Serial.println("IP address: "); Serial.println(WiFi.localIP()); 85 | 86 | // Setup MQTT subscription for onoff feed 87 | mqtt.subscribe(&onoffbutton); 88 | 89 | // Setup MQTT subscriptions for throttle & error messages 90 | mqtt.subscribe(&throttle); 91 | mqtt.subscribe(&errors); 92 | 93 | } 94 | 95 | uint32_t x=0; 96 | 97 | void loop() { 98 | // Ensure the connection to the MQTT server is alive (this will make the first 99 | // connection and automatically reconnect when disconnected). See the MQTT_connect 100 | // function definition further below. 101 | MQTT_connect(); 102 | 103 | // this is our 'wait for incoming subscription packets' busy subloop 104 | // try to spend your time here 105 | Adafruit_MQTT_Subscribe *subscription; 106 | while ((subscription = mqtt.readSubscription(5000))) { 107 | if (subscription == &onoffbutton) { 108 | Serial.print(F("Got onoff: ")); 109 | Serial.println((char *)onoffbutton.lastread); 110 | } else if(subscription == &errors) { 111 | Serial.print(F("ERROR: ")); 112 | Serial.println((char *)errors.lastread); 113 | } else if(subscription == &throttle) { 114 | Serial.println((char *)throttle.lastread); 115 | } 116 | } 117 | 118 | // Now we can publish stuff! 119 | Serial.print(F("\nSending photocell val ")); 120 | Serial.print(x); 121 | Serial.print("..."); 122 | if (! photocell.publish(x++)) { 123 | Serial.println(F("Failed")); 124 | } else { 125 | Serial.println(F("OK!")); 126 | } 127 | 128 | } 129 | 130 | // Function to connect and reconnect as necessary to the MQTT server. 131 | // Should be called in the loop function and it will take care if connecting. 132 | void MQTT_connect() { 133 | int8_t ret; 134 | 135 | // Stop if already connected. 136 | if (mqtt.connected()) { 137 | return; 138 | } 139 | 140 | Serial.print("Connecting to MQTT... "); 141 | 142 | uint8_t retries = 3; 143 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 144 | Serial.println(mqtt.connectErrorString(ret)); 145 | Serial.println("Retrying MQTT connection in 5 seconds..."); 146 | mqtt.disconnect(); 147 | delay(5000); // wait 5 seconds 148 | retries--; 149 | if (retries == 0) { 150 | // basically die and wait for WDT to reset me 151 | while (1); 152 | } 153 | } 154 | Serial.println("MQTT Connected!"); 155 | } 156 | -------------------------------------------------------------------------------- /examples/adafruitio_secure_airlift/.esp8266.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_secure_airlift/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_secure_airlift/adafruitio_secure_airlift.ino: -------------------------------------------------------------------------------- 1 | /**************************************************************** 2 | Adafruit MQTT Library, Adafruit IO SSL/TLS Example for AirLift 3 | 4 | Must use the latest version of nina-fw from: 5 | https://github.com/adafruit/nina-fw 6 | 7 | Works great with Adafruit AirLift ESP32 Co-Processors! 8 | --> https://www.adafruit.com/product/4201 9 | --> https://www.adafruit.com/product/4116 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Brent Rubell for Adafruit Industries. 16 | MIT license, all text above must be included in any redistribution 17 | *******************************************************************/ 18 | 19 | #include 20 | #include 21 | 22 | // For AirLift Breakout/Wing/Shield: Configure the following to match the ESP32 Pins! 23 | #if !defined(SPIWIFI_SS) 24 | // Don't change the names of these #define's! they match the variant ones 25 | #define SPIWIFI SPI 26 | #define SPIWIFI_SS 11 // Chip select pin 27 | #define SPIWIFI_ACK 10 // a.k.a BUSY or READY pin 28 | #define ESP32_RESETN 9 // Reset pin 29 | #define ESP32_GPIO0 -1 // Not connected 30 | #define SET_PINS 1 // Pins were set using this IFNDEF 31 | #endif 32 | 33 | #include "Adafruit_MQTT.h" 34 | #include "Adafruit_MQTT_Client.h" 35 | 36 | /************************* WiFi Access Point *********************************/ 37 | 38 | #define WLAN_SSID "WLAN_SSID" 39 | #define WLAN_PASS "WIFI_PASSWORD" 40 | int keyIndex = 0; // your network key Index number (needed only for WEP) 41 | 42 | int status = WL_IDLE_STATUS; 43 | /************************* Adafruit.io Setup *********************************/ 44 | 45 | #define AIO_SERVER "io.adafruit.com" 46 | // Using port 8883 for MQTTS 47 | #define AIO_SERVERPORT 8883 48 | // Adafruit IO Account Configuration 49 | // (to obtain these values, visit https://io.adafruit.com and click on Active Key) 50 | #define AIO_USERNAME "YOUR_ADAFRUIT_IO_USERNAME" 51 | #define AIO_KEY "YOUR_ADAFRUIT_IO_KEY" 52 | 53 | /************ Global State (you don't need to change this!) ******************/ 54 | 55 | // WiFiSSLClient for SSL/TLS support 56 | WiFiSSLClient client; 57 | 58 | // Setup the MQTT client class by WLAN_PASSing in the WiFi client and MQTT server and login details. 59 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 60 | /****************************** Feeds ***************************************/ 61 | 62 | // Setup a feed called 'test' for publishing. 63 | // Notice MQTT paths for AIO follow the form: /feeds/ 64 | Adafruit_MQTT_Publish test = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/test"); 65 | 66 | /*************************** Sketch Code ************************************/ 67 | 68 | void setup() 69 | { 70 | //Initialize serial and wait for port to open: 71 | Serial.begin(115200); 72 | while (!Serial) 73 | { 74 | ; // wait for serial port to connect. Needed for native USB port only 75 | } 76 | 77 | // if the AirLift's pins were defined above... 78 | #ifdef SET_PINS 79 | WiFi.setPins(SPIWIFI_SS, SPIWIFI_ACK, ESP32_RESETN, ESP32_GPIO0, &SPIWIFI); 80 | #endif 81 | 82 | // check for the wifi module 83 | while (WiFi.status() == WL_NO_MODULE) 84 | { 85 | Serial.println("Communication with WiFi module failed!"); 86 | delay(1000); 87 | } 88 | 89 | String fv = WiFi.firmwareVersion(); 90 | if (fv < "1.0.0") 91 | { 92 | Serial.println("Please upgrade the firmware"); 93 | } 94 | 95 | // attempt to connect to Wifi network: 96 | Serial.print("Attempting to connect to SSID: "); 97 | Serial.println(WLAN_SSID); 98 | // Connect to WPA/WPA2 network. Change this line if using open or WEP network: 99 | do 100 | { 101 | status = WiFi.begin(WLAN_SSID, WLAN_PASS); 102 | delay(100); // wait until connected 103 | } while (status != WL_CONNECTED); 104 | Serial.println("Connected to wifi"); 105 | printWiFiStatus(); 106 | } 107 | 108 | uint32_t x = 0; 109 | 110 | void loop() 111 | { 112 | // Ensure the connection to the MQTT server is alive (this will make the first 113 | // connection and automatically reconnect when disconnected). See the MQTT_connect 114 | // function definition further below. 115 | MQTT_connect(); 116 | 117 | // Now we can publish stuff! 118 | Serial.print(F("\nSending val ")); 119 | Serial.print(x); 120 | Serial.print(F(" to test feed...")); 121 | if (!test.publish(x++)) 122 | { 123 | Serial.println(F("Failed")); 124 | } 125 | else 126 | { 127 | Serial.println(F("OK!")); 128 | } 129 | 130 | // wait a couple seconds to avoid rate limit 131 | delay(2000); 132 | } 133 | 134 | // Function to connect and reconnect as necessary to the MQTT server. 135 | // Should be called in the loop function and it will take care if connecting. 136 | void MQTT_connect() 137 | { 138 | int8_t ret; 139 | 140 | // Stop if already connected. 141 | if (mqtt.connected()) 142 | { 143 | return; 144 | } 145 | 146 | Serial.print("Connecting to MQTT... "); 147 | 148 | uint8_t retries = 3; 149 | while ((ret = mqtt.connect()) != 0) 150 | { // connect will return 0 for connected 151 | Serial.println(mqtt.connectErrorString(ret)); 152 | Serial.println("Retrying MQTT connection in 5 seconds..."); 153 | mqtt.disconnect(); 154 | delay(5000); // wait 5 seconds 155 | retries--; 156 | if (retries == 0) 157 | { 158 | // basically die and wait for WDT to reset me 159 | while (1) 160 | ; 161 | } 162 | } 163 | 164 | Serial.println("MQTT Connected!"); 165 | } 166 | 167 | void printWiFiStatus() 168 | { 169 | // print the SSID of the network you're attached to: 170 | Serial.print("SSID: "); 171 | Serial.println(WiFi.SSID()); 172 | 173 | // print your board's IP address: 174 | IPAddress ip = WiFi.localIP(); 175 | Serial.print("IP Address: "); 176 | Serial.println(ip); 177 | 178 | // print the received signal strength: 179 | long rssi = WiFi.RSSI(); 180 | Serial.print("signal strength (RSSI):"); 181 | Serial.print(rssi); 182 | Serial.println(" dBm"); 183 | } -------------------------------------------------------------------------------- /examples/adafruitio_secure_esp32/.esp8266.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_secure_esp32/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_secure_esp32/adafruitio_secure_esp32.ino: -------------------------------------------------------------------------------- 1 | /*********************************************************************** 2 | Adafruit MQTT Library ESP32 Adafruit IO SSL/TLS example 3 | 4 | Use the latest version of the ESP32 Arduino Core: 5 | https://github.com/espressif/arduino-esp32 6 | 7 | Works great with Adafruit Huzzah32 Feather and Breakout Board: 8 | https://www.adafruit.com/product/3405 9 | https://www.adafruit.com/products/4172 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Tony DiCola for Adafruit Industries. 16 | Modified by Brent Rubell for Adafruit Industries 17 | MIT license, all text above must be included in any redistribution 18 | **********************************************************************/ 19 | #include 20 | #include "WiFiClientSecure.h" 21 | #include "Adafruit_MQTT.h" 22 | #include "Adafruit_MQTT_Client.h" 23 | 24 | /************************* WiFi Access Point *********************************/ 25 | 26 | #define WLAN_SSID "WLAN_SSID" 27 | #define WLAN_PASS "WIFI_PASSWORD" 28 | 29 | /************************* Adafruit.io Setup *********************************/ 30 | 31 | #define AIO_SERVER "io.adafruit.com" 32 | 33 | // Using port 8883 for MQTTS 34 | #define AIO_SERVERPORT 8883 35 | 36 | // Adafruit IO Account Configuration 37 | // (to obtain these values, visit https://io.adafruit.com and click on Active Key) 38 | #define AIO_USERNAME "YOUR_ADAFRUIT_IO_USERNAME" 39 | #define AIO_KEY "YOUR_ADAFRUIT_IO_KEY" 40 | 41 | /************ Global State (you don't need to change this!) ******************/ 42 | 43 | // WiFiFlientSecure for SSL/TLS support 44 | WiFiClientSecure client; 45 | 46 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 47 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 48 | 49 | // io.adafruit.com root CA 50 | const char* adafruitio_root_ca = \ 51 | "-----BEGIN CERTIFICATE-----\n" 52 | "MIIEjTCCA3WgAwIBAgIQDQd4KhM/xvmlcpbhMf/ReTANBgkqhkiG9w0BAQsFADBh\n" 53 | "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" 54 | "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\n" 55 | "MjAeFw0xNzExMDIxMjIzMzdaFw0yNzExMDIxMjIzMzdaMGAxCzAJBgNVBAYTAlVT\n" 56 | "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" 57 | "b20xHzAdBgNVBAMTFkdlb1RydXN0IFRMUyBSU0EgQ0EgRzEwggEiMA0GCSqGSIb3\n" 58 | "DQEBAQUAA4IBDwAwggEKAoIBAQC+F+jsvikKy/65LWEx/TMkCDIuWegh1Ngwvm4Q\n" 59 | "yISgP7oU5d79eoySG3vOhC3w/3jEMuipoH1fBtp7m0tTpsYbAhch4XA7rfuD6whU\n" 60 | "gajeErLVxoiWMPkC/DnUvbgi74BJmdBiuGHQSd7LwsuXpTEGG9fYXcbTVN5SATYq\n" 61 | "DfbexbYxTMwVJWoVb6lrBEgM3gBBqiiAiy800xu1Nq07JdCIQkBsNpFtZbIZhsDS\n" 62 | "fzlGWP4wEmBQ3O67c+ZXkFr2DcrXBEtHam80Gp2SNhou2U5U7UesDL/xgLK6/0d7\n" 63 | "6TnEVMSUVJkZ8VeZr+IUIlvoLrtjLbqugb0T3OYXW+CQU0kBAgMBAAGjggFAMIIB\n" 64 | "PDAdBgNVHQ4EFgQUlE/UXYvkpOKmgP792PkA76O+AlcwHwYDVR0jBBgwFoAUTiJU\n" 65 | "IBiV5uNu5g/6+rkS7QYXjzkwDgYDVR0PAQH/BAQDAgGGMB0GA1UdJQQWMBQGCCsG\n" 66 | "AQUFBwMBBggrBgEFBQcDAjASBgNVHRMBAf8ECDAGAQH/AgEAMDQGCCsGAQUFBwEB\n" 67 | "BCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEIGA1Ud\n" 68 | "HwQ7MDkwN6A1oDOGMWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEds\n" 69 | "b2JhbFJvb3RHMi5jcmwwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEW\n" 70 | "HGh0dHBzOi8vd3d3LmRpZ2ljZXJ0LmNvbS9DUFMwDQYJKoZIhvcNAQELBQADggEB\n" 71 | "AIIcBDqC6cWpyGUSXAjjAcYwsK4iiGF7KweG97i1RJz1kwZhRoo6orU1JtBYnjzB\n" 72 | "c4+/sXmnHJk3mlPyL1xuIAt9sMeC7+vreRIF5wFBC0MCN5sbHwhNN1JzKbifNeP5\n" 73 | "ozpZdQFmkCo+neBiKR6HqIA+LMTMCMMuv2khGGuPHmtDze4GmEGZtYLyF8EQpa5Y\n" 74 | "jPuV6k2Cr/N3XxFpT3hRpt/3usU/Zb9wfKPtWpoznZ4/44c1p9rzFcZYrWkj3A+7\n" 75 | "TNBJE0GmP2fhXhP1D/XVfIW/h0yCJGEiV9Glm/uGOa3DXHlmbAcxSyCRraG+ZBkA\n" 76 | "7h4SeM6Y8l/7MBRpPCz6l8Y=\n" 77 | "-----END CERTIFICATE-----\n"; 78 | 79 | /****************************** Feeds ***************************************/ 80 | 81 | // Setup a feed called 'test' for publishing. 82 | // Notice MQTT paths for AIO follow the form: /feeds/ 83 | Adafruit_MQTT_Publish test = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/test"); 84 | 85 | /*************************** Sketch Code ************************************/ 86 | 87 | void setup() { 88 | Serial.begin(115200); 89 | delay(10); 90 | 91 | Serial.println(F("Adafruit IO MQTTS (SSL/TLS) Example")); 92 | 93 | // Connect to WiFi access point. 94 | Serial.println(); Serial.println(); 95 | Serial.print("Connecting to "); 96 | Serial.println(WLAN_SSID); 97 | 98 | delay(1000); 99 | 100 | WiFi.begin(WLAN_SSID, WLAN_PASS); 101 | delay(2000); 102 | 103 | while (WiFi.status() != WL_CONNECTED) { 104 | delay(500); 105 | Serial.print("."); 106 | } 107 | Serial.println(); 108 | 109 | Serial.println("WiFi connected"); 110 | Serial.println("IP address: "); Serial.println(WiFi.localIP()); 111 | 112 | // Set Adafruit IO's root CA 113 | client.setCACert(adafruitio_root_ca); 114 | } 115 | 116 | uint32_t x=0; 117 | 118 | void loop() { 119 | // Ensure the connection to the MQTT server is alive (this will make the first 120 | // connection and automatically reconnect when disconnected). See the MQTT_connect 121 | // function definition further below. 122 | MQTT_connect(); 123 | 124 | // Now we can publish stuff! 125 | Serial.print(F("\nSending val ")); 126 | Serial.print(x); 127 | Serial.print(F(" to test feed...")); 128 | if (! test.publish(x++)) { 129 | Serial.println(F("Failed")); 130 | } else { 131 | Serial.println(F("OK!")); 132 | } 133 | 134 | // wait a couple seconds to avoid rate limit 135 | delay(2000); 136 | 137 | } 138 | 139 | // Function to connect and reconnect as necessary to the MQTT server. 140 | // Should be called in the loop function and it will take care if connecting. 141 | void MQTT_connect() { 142 | int8_t ret; 143 | 144 | // Stop if already connected. 145 | if (mqtt.connected()) { 146 | return; 147 | } 148 | 149 | Serial.print("Connecting to MQTT... "); 150 | 151 | uint8_t retries = 3; 152 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 153 | Serial.println(mqtt.connectErrorString(ret)); 154 | Serial.println("Retrying MQTT connection in 5 seconds..."); 155 | mqtt.disconnect(); 156 | delay(5000); // wait 5 seconds 157 | retries--; 158 | if (retries == 0) { 159 | // basically die and wait for WDT to reset me 160 | while (1); 161 | } 162 | } 163 | 164 | Serial.println("MQTT Connected!"); 165 | } 166 | -------------------------------------------------------------------------------- /examples/adafruitio_secure_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_secure_esp8266/adafruitio_secure_esp8266.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library ESP8266 Adafruit IO SSL/TLS example 3 | 4 | Must use the latest version of ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board & Feather 8 | ----> https://www.adafruit.com/product/2471 9 | ----> https://www.adafruit.com/products/2821 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Tony DiCola for Adafruit Industries. 16 | SSL/TLS additions by Todd Treece for Adafruit Industries. 17 | MIT license, all text above must be included in any redistribution 18 | ****************************************************/ 19 | #include 20 | #include "Adafruit_MQTT.h" 21 | #include "Adafruit_MQTT_Client.h" 22 | 23 | /************************* WiFi Access Point *********************************/ 24 | 25 | #define WLAN_SSID "WLAN_SSID" 26 | #define WLAN_PASS "WIFI_PASSWORD" 27 | 28 | /************************* Adafruit.io Setup *********************************/ 29 | 30 | #define AIO_SERVER "io.adafruit.com" 31 | // Using port 8883 for MQTTS 32 | #define AIO_SERVERPORT 8883 33 | // Adafruit IO Account Configuration 34 | // (to obtain these values, visit https://io.adafruit.com and click on Active Key) 35 | #define AIO_USERNAME "YOUR_ADAFRUIT_IO_USERNAME" 36 | #define AIO_KEY "YOUR_ADAFRUIT_IO_KEY" 37 | 38 | /************ Global State (you don't need to change this!) ******************/ 39 | 40 | // WiFiFlientSecure for SSL/TLS support 41 | WiFiClientSecure client; 42 | 43 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 44 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 45 | 46 | // io.adafruit.com SHA1 fingerprint 47 | /* WARNING - This value was last updated on 07/02/24 (expires Aug2025) and may not be up-to-date! 48 | * If security is a concern for your project, we strongly recommend users impacted by this moving 49 | * to ESP32 which has certificate verification by storing root certs and having a 50 | * chain-of-trust rather than doing individual certificate fingerprints. 51 | */ 52 | static const char *fingerprint PROGMEM = "23 97 B0 6A 5A DA 2C F7 F3 3D 0E AB 9B E8 F7 3A 97 A4 07 C1"; 53 | 54 | /****************************** Feeds ***************************************/ 55 | 56 | // Setup a feed called 'test' for publishing. 57 | // Notice MQTT paths for AIO follow the form: /feeds/ 58 | Adafruit_MQTT_Publish test = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/test"); 59 | 60 | /*************************** Sketch Code ************************************/ 61 | 62 | void setup() { 63 | Serial.begin(115200); 64 | delay(10); 65 | 66 | Serial.println(F("Adafruit IO MQTTS (SSL/TLS) Example")); 67 | 68 | // Connect to WiFi access point. 69 | Serial.println(); Serial.println(); 70 | Serial.print("Connecting to "); 71 | Serial.println(WLAN_SSID); 72 | 73 | delay(1000); 74 | 75 | WiFi.begin(WLAN_SSID, WLAN_PASS); 76 | delay(2000); 77 | 78 | while (WiFi.status() != WL_CONNECTED) { 79 | delay(500); 80 | Serial.print("."); 81 | } 82 | Serial.println(); 83 | 84 | Serial.println("WiFi connected"); 85 | Serial.println("IP address: "); Serial.println(WiFi.localIP()); 86 | 87 | // check the fingerprint of io.adafruit.com's SSL cert 88 | client.setFingerprint(fingerprint); 89 | } 90 | 91 | uint32_t x=0; 92 | 93 | void loop() { 94 | // Ensure the connection to the MQTT server is alive (this will make the first 95 | // connection and automatically reconnect when disconnected). See the MQTT_connect 96 | // function definition further below. 97 | MQTT_connect(); 98 | 99 | // Now we can publish stuff! 100 | Serial.print(F("\nSending val ")); 101 | Serial.print(x); 102 | Serial.print(F(" to test feed...")); 103 | if (! test.publish(x++)) { 104 | Serial.println(F("Failed")); 105 | } else { 106 | Serial.println(F("OK!")); 107 | } 108 | 109 | // wait a couple seconds to avoid rate limit 110 | delay(2000); 111 | 112 | } 113 | 114 | // Function to connect and reconnect as necessary to the MQTT server. 115 | // Should be called in the loop function and it will take care if connecting. 116 | void MQTT_connect() { 117 | int8_t ret; 118 | 119 | // Stop if already connected. 120 | if (mqtt.connected()) { 121 | return; 122 | } 123 | 124 | Serial.print("Connecting to MQTT... "); 125 | 126 | uint8_t retries = 3; 127 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 128 | Serial.println(mqtt.connectErrorString(ret)); 129 | Serial.println("Retrying MQTT connection in 5 seconds..."); 130 | mqtt.disconnect(); 131 | delay(5000); // wait 5 seconds 132 | retries--; 133 | if (retries == 0) { 134 | // basically die and wait for WDT to reset me 135 | while (1); 136 | } 137 | } 138 | 139 | Serial.println("MQTT Connected!"); 140 | } 141 | -------------------------------------------------------------------------------- /examples/adafruitio_time_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/adafruitio_time_esp8266/adafruitio_time_esp8266.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library ESP8266 Adafruit IO SSL/TLS example 3 | 4 | Must use the latest version of ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board & Feather 8 | ----> https://www.adafruit.com/product/2471 9 | ----> https://www.adafruit.com/products/2821 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Tony DiCola for Adafruit Industries. 16 | Time additions by Todd Treece for Adafruit Industries. 17 | MIT license, all text above must be included in any redistribution 18 | ****************************************************/ 19 | #include 20 | #include "Adafruit_MQTT.h" 21 | #include "Adafruit_MQTT_Client.h" 22 | 23 | /************************* WiFi Access Point *********************************/ 24 | #define WLAN_SSID "network" 25 | #define WLAN_PASS "password" 26 | 27 | /************************* Adafruit.io Setup *********************************/ 28 | #define AIO_SERVER "io.adafruit.com" 29 | #define AIO_SERVERPORT 8883 30 | #define AIO_USERNAME "user" 31 | #define AIO_KEY "key" 32 | 33 | WiFiClientSecure client; 34 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_USERNAME, AIO_KEY); 35 | 36 | Adafruit_MQTT_Subscribe timefeed = Adafruit_MQTT_Subscribe(&mqtt, "time/seconds"); 37 | 38 | // set timezone offset from UTC 39 | int timeZone = -4; // UTC - 4 eastern daylight time (nyc) 40 | int interval = 4; // trigger every X hours 41 | int hour = 0; // current hour 42 | 43 | void timecallback(uint32_t current) { 44 | 45 | // stash previous hour 46 | int previous = hour; 47 | 48 | // adjust to local time zone 49 | current += (timeZone * 60 * 60); 50 | 51 | // calculate current hour 52 | hour = (current / 60 / 60) % 24; 53 | 54 | // only trigger on interval 55 | if((hour != previous) && (hour % interval) == 0) { 56 | Serial.println("Run your code here"); 57 | } 58 | 59 | } 60 | 61 | void setup() { 62 | 63 | Serial.begin(115200); 64 | delay(10); 65 | 66 | Serial.print(F("Adafruit IO Time Demo")); 67 | 68 | WiFi.begin(WLAN_SSID, WLAN_PASS); 69 | while (WiFi.status() != WL_CONNECTED) { 70 | delay(500); 71 | Serial.print(F(".")); 72 | } 73 | Serial.println(F(" WiFi connected.")); 74 | 75 | timefeed.setCallback(timecallback); 76 | mqtt.subscribe(&timefeed); 77 | 78 | } 79 | 80 | void loop() { 81 | 82 | // Ensure the connection to the MQTT server is alive (this will make the first 83 | // connection and automatically reconnect when disconnected). See the MQTT_connect 84 | // function definition further below. 85 | MQTT_connect(); 86 | 87 | // wait 10 seconds for subscription messages 88 | // since we have no other tasks in this example. 89 | mqtt.processPackets(10000); 90 | 91 | // keep the connection alive 92 | mqtt.ping(); 93 | 94 | } 95 | 96 | // Function to connect and reconnect as necessary to the MQTT server. 97 | // Should be called in the loop function and it will take care if connecting. 98 | void MQTT_connect() { 99 | int8_t ret; 100 | 101 | // Stop if already connected. 102 | if (mqtt.connected()) { 103 | return; 104 | } 105 | 106 | Serial.print("Connecting to MQTT... "); 107 | 108 | uint8_t retries = 3; 109 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 110 | Serial.println(mqtt.connectErrorString(ret)); 111 | Serial.println("Retrying MQTT connection in 5 seconds..."); 112 | mqtt.disconnect(); 113 | delay(5000); // wait 5 seconds 114 | retries--; 115 | if (retries == 0) { 116 | // basically die and wait for WDT to reset me 117 | while (1); 118 | } 119 | } 120 | 121 | Serial.println("MQTT Connected!"); 122 | } 123 | -------------------------------------------------------------------------------- /examples/mqtt_2subs_esp8266/.due.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_2subs_esp8266/.due.test.skip -------------------------------------------------------------------------------- /examples/mqtt_2subs_esp8266/.leonardo.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_2subs_esp8266/.leonardo.test.skip -------------------------------------------------------------------------------- /examples/mqtt_2subs_esp8266/.uno.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_2subs_esp8266/.uno.test.skip -------------------------------------------------------------------------------- /examples/mqtt_2subs_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_2subs_esp8266/mqtt_2subs_esp8266.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library ESP8266 Example 3 | 4 | Must use ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board & Feather 8 | ----> https://www.adafruit.com/product/2471 9 | ----> https://www.adafruit.com/products/2821 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Tony DiCola for Adafruit Industries. 16 | MIT license, all text above must be included in any redistribution 17 | ****************************************************/ 18 | #include 19 | #include "Adafruit_MQTT.h" 20 | #include "Adafruit_MQTT_Client.h" 21 | 22 | // the on off button feed turns this LED on/off 23 | #define LED 2 24 | // the slider feed sets the PWM output of this pin 25 | #define PWMOUT 12 26 | 27 | /************************* WiFi Access Point *********************************/ 28 | 29 | #define WLAN_SSID "...your SSID..." 30 | #define WLAN_PASS "...your password..." 31 | 32 | /************************* Adafruit.io Setup *********************************/ 33 | 34 | #define AIO_SERVER "io.adafruit.com" 35 | #define AIO_SERVERPORT 1883 // use 8883 for SSL 36 | #define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..." 37 | #define AIO_KEY "...your AIO key..." 38 | 39 | /************ Global State (you don't need to change this!) ******************/ 40 | 41 | // Create an ESP8266 WiFiClient class to connect to the MQTT server. 42 | WiFiClient client; 43 | // or... use WiFiFlientSecure for SSL 44 | //WiFiClientSecure client; 45 | 46 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 47 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_USERNAME, AIO_KEY); 48 | 49 | /****************************** Feeds ***************************************/ 50 | 51 | // Notice MQTT paths for AIO follow the form: /feeds/ 52 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff"); 53 | Adafruit_MQTT_Subscribe slider = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/slider"); 54 | 55 | /*************************** Sketch Code ************************************/ 56 | 57 | // Bug workaround for Arduino 1.6.6, it seems to need a function declaration 58 | // for some reason (only affects ESP8266, likely an arduino-builder bug). 59 | void MQTT_connect(); 60 | 61 | void setup() { 62 | pinMode(LED, OUTPUT); 63 | pinMode(PWMOUT, OUTPUT); 64 | 65 | Serial.begin(115200); 66 | delay(10); 67 | 68 | Serial.println(F("Adafruit MQTT demo")); 69 | 70 | // Connect to WiFi access point. 71 | Serial.println(); Serial.println(); 72 | Serial.print("Connecting to "); 73 | Serial.println(WLAN_SSID); 74 | 75 | WiFi.begin(WLAN_SSID, WLAN_PASS); 76 | while (WiFi.status() != WL_CONNECTED) { 77 | delay(500); 78 | Serial.print("."); 79 | } 80 | Serial.println(); 81 | 82 | Serial.println("WiFi connected"); 83 | Serial.println("IP address: "); Serial.println(WiFi.localIP()); 84 | 85 | // Setup MQTT subscription for onoff & slider feed. 86 | mqtt.subscribe(&onoffbutton); 87 | mqtt.subscribe(&slider); 88 | } 89 | 90 | uint32_t x=0; 91 | 92 | void loop() { 93 | // Ensure the connection to the MQTT server is alive (this will make the first 94 | // connection and automatically reconnect when disconnected). See the MQTT_connect 95 | // function definition further below. 96 | MQTT_connect(); 97 | 98 | // this is our 'wait for incoming subscription packets' busy subloop 99 | // try to spend your time here 100 | 101 | Adafruit_MQTT_Subscribe *subscription; 102 | while ((subscription = mqtt.readSubscription(5000))) { 103 | // Check if its the onoff button feed 104 | if (subscription == &onoffbutton) { 105 | Serial.print(F("On-Off button: ")); 106 | Serial.println((char *)onoffbutton.lastread); 107 | 108 | if (strcmp((char *)onoffbutton.lastread, "ON") == 0) { 109 | digitalWrite(LED, LOW); 110 | } 111 | if (strcmp((char *)onoffbutton.lastread, "OFF") == 0) { 112 | digitalWrite(LED, HIGH); 113 | } 114 | } 115 | 116 | // check if its the slider feed 117 | if (subscription == &slider) { 118 | Serial.print(F("Slider: ")); 119 | Serial.println((char *)slider.lastread); 120 | uint16_t sliderval = atoi((char *)slider.lastread); // convert to a number 121 | analogWrite(PWMOUT, sliderval); 122 | } 123 | } 124 | 125 | // ping the server to keep the mqtt connection alive 126 | if(! mqtt.ping()) { 127 | mqtt.disconnect(); 128 | } 129 | 130 | } 131 | 132 | // Function to connect and reconnect as necessary to the MQTT server. 133 | // Should be called in the loop function and it will take care if connecting. 134 | void MQTT_connect() { 135 | int8_t ret; 136 | 137 | // Stop if already connected. 138 | if (mqtt.connected()) { 139 | return; 140 | } 141 | 142 | Serial.print("Connecting to MQTT... "); 143 | 144 | uint8_t retries = 3; 145 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 146 | Serial.println(mqtt.connectErrorString(ret)); 147 | Serial.println("Retrying MQTT connection in 5 seconds..."); 148 | mqtt.disconnect(); 149 | delay(5000); // wait 5 seconds 150 | retries--; 151 | if (retries == 0) { 152 | // basically die and wait for WDT to reset me 153 | while (1); 154 | } 155 | } 156 | Serial.println("MQTT Connected!"); 157 | } 158 | -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/.due.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_arbitrary_data/.due.test.skip -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/.leonardo.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_arbitrary_data/.leonardo.test.skip -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/.uno.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_arbitrary_data/.uno.test.skip -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/.zero.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_arbitrary_data/.zero.test.skip -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/README.md: -------------------------------------------------------------------------------- 1 | # Adafruit MQTT Library Arbitrary Data Publish Example 2 | 3 | This example illustrates publishing an arbitrary data packet using the Adafruit MQTT library to an MQTT feed which can then be parsed by the included python subscriber client. Possible usage cases include adding metadata (collection time, sensor info etc) to a datapoint. 4 | 5 | ![alt-text](https://raw.githubusercontent.com/stuthedew/Adafruit_MQTT_Library/Arbitrary_data_publish/examples/mqtt_arbitrary_data/python_subscriber/mqtt_figure.png "Arbitrary data flow diagram") 6 | 7 | My motivation for this was wanting to be able to include metadata to a post. 8 | Specifically, I was playing around with a [Teviso RD3024 radiation sensor](http://www.teviso.com/en/products/radiation-sensor-rd3024.htm), and a salvaged Americium radiation source from a smoke detector, at varying distances from the sensor. I wanted a way to associate the collection time, and distance between the source and sensor with the actual radiation reading itself. 9 | 10 | 11 | --- 12 | 13 | ## Installing and configuring Mosquitto broker (minimal working setup): 14 | 15 | ####_Installing on Raspberry Pi/Linux:_ 16 | 17 | ```bash 18 | sudo apt-get install mosquitto 19 | cd /etc/mosquitto/ 20 | #See "Configuring Mosquitto Broker below" 21 | ``` 22 | 23 | ####_Installing On a Mac:_ 24 | ```bash 25 | brew install mosquitto 26 | cd /usr/local/etc/mosquitto 27 | #See "Configuring Mosquitto Broker below" 28 | ``` 29 | 30 | --- 31 | 32 | ####Configuring Mosquitto broker 33 | ```bash 34 | sudo nano mosquitto.conf 35 | ``` 36 | Now we have to enable a password file to correctly interface with the Adafruit MQTT library. Scroll about two thirds of the way down until you see: 37 | 38 | ```bash 39 | # ----------------------------------------------------------------- 40 | # Default authentication and topic access control 41 | # ----------------------------------------------------------------- 42 | ``` 43 | 44 | You should see `#password_file` about a paragraph after that. 45 | Change 46 | 47 | ```bash 48 | #password_file 49 | ``` 50 | 51 | To 52 | 53 | ```bash 54 | password_file pwfile 55 | ``` 56 | 57 | Now `ctrl-x` to save and exit. 58 | 59 | You're almost done! We just have to create and populate the password file we just configured. The default user info is: 60 | * **Arduino Subscriber:** 61 | * Username: TestUser 62 | * Password: TestUser 63 | 64 | * **Python Subscriber:** 65 | * Username: TestPy 66 | * Password: TestPy 67 | 68 | ```bash 69 | touch pwfile #create the password file 70 | mosquitto_passwd pwfile TestUser #Enter and confirm password when prompted 71 | mosquitto_passwd pwfile TestPy #Enter and confirm password when prompted 72 | ``` 73 | 74 | ####Running Mosquitto broker 75 | Now run Mosquitto broker to allow Arduino publisher and Python subscriber to communicate 76 | 77 | ```bash 78 | mosquitto 79 | ``` 80 | 81 | --- 82 | 83 | ## Using Example Python Subscriber: 84 | 85 | ####Installing Python subscriber 86 | Install dependencies if you haven't already 87 | ```bash 88 | cd ../Adafruit_MQTT_Library/examples/mqtt_arbitrary_buffer/python_subscriber 89 | pip install -r requirements.txt 90 | ``` 91 | 92 | 93 | ####Installing Python subscriber 94 | Run python script with default values and watch your parsed data print out. 95 | ```bash 96 | python subscriber.py #Add -h flag to see modifiable options 97 | ``` 98 | 99 | Assuming that the Mosquitto broker is running in the background and the Adafruit_MQTT client (Arduino) is publishing, you should see the example data print out every 10 seconds. 100 | 101 | ```bash 102 | MQTT: Connection successful 103 | Connection successful 104 | Subscribed to /feeds/arb_packet 105 | Received char Array: "Hello!", val1: -4533, val2: 73102, val3: 3354... 106 | Received char Array: "Hello!", val1: -4533, val2: 83611, val3: 3354... 107 | Received char Array: "Hello!", val1: -4533, val2: 94115, val3: 3354... 108 | ``` 109 | -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/mqtt_arbitrary_data.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library Arbitrary Data Example 3 | 4 | Must use ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board & Feather 8 | ----> https://www.adafruit.com/product/2471 9 | ----> https://www.adafruit.com/products/2821 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Stuart Feichtinger 16 | Modifed from the mqtt_esp8266 example written by Tony DiCola for Adafruit Industries. 17 | MIT license, all text above must be included in any redistribution 18 | ****************************************************/ 19 | #include 20 | #include "Adafruit_MQTT.h" 21 | #include "Adafruit_MQTT_Client.h" 22 | 23 | /************************* WiFi Access Point *********************************/ 24 | 25 | #define WLAN_SSID "...your SSID..." 26 | #define WLAN_PASS "...your password..." 27 | 28 | /************************* Adafruit.io Setup *********************************/ 29 | 30 | #define ARB_SERVER "...host computer ip address..." 31 | #define ARB_SERVERPORT 1883 // use 8883 for SSL 32 | #define ARB_USERNAME "TestUser" 33 | #define ARB_PW "TestUser" 34 | 35 | 36 | /************ Global State (you don't need to change this!) ******************/ 37 | 38 | // Create an ESP8266 WiFiClient class to connect to the MQTT server. 39 | WiFiClient client; 40 | // or... use WiFiFlientSecure for SSL 41 | //WiFiClientSecure client; 42 | 43 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 44 | Adafruit_MQTT_Client mqtt(&client, ARB_SERVER, ARB_SERVERPORT, ARB_USERNAME, ARB_PW); 45 | 46 | /****************************** Feeds ***************************************/ 47 | 48 | // Setup a feed called 'arb_packet' for publishing. 49 | // Notice MQTT paths for AIO follow the form: /feeds/ 50 | #define ARB_FEED "/feeds/arb_packet" 51 | Adafruit_MQTT_Publish ap = Adafruit_MQTT_Publish(&mqtt, ARB_FEED); 52 | 53 | 54 | // Arbitrary Payload 55 | // Union allows for easier interaction of members in struct form with easy publishing 56 | // of "raw" bytes 57 | typedef union{ 58 | //Customize struct with whatever variables/types you like. 59 | 60 | struct __attribute__((__packed__)){ // packed to eliminate padding for easier parsing. 61 | char charAry[10]; 62 | int16_t val1; 63 | unsigned long val2; 64 | uint16_t val3; 65 | }s; 66 | 67 | uint8_t raw[sizeof(s)]; // For publishing 68 | 69 | /* 70 | // Alternate Option with anonymous struct, but manual byte count: 71 | 72 | struct __attribute__((__packed__)){ // packed to eliminate padding for easier parsing. 73 | char charAry[10]; // 10 x 1 byte = 10 bytes 74 | int16_t val1; // 1 x 2 bytes = 2 bytes 75 | unsigned long val2; // 1 x 4 bytes = 4 bytes 76 | uint16_t val3; // 1 x 2 bytes = 2 bytes 77 | ------------------- 78 | TOTAL = 18 bytes 79 | }; 80 | uint8_t raw[18]; // For publishing 81 | */ 82 | 83 | } packet_t; 84 | 85 | /*************************** Sketch Code ************************************/ 86 | 87 | // Bug workaround for Arduino 1.6.6, it seems to need a function declaration 88 | // for some reason (only affects ESP8266, likely an arduino-builder bug). 89 | void MQTT_connect(); 90 | 91 | void setup() { 92 | Serial.begin(115200); 93 | delay(10); 94 | 95 | Serial.println(F("Adafruit MQTT demo")); 96 | 97 | // Connect to WiFi access point. 98 | Serial.println(); Serial.println(); 99 | Serial.print(F("Connecting to ")); 100 | Serial.println(WLAN_SSID); 101 | 102 | WiFi.begin(WLAN_SSID, WLAN_PASS); 103 | while (WiFi.status() != WL_CONNECTED) { 104 | delay(500); 105 | Serial.print(F(".")); 106 | } 107 | Serial.println(); 108 | 109 | Serial.println(F("WiFi connected")); 110 | Serial.println(F("IP address: ")); Serial.println(WiFi.localIP()); 111 | 112 | } 113 | 114 | packet_t arbPac; 115 | 116 | const char strVal[] PROGMEM = "Hello!"; 117 | 118 | void loop() { 119 | // Ensure the connection to the MQTT server is alive (this will make the first 120 | // connection and automatically reconnect when disconnected). See the MQTT_connect 121 | // function definition further below. 122 | MQTT_connect(); 123 | 124 | //Update arbitrary packet values 125 | strcpy_P(arbPac.s.charAry, strVal); 126 | arbPac.s.val1 = -4533; 127 | arbPac.s.val2 = millis(); 128 | arbPac.s.val3 = 3354; 129 | 130 | /* 131 | // Alternate Union with anonymous struct 132 | // (see union declaration above) 133 | 134 | strcpy_P(arbPac.charAry, strVal); 135 | arbPac.val1 = -4533; 136 | arbPac.val2 = millis(); 137 | arbPac.val3 = 3354; 138 | */ 139 | 140 | if (! ap.publish(arbPac.raw, sizeof(packet_t))) 141 | Serial.println(F("Publish Failed.")); 142 | else { 143 | Serial.println(F("Publish Success!")); 144 | delay(500); 145 | } 146 | 147 | delay(10000); 148 | 149 | 150 | // ping the server to keep the mqtt connection alive 151 | // NOT required if you are publishing once every KEEPALIVE seconds 152 | /* 153 | if(! mqtt.ping()) { 154 | mqtt.disconnect(); 155 | } 156 | */ 157 | } 158 | 159 | // Function to connect and reconnect as necessary to the MQTT server. 160 | // Should be called in the loop function and it will take care if connecting. 161 | void MQTT_connect() { 162 | int8_t ret; 163 | 164 | // Stop if already connected. 165 | if (mqtt.connected()) { 166 | return; 167 | } 168 | 169 | Serial.print(F("Connecting to MQTT... ")); 170 | 171 | uint8_t retries = 3; 172 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 173 | Serial.println(mqtt.connectErrorString(ret)); 174 | Serial.println(F("Retrying MQTT connection in 5 seconds...")); 175 | mqtt.disconnect(); 176 | delay(5000); // wait 5 seconds 177 | retries--; 178 | if (retries == 0) { 179 | // basically die and wait for WDT to reset me 180 | while (1); 181 | } 182 | } 183 | Serial.println(F("MQTT Connected!")); 184 | } 185 | -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/python_subscriber/mqtt_figure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_arbitrary_data/python_subscriber/mqtt_figure.png -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/python_subscriber/requirements.txt: -------------------------------------------------------------------------------- 1 | paho-mqtt>=1.1 2 | -------------------------------------------------------------------------------- /examples/mqtt_arbitrary_data/python_subscriber/subscriber.py: -------------------------------------------------------------------------------- 1 | '''MQTT subscriber for Adafruit MQTT library mqtt_arbitrary_buffer example''' 2 | import paho.mqtt.client as mqtt 3 | import argparse 4 | import struct 5 | import array 6 | import sys 7 | 8 | return_str =[ 9 | "Connection successful", 10 | "incorrect protocol version", 11 | "invalid client identifier", 12 | "server unavailable", 13 | "bad username or password", 14 | "not authorised" 15 | ] 16 | 17 | args = None 18 | 19 | # The callback for when the client receives a CONNACK response from the server. 20 | def on_connect(client, userdata, rc): 21 | """callback function on connect. Subscribes or exits depending on outcome""" 22 | print("MQTT: "), 23 | print(return_str[rc]) 24 | if(rc > 1): 25 | print("Connection refused - " + return_str[rc]) 26 | sys.exit(rc) 27 | # Subscribing in on_connect() means that if we lose the connection and 28 | # reconnect then subscriptions will be renewed. 29 | else: 30 | print(return_str[rc]) 31 | client.subscribe(args.topic) 32 | print("Subscribed to {}".format(args.topic)) 33 | 34 | def on_disconnect(client, userdata, rc): 35 | """Callback for disconnect""" 36 | if rc != 0: 37 | print("Unexpected disconnection.") 38 | client.reconnect() 39 | 40 | # The callback for when a PUBLISH message is received from the server. 41 | def on_message(client, userdata, msg): 42 | try: 43 | pMsg = parseMsg(msg.payload) 44 | print("Received char Array: \"{}\", val1: {}, val2: {}, val3: {}...".format(pMsg[0], pMsg[1], pMsg[2], pMsg[3])) 45 | 46 | except Exception as err: 47 | print err 48 | 49 | 50 | 51 | def argBegin(): 52 | parser = argparse.ArgumentParser(description='MQTT subscriber for Adafruit MQTT library mqtt_arbitrary_buffer example') 53 | parser.add_argument("--host", default="localhost", help='mqtt host to connect to. Defaults to localhost.') 54 | parser.add_argument("-p", "--port", default=1883, help='network port to connect to. Defaults to 1883.') 55 | parser.add_argument("-t", "--topic", nargs='*', default="/feeds/arb_packet", help="mqtt topic to subscribe to. May be repeated multiple times.") 56 | parser.add_argument("-u", "--username", default="testPy", help="provide a username (requires MQTT 3.1 broker)") 57 | parser.add_argument("-P", "--password", default="testPy", help="provide a password (requires MQTT 3.1 broker)") 58 | parser.add_argument("-k", "--keepalive", default=60, help="keep alive in seconds for this client. Defaults to 60.") 59 | 60 | return parser.parse_args() 61 | 62 | 63 | def parseMsg(payload): 64 | """Parses C struct from MQTT publisher Adafruit MQTT client to Python list""" 65 | 66 | arr = array.array('B', payload) #convert python list to C-like array of unsigned char (B) 67 | 68 | parsedStruct = struct.Struct('< 10s h L H') #define struct template (see below) 69 | ''' 70 | Format of Struct from Adafruit MQTT client, Arduino, etc: 71 | 72 | Adafruit MQTT client == Little endian (<) 73 | 74 | Var NAME | C TYPE (python symbol) | size of member x bytes 75 | ------------------------------------------------------------------- 76 | "charAry" | uchar (s) | 10s x 1 = 10 bytes 77 | "val1" | int16 / short (h) | 1h x 2 = 2 bytes 78 | "val2" | unsigned long (L) | 1L x 4 = 4 bytes 79 | "val3" | uint16/unsigned short(H)| 1H x 2 = 2 bytes 80 | ------------------------------------------------------------------ 81 | Total packet size = | 18 bytes | 82 | 83 | See Section 7.3.2 of Python struct module documentation for complete format list 84 | https://docs.python.org/2/library/struct.html 85 | ''' 86 | 87 | charAry, val1, val2, val3 = parsedStruct.unpack_from(arr) #convert byte array to formatted struct 88 | charAry = charAry.rstrip(' \t\r\n\0') #remove trailing white space from buffer 89 | return charAry, val1, val2, val3 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | def main(): 98 | """Wait for incoming message published by Adafruit MQTT client""" 99 | global args 100 | args = argBegin() 101 | client = mqtt.Client() 102 | client.on_connect = on_connect 103 | client.on_message = on_message 104 | client.username_pw_set(args.username, args.password) 105 | client.connect(args.host, args.port, args.keepalive) 106 | 107 | # Blocking call that processes network traffic, dispatches callbacks and 108 | # handles reconnecting. 109 | # Other loop*() functions are available that give a threaded interface and a 110 | # manual interface. 111 | client.loop_forever() 112 | 113 | if __name__ == '__main__': 114 | sys.exit(main()) 115 | -------------------------------------------------------------------------------- /examples/mqtt_esp8266/.due.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_esp8266/.due.test.skip -------------------------------------------------------------------------------- /examples/mqtt_esp8266/.leonardo.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_esp8266/.leonardo.test.skip -------------------------------------------------------------------------------- /examples/mqtt_esp8266/.uno.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_esp8266/.uno.test.skip -------------------------------------------------------------------------------- /examples/mqtt_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_esp8266/mqtt_esp8266.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library ESP8266 Example 3 | 4 | Must use ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board & Feather 8 | ----> https://www.adafruit.com/product/2471 9 | ----> https://www.adafruit.com/products/2821 10 | 11 | Adafruit invests time and resources providing this open source code, 12 | please support Adafruit and open-source hardware by purchasing 13 | products from Adafruit! 14 | 15 | Written by Tony DiCola for Adafruit Industries. 16 | MIT license, all text above must be included in any redistribution 17 | ****************************************************/ 18 | #include 19 | #include "Adafruit_MQTT.h" 20 | #include "Adafruit_MQTT_Client.h" 21 | 22 | /************************* WiFi Access Point *********************************/ 23 | 24 | #define WLAN_SSID "...your SSID..." 25 | #define WLAN_PASS "...your password..." 26 | 27 | /************************* Adafruit.io Setup *********************************/ 28 | 29 | #define AIO_SERVER "io.adafruit.com" 30 | #define AIO_SERVERPORT 1883 // use 8883 for SSL 31 | #define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..." 32 | #define AIO_KEY "...your AIO key..." 33 | 34 | /************ Global State (you don't need to change this!) ******************/ 35 | 36 | // Create an ESP8266 WiFiClient class to connect to the MQTT server. 37 | WiFiClient client; 38 | // or... use WiFiClientSecure for SSL 39 | //WiFiClientSecure client; 40 | 41 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 42 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 43 | 44 | /****************************** Feeds ***************************************/ 45 | 46 | // Setup a feed called 'photocell' for publishing. 47 | // Notice MQTT paths for AIO follow the form: /feeds/ 48 | Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell"); 49 | 50 | // Setup a feed called 'onoff' for subscribing to changes. 51 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff"); 52 | 53 | /*************************** Sketch Code ************************************/ 54 | 55 | // Bug workaround for Arduino 1.6.6, it seems to need a function declaration 56 | // for some reason (only affects ESP8266, likely an arduino-builder bug). 57 | void MQTT_connect(); 58 | 59 | void setup() { 60 | Serial.begin(115200); 61 | delay(10); 62 | 63 | Serial.println(F("Adafruit MQTT demo")); 64 | 65 | // Connect to WiFi access point. 66 | Serial.println(); Serial.println(); 67 | Serial.print("Connecting to "); 68 | Serial.println(WLAN_SSID); 69 | 70 | WiFi.begin(WLAN_SSID, WLAN_PASS); 71 | while (WiFi.status() != WL_CONNECTED) { 72 | delay(500); 73 | Serial.print("."); 74 | } 75 | Serial.println(); 76 | 77 | Serial.println("WiFi connected"); 78 | Serial.println("IP address: "); Serial.println(WiFi.localIP()); 79 | 80 | // Setup MQTT subscription for onoff feed. 81 | mqtt.subscribe(&onoffbutton); 82 | } 83 | 84 | uint32_t x=0; 85 | 86 | void loop() { 87 | // Ensure the connection to the MQTT server is alive (this will make the first 88 | // connection and automatically reconnect when disconnected). See the MQTT_connect 89 | // function definition further below. 90 | MQTT_connect(); 91 | 92 | // this is our 'wait for incoming subscription packets' busy subloop 93 | // try to spend your time here 94 | 95 | Adafruit_MQTT_Subscribe *subscription; 96 | while ((subscription = mqtt.readSubscription(5000))) { 97 | if (subscription == &onoffbutton) { 98 | Serial.print(F("Got: ")); 99 | Serial.println((char *)onoffbutton.lastread); 100 | } 101 | } 102 | 103 | // Now we can publish stuff! 104 | Serial.print(F("\nSending photocell val ")); 105 | Serial.print(x); 106 | Serial.print("..."); 107 | if (! photocell.publish(x++)) { 108 | Serial.println(F("Failed")); 109 | } else { 110 | Serial.println(F("OK!")); 111 | } 112 | 113 | // ping the server to keep the mqtt connection alive 114 | // NOT required if you are publishing once every KEEPALIVE seconds 115 | /* 116 | if(! mqtt.ping()) { 117 | mqtt.disconnect(); 118 | } 119 | */ 120 | } 121 | 122 | // Function to connect and reconnect as necessary to the MQTT server. 123 | // Should be called in the loop function and it will take care if connecting. 124 | void MQTT_connect() { 125 | int8_t ret; 126 | 127 | // Stop if already connected. 128 | if (mqtt.connected()) { 129 | return; 130 | } 131 | 132 | Serial.print("Connecting to MQTT... "); 133 | 134 | uint8_t retries = 3; 135 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 136 | Serial.println(mqtt.connectErrorString(ret)); 137 | Serial.println("Retrying MQTT connection in 5 seconds..."); 138 | mqtt.disconnect(); 139 | delay(5000); // wait 5 seconds 140 | retries--; 141 | if (retries == 0) { 142 | // basically die and wait for WDT to reset me 143 | while (1); 144 | } 145 | } 146 | Serial.println("MQTT Connected!"); 147 | } 148 | -------------------------------------------------------------------------------- /examples/mqtt_esp8266_callback/.esp8266.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_esp8266_callback/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_esp8266_callback/mqtt_esp8266_callback.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library ESP8266 Example 3 | 4 | Must use ESP8266 Arduino from: 5 | https://github.com/esp8266/Arduino 6 | 7 | Works great with Adafruit's Huzzah ESP board: 8 | ----> https://www.adafruit.com/product/2471 9 | 10 | Adafruit invests time and resources providing this open source code, 11 | please support Adafruit and open-source hardware by purchasing 12 | products from Adafruit! 13 | 14 | Written by Tony DiCola for Adafruit Industries. 15 | MIT license, all text above must be included in any redistribution 16 | ****************************************************/ 17 | #include 18 | #include "Adafruit_MQTT.h" 19 | #include "Adafruit_MQTT_Client.h" 20 | 21 | /************************* WiFi Access Point *********************************/ 22 | 23 | #define WLAN_SSID "network" 24 | #define WLAN_PASS "password" 25 | 26 | /************************* Adafruit.io Setup *********************************/ 27 | 28 | #define AIO_SERVER "io.adafruit.com" 29 | #define AIO_SERVERPORT 1883 30 | #define AIO_USERNAME "user" 31 | #define AIO_KEY "key" 32 | 33 | /************ Global State (you don't need to change this!) ******************/ 34 | 35 | // Create an ESP8266 WiFiClient class to connect to the MQTT server. 36 | WiFiClient client; 37 | 38 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 39 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_USERNAME, AIO_KEY); 40 | 41 | /****************************** Feeds ***************************************/ 42 | 43 | // Setup a feed called 'time' for subscribing to current time 44 | Adafruit_MQTT_Subscribe timefeed = Adafruit_MQTT_Subscribe(&mqtt, "time/seconds"); 45 | 46 | // Setup a feed called 'slider' for subscribing to changes on the slider 47 | Adafruit_MQTT_Subscribe slider = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/slider", MQTT_QOS_1); 48 | 49 | // Setup a feed called 'onoff' for subscribing to changes to the button 50 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff", MQTT_QOS_1); 51 | 52 | /*************************** Sketch Code ************************************/ 53 | 54 | int sec; 55 | int min; 56 | int hour; 57 | 58 | int timeZone = -4; // utc-4 eastern daylight time (nyc) 59 | 60 | void timecallback(uint32_t current) { 61 | 62 | // adjust to local time zone 63 | current += (timeZone * 60 * 60); 64 | 65 | // calculate current time 66 | sec = current % 60; 67 | current /= 60; 68 | min = current % 60; 69 | current /= 60; 70 | hour = current % 24; 71 | 72 | // print hour 73 | if(hour == 0 || hour == 12) 74 | Serial.print("12"); 75 | if(hour < 12) 76 | Serial.print(hour); 77 | else 78 | Serial.print(hour - 12); 79 | 80 | // print mins 81 | Serial.print(":"); 82 | if(min < 10) Serial.print("0"); 83 | Serial.print(min); 84 | 85 | // print seconds 86 | Serial.print(":"); 87 | if(sec < 10) Serial.print("0"); 88 | Serial.print(sec); 89 | 90 | if(hour < 12) 91 | Serial.println(" am"); 92 | else 93 | Serial.println(" pm"); 94 | 95 | } 96 | 97 | void slidercallback(double x) { 98 | Serial.print("Hey we're in a slider callback, the slider value is: "); 99 | Serial.println(x); 100 | } 101 | 102 | void onoffcallback(char *data, uint16_t len) { 103 | Serial.print("Hey we're in a onoff callback, the button value is: "); 104 | Serial.println(data); 105 | } 106 | 107 | 108 | void setup() { 109 | Serial.begin(115200); 110 | delay(10); 111 | 112 | Serial.println(F("Adafruit MQTT demo")); 113 | 114 | // Connect to WiFi access point. 115 | Serial.println(); Serial.println(); 116 | Serial.print("Connecting to "); 117 | Serial.println(WLAN_SSID); 118 | 119 | WiFi.begin(WLAN_SSID, WLAN_PASS); 120 | while (WiFi.status() != WL_CONNECTED) { 121 | delay(500); 122 | Serial.print("."); 123 | } 124 | Serial.println(); 125 | 126 | Serial.println("WiFi connected"); 127 | Serial.println("IP address: "); Serial.println(WiFi.localIP()); 128 | 129 | timefeed.setCallback(timecallback); 130 | slider.setCallback(slidercallback); 131 | onoffbutton.setCallback(onoffcallback); 132 | 133 | // Setup MQTT subscription for time feed. 134 | mqtt.subscribe(&timefeed); 135 | mqtt.subscribe(&slider); 136 | mqtt.subscribe(&onoffbutton); 137 | 138 | } 139 | 140 | uint32_t x=0; 141 | 142 | void loop() { 143 | // Ensure the connection to the MQTT server is alive (this will make the first 144 | // connection and automatically reconnect when disconnected). See the MQTT_connect 145 | // function definition further below. 146 | MQTT_connect(); 147 | 148 | // this is our 'wait for incoming subscription packets and callback em' busy subloop 149 | // try to spend your time here: 150 | mqtt.processPackets(10000); 151 | 152 | // ping the server to keep the mqtt connection alive 153 | // NOT required if you are publishing once every KEEPALIVE seconds 154 | 155 | if(! mqtt.ping()) { 156 | mqtt.disconnect(); 157 | } 158 | } 159 | 160 | // Function to connect and reconnect as necessary to the MQTT server. 161 | // Should be called in the loop function and it will take care if connecting. 162 | void MQTT_connect() { 163 | int8_t ret; 164 | 165 | // Stop if already connected. 166 | if (mqtt.connected()) { 167 | return; 168 | } 169 | 170 | Serial.print("Connecting to MQTT... "); 171 | 172 | uint8_t retries = 3; 173 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 174 | Serial.println(mqtt.connectErrorString(ret)); 175 | Serial.println("Retrying MQTT connection in 10 seconds..."); 176 | mqtt.disconnect(); 177 | delay(10000); // wait 10 seconds 178 | retries--; 179 | if (retries == 0) { 180 | // basically die and wait for WDT to reset me 181 | while (1); 182 | } 183 | } 184 | Serial.println("MQTT Connected!"); 185 | } 186 | -------------------------------------------------------------------------------- /examples/mqtt_ethernet/.due.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_ethernet/.due.test.skip -------------------------------------------------------------------------------- /examples/mqtt_ethernet/.esp8266.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_ethernet/.esp8266.test.skip -------------------------------------------------------------------------------- /examples/mqtt_ethernet/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_ethernet/mqtt_ethernet.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library Ethernet Example 3 | 4 | Adafruit invests time and resources providing this open source code, 5 | please support Adafruit and open-source hardware by purchasing 6 | products from Adafruit! 7 | 8 | Written by Alec Moore 9 | Derived from the code written by Limor Fried/Ladyada for Adafruit Industries. 10 | MIT license, all text above must be included in any redistribution 11 | ****************************************************/ 12 | #include 13 | #include "Adafruit_MQTT.h" 14 | #include "Adafruit_MQTT_Client.h" 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | /************************* Ethernet Client Setup *****************************/ 22 | byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; 23 | 24 | //Uncomment the following, and set to a valid ip if you don't have dhcp available. 25 | //IPAddress iotIP (192, 168, 0, 42); 26 | //Uncomment the following, and set to your preference if you don't have automatic dns. 27 | //IPAddress dnsIP (8, 8, 8, 8); 28 | //If you uncommented either of the above lines, make sure to change "Ethernet.begin(mac)" to "Ethernet.begin(mac, iotIP)" or "Ethernet.begin(mac, iotIP, dnsIP)" 29 | 30 | 31 | /************************* Adafruit.io Setup *********************************/ 32 | 33 | #define AIO_SERVER "io.adafruit.com" 34 | #define AIO_SERVERPORT 1883 35 | #define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..." 36 | #define AIO_KEY "...your AIO key..." 37 | 38 | 39 | /************ Global State (you don't need to change this!) ******************/ 40 | 41 | //Set up the ethernet client 42 | EthernetClient client; 43 | 44 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 45 | 46 | // You don't need to change anything below this line! 47 | #define halt(s) { Serial.println(F( s )); while(1); } 48 | 49 | 50 | /****************************** Feeds ***************************************/ 51 | 52 | // Setup a feed called 'photocell' for publishing. 53 | // Notice MQTT paths for AIO follow the form: /feeds/ 54 | Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell"); 55 | 56 | // Setup a feed called 'onoff' for subscribing to changes. 57 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff"); 58 | 59 | /*************************** Sketch Code ************************************/ 60 | 61 | void setup() { 62 | Serial.begin(115200); 63 | 64 | Serial.println(F("Adafruit MQTT demo")); 65 | 66 | // Initialise the Client 67 | Serial.print(F("\nInit the Client...")); 68 | Ethernet.begin(mac); 69 | delay(1000); //give the ethernet a second to initialize 70 | 71 | 72 | mqtt.subscribe(&onoffbutton); 73 | } 74 | 75 | uint32_t x=0; 76 | 77 | void loop() { 78 | // Ensure the connection to the MQTT server is alive (this will make the first 79 | // connection and automatically reconnect when disconnected). See the MQTT_connect 80 | // function definition further below. 81 | MQTT_connect(); 82 | 83 | // this is our 'wait for incoming subscription packets' busy subloop 84 | Adafruit_MQTT_Subscribe *subscription; 85 | while ((subscription = mqtt.readSubscription(1000))) { 86 | if (subscription == &onoffbutton) { 87 | Serial.print(F("Got: ")); 88 | Serial.println((char *)onoffbutton.lastread); 89 | } 90 | } 91 | 92 | // Now we can publish stuff! 93 | Serial.print(F("\nSending photocell val ")); 94 | Serial.print(x); 95 | Serial.print("..."); 96 | if (! photocell.publish(x++)) { 97 | Serial.println(F("Failed")); 98 | } else { 99 | Serial.println(F("OK!")); 100 | } 101 | 102 | // ping the server to keep the mqtt connection alive 103 | if(! mqtt.ping()) { 104 | mqtt.disconnect(); 105 | } 106 | 107 | } 108 | 109 | // Function to connect and reconnect as necessary to the MQTT server. 110 | // Should be called in the loop function and it will take care if connecting. 111 | void MQTT_connect() { 112 | int8_t ret; 113 | 114 | // Stop if already connected. 115 | if (mqtt.connected()) { 116 | return; 117 | } 118 | 119 | Serial.print("Connecting to MQTT... "); 120 | 121 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 122 | Serial.println(mqtt.connectErrorString(ret)); 123 | Serial.println("Retrying MQTT connection in 5 seconds..."); 124 | mqtt.disconnect(); 125 | delay(5000); // wait 5 seconds 126 | } 127 | Serial.println("MQTT Connected!"); 128 | } 129 | -------------------------------------------------------------------------------- /examples/mqtt_fona/.due.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_fona/.due.test.skip -------------------------------------------------------------------------------- /examples/mqtt_fona/.esp8266.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_fona/.esp8266.test.skip -------------------------------------------------------------------------------- /examples/mqtt_fona/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_fona/fonahelper.cpp: -------------------------------------------------------------------------------- 1 | #include "Adafruit_FONA.h" 2 | #include 3 | #include 4 | 5 | #define halt(s) \ 6 | { \ 7 | Serial.println(F(s)); \ 8 | while (1) \ 9 | ; \ 10 | } 11 | 12 | extern Adafruit_FONA fona; 13 | extern SoftwareSerial fonaSS; 14 | 15 | boolean FONAconnect(const __FlashStringHelper *apn, 16 | const __FlashStringHelper *username, 17 | const __FlashStringHelper *password) { 18 | Watchdog.reset(); 19 | 20 | Serial.println(F("Initializing FONA....(May take 3 seconds)")); 21 | 22 | fonaSS.begin(4800); // if you're using software serial 23 | 24 | if (!fona.begin(fonaSS)) { // can also try fona.begin(Serial1) 25 | Serial.println(F("Couldn't find FONA")); 26 | return false; 27 | } 28 | fonaSS.println("AT+CMEE=2"); 29 | Serial.println(F("FONA is OK")); 30 | Watchdog.reset(); 31 | Serial.println(F("Checking for network...")); 32 | while (fona.getNetworkStatus() != 1) { 33 | delay(500); 34 | } 35 | 36 | Watchdog.reset(); 37 | delay(5000); // wait a few seconds to stabilize connection 38 | Watchdog.reset(); 39 | 40 | fona.setGPRSNetworkSettings(apn, username, password); 41 | 42 | Serial.println(F("Disabling GPRS")); 43 | fona.enableGPRS(false); 44 | 45 | Watchdog.reset(); 46 | delay(5000); // wait a few seconds to stabilize connection 47 | Watchdog.reset(); 48 | 49 | Serial.println(F("Enabling GPRS")); 50 | if (!fona.enableGPRS(true)) { 51 | Serial.println(F("Failed to turn GPRS on")); 52 | return false; 53 | } 54 | Watchdog.reset(); 55 | 56 | return true; 57 | } 58 | -------------------------------------------------------------------------------- /examples/mqtt_fona/mqtt_fona.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library FONA Example 3 | 4 | Designed specifically to work with the Adafruit FONA 5 | ----> http://www.adafruit.com/products/1946 6 | ----> http://www.adafruit.com/products/1963 7 | ----> http://www.adafruit.com/products/2468 8 | ----> http://www.adafruit.com/products/2542 9 | 10 | These cellular modules use TTL Serial to communicate, 2 pins are 11 | required to interface. 12 | 13 | Adafruit invests time and resources providing this open source code, 14 | please support Adafruit and open-source hardware by purchasing 15 | products from Adafruit! 16 | 17 | Written by Limor Fried/Ladyada for Adafruit Industries. 18 | MIT license, all text above must be included in any redistribution 19 | ****************************************************/ 20 | #include 21 | #include 22 | #include "Adafruit_FONA.h" 23 | #include "Adafruit_MQTT.h" 24 | #include "Adafruit_MQTT_FONA.h" 25 | 26 | /*************************** FONA Pins ***********************************/ 27 | 28 | // Default pins for Feather 32u4 FONA 29 | #define FONA_RX 9 30 | #define FONA_TX 8 31 | #define FONA_RST 4 32 | SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); 33 | 34 | Adafruit_FONA fona = Adafruit_FONA(FONA_RST); 35 | 36 | /************************* WiFi Access Point *********************************/ 37 | 38 | // Optionally configure a GPRS APN, username, and password. 39 | // You might need to do this to access your network's GPRS/data 40 | // network. Contact your provider for the exact APN, username, 41 | // and password values. Username and password are optional and 42 | // can be removed, but APN is required. 43 | #define FONA_APN "" 44 | #define FONA_USERNAME "" 45 | #define FONA_PASSWORD "" 46 | 47 | /************************* Adafruit.io Setup *********************************/ 48 | 49 | #define AIO_SERVER "io.adafruit.com" 50 | #define AIO_SERVERPORT 1883 51 | #define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..." 52 | #define AIO_KEY "...your AIO key..." 53 | 54 | /************ Global State (you don't need to change this!) ******************/ 55 | 56 | // Setup the FONA MQTT class by passing in the FONA class and MQTT server and login details. 57 | Adafruit_MQTT_FONA mqtt(&fona, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 58 | 59 | // You don't need to change anything below this line! 60 | #define halt(s) { Serial.println(F( s )); while(1); } 61 | 62 | // FONAconnect is a helper function that sets up the FONA and connects to 63 | // the GPRS network. See the fonahelper.cpp tab above for the source! 64 | boolean FONAconnect(const __FlashStringHelper *apn, const __FlashStringHelper *username, const __FlashStringHelper *password); 65 | 66 | /****************************** Feeds ***************************************/ 67 | 68 | // Setup a feed called 'photocell' for publishing. 69 | // Notice MQTT paths for AIO follow the form: /feeds/ 70 | Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell"); 71 | 72 | // Setup a feed called 'onoff' for subscribing to changes. 73 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff"); 74 | 75 | /*************************** Sketch Code ************************************/ 76 | 77 | // How many transmission failures in a row we're willing to be ok with before reset 78 | uint8_t txfailures = 0; 79 | #define MAXTXFAILURES 3 80 | 81 | void setup() { 82 | while (!Serial); 83 | 84 | // Watchdog is optional! 85 | //Watchdog.enable(8000); 86 | 87 | Serial.begin(115200); 88 | 89 | Serial.println(F("Adafruit FONA MQTT demo")); 90 | 91 | mqtt.subscribe(&onoffbutton); 92 | 93 | Watchdog.reset(); 94 | delay(5000); // wait a few seconds to stabilize connection 95 | Watchdog.reset(); 96 | 97 | // Initialise the FONA module 98 | while (! FONAconnect(F(FONA_APN), F(FONA_USERNAME), F(FONA_PASSWORD))) { 99 | Serial.println("Retrying FONA"); 100 | } 101 | 102 | Serial.println(F("Connected to Cellular!")); 103 | 104 | Watchdog.reset(); 105 | delay(5000); // wait a few seconds to stabilize connection 106 | Watchdog.reset(); 107 | } 108 | 109 | uint32_t x=0; 110 | 111 | void loop() { 112 | // Make sure to reset watchdog every loop iteration! 113 | Watchdog.reset(); 114 | 115 | // Ensure the connection to the MQTT server is alive (this will make the first 116 | // connection and automatically reconnect when disconnected). See the MQTT_connect 117 | // function definition further below. 118 | MQTT_connect(); 119 | 120 | Watchdog.reset(); 121 | // Now we can publish stuff! 122 | Serial.print(F("\nSending photocell val ")); 123 | Serial.print(x); 124 | Serial.print("..."); 125 | if (! photocell.publish(x++)) { 126 | Serial.println(F("Failed")); 127 | txfailures++; 128 | } else { 129 | Serial.println(F("OK!")); 130 | txfailures = 0; 131 | } 132 | 133 | Watchdog.reset(); 134 | // this is our 'wait for incoming subscription packets' busy subloop 135 | Adafruit_MQTT_Subscribe *subscription; 136 | while ((subscription = mqtt.readSubscription(5000))) { 137 | if (subscription == &onoffbutton) { 138 | Serial.print(F("Got: ")); 139 | Serial.println((char *)onoffbutton.lastread); 140 | } 141 | } 142 | 143 | // ping the server to keep the mqtt connection alive, only needed if we're not publishing 144 | //if(! mqtt.ping()) { 145 | // Serial.println(F("MQTT Ping failed.")); 146 | //} 147 | 148 | } 149 | 150 | // Function to connect and reconnect as necessary to the MQTT server. 151 | // Should be called in the loop function and it will take care if connecting. 152 | void MQTT_connect() { 153 | int8_t ret; 154 | 155 | // Stop if already connected. 156 | if (mqtt.connected()) { 157 | return; 158 | } 159 | 160 | Serial.print("Connecting to MQTT... "); 161 | 162 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 163 | Serial.println(mqtt.connectErrorString(ret)); 164 | Serial.println("Retrying MQTT connection in 5 seconds..."); 165 | mqtt.disconnect(); 166 | delay(5000); // wait 5 seconds 167 | } 168 | Serial.println("MQTT Connected!"); 169 | } 170 | -------------------------------------------------------------------------------- /examples/mqtt_retain/.due.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_retain/.due.test.skip -------------------------------------------------------------------------------- /examples/mqtt_retain/.leonardo.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_retain/.leonardo.test.skip -------------------------------------------------------------------------------- /examples/mqtt_retain/.uno.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_retain/.uno.test.skip -------------------------------------------------------------------------------- /examples/mqtt_retain/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_retain/mqtt_retain.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library Retain Flag Example 3 | 4 | This example demonstrates use of the retain flag when publishing messages. 5 | If retain is set, the MQTT broker will store the message. When a new 6 | client subscribes to the topic, the retained message will be republished 7 | to that client. This is useful for configuration messages and 'last known 8 | good' values. 9 | 10 | Written by Ben Willmore. 11 | MIT license, all text above must be included in any redistribution 12 | ****************************************************/ 13 | 14 | #include // use for ESP32 15 | #include "Adafruit_MQTT.h" 16 | #include "Adafruit_MQTT_Client.h" 17 | 18 | /************************* WiFi Access Point *********************************/ 19 | 20 | #define WLAN_SSID "...your SSID..." 21 | #define WLAN_PASS "...your password..." 22 | 23 | /************************* Adafruit.io Setup *********************************/ 24 | 25 | #define MQTT_SERVER "...your MQTT server..." 26 | #define MQTT_SERVERPORT 1883 // use 8883 for SSL 27 | #define MQTT_USERNAME "MQTT username" 28 | #define MQTT_KEY "MQTT key" 29 | #define DEVICE_ID "mqtt-retain-example" 30 | 31 | /************ Global State (you don't need to change this!) ******************/ 32 | 33 | // Create a WiFiClient class to connect to the MQTT server. 34 | WiFiClient client; 35 | // or... use WiFiClientSecure for SSL 36 | //WiFiClientSecure client; 37 | 38 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 39 | Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, MQTT_SERVERPORT, MQTT_USERNAME, MQTT_KEY); 40 | 41 | /****************************** Feeds ***************************************/ 42 | 43 | // Set up for publishing and subscribing to the same feed, for demonstration only 44 | Adafruit_MQTT_Publish publish_feed = Adafruit_MQTT_Publish(&mqtt, DEVICE_ID "/temp"); 45 | Adafruit_MQTT_Subscribe subscribe_feed = Adafruit_MQTT_Subscribe(&mqtt, DEVICE_ID "/temp"); 46 | 47 | /*************************** Sketch Code ************************************/ 48 | 49 | void setup() { 50 | Serial.begin(115200); 51 | delay(10); 52 | 53 | Serial.println(F("MQTT retain flag demo")); 54 | 55 | // Connect to WiFi access point. 56 | Serial.println(); Serial.println(); 57 | Serial.print("Connecting to "); 58 | Serial.println(WLAN_SSID); 59 | 60 | WiFi.begin(WLAN_SSID, WLAN_PASS); 61 | while (WiFi.status() != WL_CONNECTED) { 62 | delay(500); 63 | Serial.print("."); 64 | } 65 | Serial.println(); 66 | 67 | Serial.println("WiFi connected"); 68 | Serial.println("IP address: "); 69 | Serial.println(WiFi.localIP()); 70 | 71 | // Connect to MQTT broker, then publish a retained message and a 72 | // non-retained message. 73 | Serial.print("\nConnecting to MQTT broker..."); 74 | MQTT_connect(); 75 | Serial.println("connected"); 76 | 77 | Serial.println("Publishing messages while not subscribed"); 78 | publish_feed.publish("This message should be retained", true); 79 | publish_feed.publish("This message should not be retained"); 80 | 81 | Serial.println("Disconnecting from MQTT broker\n"); 82 | mqtt.disconnect(); 83 | 84 | subscribe_feed.setCallback(subscribe_callback); 85 | mqtt.subscribe(&subscribe_feed); 86 | } 87 | 88 | void subscribe_callback(char *data, uint16_t len) { 89 | Serial.print("--> Message received: \""); 90 | Serial.print(data); 91 | Serial.println("\"\n"); 92 | } 93 | 94 | void loop() { 95 | 96 | // Connect to MQTT broker. We should receive the retained message only. 97 | Serial.println("Connecting to broker. Expect to receive retained message:"); 98 | MQTT_connect(); 99 | 100 | mqtt.processPackets(1000); 101 | 102 | Serial.println("Publishing non-retained message. Expect to receive it immediately:"); 103 | publish_feed.publish("This message should be received immediately but not retained"); 104 | 105 | mqtt.processPackets(1000); 106 | 107 | Serial.println("Publishing retained message. Expect to receive it immediately and on re-subscribing:"); 108 | publish_feed.publish("This message should be received immediately AND retained", true); 109 | 110 | mqtt.processPackets(10000); 111 | 112 | Serial.println("Disconnecting from broker\n"); 113 | mqtt.disconnect(); 114 | 115 | delay(15000); 116 | } 117 | 118 | // Function to connect and reconnect as necessary to the MQTT server. 119 | // Should be called in the loop function and it will take care if connecting. 120 | void MQTT_connect() { 121 | int8_t ret; 122 | 123 | // Stop if already connected. 124 | if (mqtt.connected()) { 125 | return; 126 | } 127 | 128 | uint8_t retries = 3; 129 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 130 | Serial.println(mqtt.connectErrorString(ret)); 131 | Serial.println("Retrying MQTT connection in 5 seconds..."); 132 | mqtt.disconnect(); 133 | delay(5000); // wait 5 seconds 134 | retries--; 135 | if (retries == 0) { 136 | // basically die and wait for WDT to reset me 137 | while (1); 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /examples/mqtt_winc1500/.esp8266.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_winc1500/mqtt_winc1500.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library WINC1500 Example 3 | 4 | Adafruit invests time and resources providing this open source code, 5 | please support Adafruit and open-source hardware by purchasing 6 | products from Adafruit! 7 | 8 | Written by Limor Fried/Ladyada for Adafruit Industries. 9 | MIT license, all text above must be included in any redistribution 10 | ****************************************************/ 11 | #include 12 | #include "Adafruit_MQTT.h" 13 | #include "Adafruit_MQTT_Client.h" 14 | #include 15 | 16 | /************************* WiFI Setup *****************************/ 17 | #define WINC_CS 8 18 | #define WINC_IRQ 7 19 | #define WINC_RST 4 20 | #define WINC_EN 2 // or, tie EN to VCC 21 | 22 | char ssid[] = "yournetwork"; // your network SSID (name) 23 | char pass[] = "yourpassword"; // your network password (use for WPA, or use as key for WEP) 24 | int keyIndex = 0; // your network key Index number (needed only for WEP) 25 | 26 | int status = WL_IDLE_STATUS; 27 | 28 | /************************* Adafruit.io Setup *********************************/ 29 | 30 | #define AIO_SERVER "io.adafruit.com" 31 | #define AIO_SERVERPORT 1883 32 | #define AIO_USERNAME "adafruitiousername" 33 | #define AIO_KEY "adafruitiokey" 34 | 35 | /************ Global State (you don't need to change this!) ******************/ 36 | 37 | //Set up the wifi client 38 | WiFiClient client; 39 | 40 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 41 | 42 | // You don't need to change anything below this line! 43 | #define halt(s) { Serial.println(F( s )); while(1); } 44 | 45 | /****************************** Feeds ***************************************/ 46 | 47 | // Setup a feed called 'photocell' for publishing. 48 | // Notice MQTT paths for AIO follow the form: /feeds/ 49 | Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell"); 50 | 51 | // Setup a feed called 'onoff' for subscribing to changes. 52 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff"); 53 | 54 | /*************************** Sketch Code ************************************/ 55 | 56 | #define LEDPIN 13 57 | 58 | 59 | void setup() { 60 | WiFi.setPins(WINC_CS, WINC_IRQ, WINC_RST, WINC_EN); 61 | 62 | while (!Serial); 63 | Serial.begin(115200); 64 | 65 | Serial.println(F("Adafruit MQTT demo for WINC1500")); 66 | 67 | // Initialise the Client 68 | Serial.print(F("\nInit the WiFi module...")); 69 | // check for the presence of the breakout 70 | if (WiFi.status() == WL_NO_SHIELD) { 71 | Serial.println("WINC1500 not present"); 72 | // don't continue: 73 | while (true); 74 | } 75 | Serial.println("ATWINC OK!"); 76 | 77 | pinMode(LEDPIN, OUTPUT); 78 | mqtt.subscribe(&onoffbutton); 79 | } 80 | 81 | uint32_t x=0; 82 | 83 | void loop() { 84 | // Ensure the connection to the MQTT server is alive (this will make the first 85 | // connection and automatically reconnect when disconnected). See the MQTT_connect 86 | // function definition further below. 87 | MQTT_connect(); 88 | 89 | // this is our 'wait for incoming subscription packets' busy subloop 90 | Adafruit_MQTT_Subscribe *subscription; 91 | while ((subscription = mqtt.readSubscription(5000))) { 92 | if (subscription == &onoffbutton) { 93 | Serial.print(F("Got: ")); 94 | Serial.println((char *)onoffbutton.lastread); 95 | 96 | if (0 == strcmp((char *)onoffbutton.lastread, "OFF")) { 97 | digitalWrite(LEDPIN, LOW); 98 | } 99 | if (0 == strcmp((char *)onoffbutton.lastread, "ON")) { 100 | digitalWrite(LEDPIN, HIGH); 101 | } 102 | } 103 | } 104 | 105 | // Now we can publish stuff! 106 | Serial.print(F("\nSending photocell val ")); 107 | Serial.print(x); 108 | Serial.print("..."); 109 | if (! photocell.publish(x++)) { 110 | Serial.println(F("Failed")); 111 | } else { 112 | Serial.println(F("OK!")); 113 | } 114 | 115 | } 116 | 117 | // Function to connect and reconnect as necessary to the MQTT server. 118 | // Should be called in the loop function and it will take care if connecting. 119 | void MQTT_connect() { 120 | int8_t ret; 121 | 122 | // attempt to connect to Wifi network: 123 | while (WiFi.status() != WL_CONNECTED) { 124 | Serial.print("Attempting to connect to SSID: "); 125 | Serial.println(ssid); 126 | // Connect to WPA/WPA2 network. Change this line if using open or WEP network: 127 | status = WiFi.begin(ssid, pass); 128 | 129 | // wait 10 seconds for connection: 130 | uint8_t timeout = 10; 131 | while (timeout && (WiFi.status() != WL_CONNECTED)) { 132 | timeout--; 133 | delay(1000); 134 | } 135 | } 136 | 137 | // Stop if already connected. 138 | if (mqtt.connected()) { 139 | return; 140 | } 141 | 142 | Serial.print("Connecting to MQTT... "); 143 | 144 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 145 | Serial.println(mqtt.connectErrorString(ret)); 146 | Serial.println("Retrying MQTT connection in 5 seconds..."); 147 | mqtt.disconnect(); 148 | delay(5000); // wait 5 seconds 149 | } 150 | Serial.println("MQTT Connected!"); 151 | } 152 | -------------------------------------------------------------------------------- /examples/mqtt_yun/.due.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_yun/.due.test.skip -------------------------------------------------------------------------------- /examples/mqtt_yun/.esp8266.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_yun/.leonardo.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_yun/.leonardo.test.skip -------------------------------------------------------------------------------- /examples/mqtt_yun/.uno.test.skip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_MQTT_Library/520c685b55ff086a29e2604778d949e30ff655de/examples/mqtt_yun/.uno.test.skip -------------------------------------------------------------------------------- /examples/mqtt_yun/.zero.test.skip: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /examples/mqtt_yun/mqtt_yun.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Adafruit MQTT Library Arduino Yun Example 3 | 4 | Make sure your Arduino Yun is connected to a WiFi access point which 5 | has internet access. Also note this sketch uses the Console class 6 | for debug output so make sure to connect to the Yun over WiFi and 7 | open the serial monitor to see the console output. 8 | 9 | Works great with the Arduino Yun: 10 | ----> https://www.adafruit.com/products/1498 11 | 12 | Adafruit invests time and resources providing this open source code, 13 | please support Adafruit and open-source hardware by purchasing 14 | products from Adafruit! 15 | 16 | Written by Tony DiCola for Adafruit Industries. 17 | MIT license, all text above must be included in any redistribution 18 | ****************************************************/ 19 | #include 20 | #include 21 | #include 22 | #include "Adafruit_MQTT.h" 23 | #include "Adafruit_MQTT_Client.h" 24 | 25 | /************************* Adafruit.io Setup *********************************/ 26 | 27 | #define AIO_SERVER "io.adafruit.com" 28 | #define AIO_SERVERPORT 1883 29 | #define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..." 30 | #define AIO_KEY "...your AIO key..." 31 | 32 | 33 | /************ Global State (you don't need to change this!) ******************/ 34 | 35 | // Create a BridgeClient instance to communicate using the Yun's bridge & Linux OS. 36 | BridgeClient client; 37 | 38 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 39 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 40 | 41 | /****************************** Feeds ***************************************/ 42 | 43 | // Setup a feed called 'photocell' for publishing. 44 | // Notice MQTT paths for AIO follow the form: /feeds/ 45 | Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell"); 46 | 47 | // Setup a feed called 'onoff' for subscribing to changes. 48 | Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff"); 49 | 50 | /*************************** Sketch Code ************************************/ 51 | 52 | void setup() { 53 | Bridge.begin(); 54 | Console.begin(); 55 | Console.println(F("Adafruit MQTT demo")); 56 | 57 | // Setup MQTT subscription for onoff feed. 58 | mqtt.subscribe(&onoffbutton); 59 | } 60 | 61 | uint32_t x=0; 62 | 63 | void loop() { 64 | // Ensure the connection to the MQTT server is alive (this will make the first 65 | // connection and automatically reconnect when disconnected). See the MQTT_connect 66 | // function definition further below. 67 | MQTT_connect(); 68 | 69 | // this is our 'wait for incoming subscription packets' busy subloop 70 | Adafruit_MQTT_Subscribe *subscription; 71 | while ((subscription = mqtt.readSubscription(1000))) { 72 | if (subscription == &onoffbutton) { 73 | Console.print(F("Got: ")); 74 | Console.println((char *)onoffbutton.lastread); 75 | } 76 | } 77 | 78 | // Now we can publish stuff! 79 | Console.print(F("\nSending photocell val ")); 80 | Console.print(x); 81 | Console.print("..."); 82 | if (! photocell.publish(x++)) { 83 | Console.println(F("Failed")); 84 | } else { 85 | Console.println(F("OK!")); 86 | } 87 | 88 | // ping the server to keep the mqtt connection alive 89 | if(! mqtt.ping()) { 90 | Console.println(F("MQTT Ping failed.")); 91 | } 92 | 93 | delay(1000); 94 | 95 | } 96 | 97 | // Function to connect and reconnect as necessary to the MQTT server. 98 | // Should be called in the loop function and it will take care if connecting. 99 | void MQTT_connect() { 100 | int8_t ret; 101 | 102 | // Stop if already connected. 103 | if (mqtt.connected()) { 104 | return; 105 | } 106 | 107 | Console.print("Connecting to MQTT... "); 108 | 109 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 110 | Console.println(mqtt.connectErrorString(ret)); 111 | Console.println("Retrying MQTT connection in 5 seconds..."); 112 | mqtt.disconnect(); 113 | delay(5000); // wait 5 seconds 114 | } 115 | Console.println("MQTT Connected!"); 116 | } 117 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | Adafruit_MQTT KEYWORD1 2 | Adafruit_MQTT_FONA KEYWORD1 3 | Adafruit_MQTT_Client KEYWORD1 4 | Adafruit_MQTT_Publish KEYWORD1 5 | Adafruit_MQTT_Subscribe KEYWORD1 6 | connect KEYWORD2 7 | connectErrorString KEYWORD2 8 | disconnect KEYWORD2 9 | connected KEYWORD2 10 | will KEYWORD2 11 | publish KEYWORD2 12 | subscribe KEYWORD2 13 | unsubscribe KEYWORD2 14 | readSubscription KEYWORD2 15 | ping KEYWORD2 16 | setCallback KEYWORD2 17 | connectServer KEYWORD2 18 | disconnectServer KEYWORD2 19 | readPacket KEYWORD2 20 | sendPacket KEYWORD2 21 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=Adafruit MQTT Library 2 | version=2.5.9 3 | author=Adafruit 4 | maintainer=Adafruit 5 | sentence=MQTT library that supports the FONA, ESP8266, ESP32, Yun, and generic Arduino Client hardware. 6 | paragraph=Simple MQTT library that supports the bare minimum to publish and subscribe to topics. 7 | category=Communication 8 | url=https://github.com/adafruit/Adafruit_MQTT_Library 9 | architectures=* 10 | depends=Adafruit SleepyDog Library, Adafruit FONA Library, WiFi101 11 | --------------------------------------------------------------------------------