Merge pull request #65 from adafruit/io_callbacks

Adafruit IO MQTT Callbacks
This commit is contained in:
Todd Treece 2017-02-15 11:39:30 -05:00 committed by GitHub
commit 47ebe871e4
11 changed files with 12 additions and 442 deletions

View File

@ -437,7 +437,7 @@ void Adafruit_MQTT::processPackets(int16_t timeout) {
else if (sub->callback_io != NULL) { else if (sub->callback_io != NULL) {
// huh lets do the callback in io mode // huh lets do the callback in io mode
//Serial.print("*** calling io instance callback with : "); Serial.println((char *)sub->lastread); //Serial.print("*** calling io instance callback with : "); Serial.println((char *)sub->lastread);
((sub->io_feed)->*(sub->callback_io))((char *)sub->lastread, sub->datalen); ((sub->io_mqtt)->*(sub->callback_io))((char *)sub->lastread, sub->datalen);
} }
} }
@ -816,7 +816,7 @@ Adafruit_MQTT_Subscribe::Adafruit_MQTT_Subscribe(Adafruit_MQTT *mqttserver,
callback_buffer = 0; callback_buffer = 0;
callback_double = 0; callback_double = 0;
callback_io = 0; callback_io = 0;
io_feed = 0; io_mqtt = 0;
} }
void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackUInt32Type cb) { void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackUInt32Type cb) {
@ -831,9 +831,9 @@ void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackBufferType cb) {
callback_buffer = cb; callback_buffer = cb;
} }
void Adafruit_MQTT_Subscribe::setCallback(AdafruitIO_Feed *f, SubscribeCallbackIOType cb) { void Adafruit_MQTT_Subscribe::setCallback(AdafruitIO_MQTT *io, SubscribeCallbackIOType cb) {
callback_io = cb; callback_io = cb;
io_feed = f; io_mqtt= io;
} }
void Adafruit_MQTT_Subscribe::removeCallback(void) { void Adafruit_MQTT_Subscribe::removeCallback(void) {
@ -841,5 +841,5 @@ void Adafruit_MQTT_Subscribe::removeCallback(void) {
callback_buffer = 0; callback_buffer = 0;
callback_double = 0; callback_double = 0;
callback_io = 0; callback_io = 0;
io_feed = 0; io_mqtt = 0;
} }

View File

@ -30,8 +30,8 @@
#endif #endif
#define ADAFRUIT_MQTT_VERSION_MAJOR 0 #define ADAFRUIT_MQTT_VERSION_MAJOR 0
#define ADAFRUIT_MQTT_VERSION_MINOR 16 #define ADAFRUIT_MQTT_VERSION_MINOR 17
#define ADAFRUIT_MQTT_VERSION_PATCH 2 #define ADAFRUIT_MQTT_VERSION_PATCH 0
// Uncomment/comment to turn on/off debug output messages. // Uncomment/comment to turn on/off debug output messages.
//#define MQTT_DEBUG //#define MQTT_DEBUG
@ -116,7 +116,7 @@
#define SUBSCRIPTIONDATALEN 100 #define SUBSCRIPTIONDATALEN 100
#endif #endif
class AdafruitIO_Feed; // forward decl class AdafruitIO_MQTT; // forward decl
//Function pointer that returns an int //Function pointer that returns an int
typedef void (*SubscribeCallbackUInt32Type)(uint32_t); typedef void (*SubscribeCallbackUInt32Type)(uint32_t);
@ -125,7 +125,7 @@ typedef void (*SubscribeCallbackDoubleType)(double);
// returns a chunk of raw data // returns a chunk of raw data
typedef void (*SubscribeCallbackBufferType)(char *str, uint16_t len); typedef void (*SubscribeCallbackBufferType)(char *str, uint16_t len);
// returns an io data wrapper instance // returns an io data wrapper instance
typedef void (AdafruitIO_Feed::*SubscribeCallbackIOType)(char *str, uint16_t len); typedef void (AdafruitIO_MQTT::*SubscribeCallbackIOType)(char *str, uint16_t len);
extern void printBuffer(uint8_t *buffer, uint16_t len); extern void printBuffer(uint8_t *buffer, uint16_t len);
@ -277,7 +277,7 @@ class Adafruit_MQTT_Subscribe {
void setCallback(SubscribeCallbackUInt32Type callb); void setCallback(SubscribeCallbackUInt32Type callb);
void setCallback(SubscribeCallbackDoubleType callb); void setCallback(SubscribeCallbackDoubleType callb);
void setCallback(SubscribeCallbackBufferType callb); void setCallback(SubscribeCallbackBufferType callb);
void setCallback(AdafruitIO_Feed *io, SubscribeCallbackIOType callb); void setCallback(AdafruitIO_MQTT *io, SubscribeCallbackIOType callb);
void removeCallback(void); void removeCallback(void);
const char *topic; const char *topic;
@ -293,7 +293,7 @@ class Adafruit_MQTT_Subscribe {
SubscribeCallbackBufferType callback_buffer; SubscribeCallbackBufferType callback_buffer;
SubscribeCallbackIOType callback_io; SubscribeCallbackIOType callback_io;
AdafruitIO_Feed *io_feed; AdafruitIO_MQTT *io_mqtt;
private: private:
Adafruit_MQTT *mqtt; Adafruit_MQTT *mqtt;

View File

@ -1,152 +0,0 @@
// The MIT License (MIT)
//
// Copyright (c) 2015 Adafruit Industries
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef _ADAFRUIT_MQTT_CC3000_H_
#define _ADAFRUIT_MQTT_CC3000_H_
#include <Adafruit_SleepyDog.h>
#include <Adafruit_CC3000.h>
#include "Adafruit_MQTT.h"
// delay in ms between calls of available()
#define MQTT_CC3000_INTERAVAILDELAY 10
// CC3000-specific version of the Adafruit_MQTT class.
// Note that this is defined as a header-only class to prevent issues with using
// the library on non-CC3000 platforms (since Arduino will include all .cpp files
// in the compilation of the library).
class Adafruit_MQTT_CC3000 : public Adafruit_MQTT {
public:
Adafruit_MQTT_CC3000(Adafruit_CC3000 *cc3k, const char *server, uint16_t port,
const char *cid, const char *user, const char *pass):
Adafruit_MQTT(server, port, cid, user, pass),
cc3000(cc3k)
{}
Adafruit_MQTT_CC3000(Adafruit_CC3000 *cc3k, const char *server, uint16_t port,
const char *user = "", const char *pass = ""):
Adafruit_MQTT(server, port, user, pass),
cc3000(cc3k)
{}
bool connectServer() {
uint32_t ip = 0;
Watchdog.reset();
// look up IP address
if (serverip == 0) {
// Try looking up the website's IP address using CC3K's built in getHostByName
strcpy_P((char *)buffer, servername);
Serial.print((char *)buffer); Serial.print(F(" -> "));
uint8_t dnsretries = 5;
Watchdog.reset();
while (ip == 0) {
if (! cc3000->getHostByName((char *)buffer, &ip)) {
Serial.println(F("Couldn't resolve!"));
dnsretries--;
Watchdog.reset();
}
//Serial.println("OK"); Serial.println(ip, HEX);
if (!dnsretries) return false;
delay(500);
}
serverip = ip;
cc3000->printIPdotsRev(serverip);
Serial.println();
}
Watchdog.reset();
// connect to server
DEBUG_PRINTLN(F("Connecting to TCP"));
mqttclient = cc3000->connectTCP(serverip, portnum);
return mqttclient.connected();
}
bool disconnectServer() {
if (connected()) {
return (mqttclient.close() == 0);
}
else {
return true;
}
}
bool connected() {
return mqttclient.connected();
}
uint16_t readPacket(uint8_t *buffer, uint16_t maxlen, int16_t timeout) {
/* Read data until either the connection is closed, or the idle timeout is reached. */
uint16_t len = 0;
int16_t t = timeout;
while (mqttclient.connected() && (timeout >= 0)) {
//DEBUG_PRINT('.');
while (mqttclient.available()) {
//DEBUG_PRINT('!');
char c = mqttclient.read();
timeout = t; // reset the timeout
buffer[len] = c;
//DEBUG_PRINTLN((uint8_t)c, HEX);
len++;
if (len == maxlen) { // we read all we want, bail
DEBUG_PRINT(F("Read packet:\t"));
DEBUG_PRINTBUFFER(buffer, len);
return len;
}
}
Watchdog.reset();
timeout -= MQTT_CC3000_INTERAVAILDELAY;
delay(MQTT_CC3000_INTERAVAILDELAY);
}
return len;
}
bool sendPacket(uint8_t *buffer, uint16_t len) {
if (mqttclient.connected()) {
uint16_t ret = mqttclient.write(buffer, (size_t)len);
DEBUG_PRINT(F("sendPacket returned: ")); DEBUG_PRINTLN(ret);
if (ret != len) {
DEBUG_PRINTLN("Failed to send complete packet.")
return false;
}
} else {
DEBUG_PRINTLN(F("Connection failed!"));
return false;
}
return true;
}
private:
uint32_t serverip;
Adafruit_CC3000 *cc3000;
Adafruit_CC3000_Client mqttclient;
};
#endif

View File

@ -1,131 +0,0 @@
#include <Adafruit_SleepyDog.h>
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
//#define STATICIP
#define halt(s) { Serial.println(F( s )); while(1); }
uint16_t checkFirmwareVersion(void);
bool displayConnectionDetails(void);
extern Adafruit_CC3000 cc3000;
boolean CC3000connect(const char* wlan_ssid, const char* wlan_pass, uint8_t wlan_security) {
Watchdog.reset();
// Check for compatible firmware
if (checkFirmwareVersion() < 0x113) halt("Wrong firmware version!");
// Delete any old connection data on the module
Serial.println(F("\nDeleting old connection profiles"));
if (!cc3000.deleteProfiles()) halt("Failed!");
#ifdef STATICIP
Serial.println(F("Setting static IP"));
uint32_t ipAddress = cc3000.IP2U32(10, 0, 1, 19);
uint32_t netMask = cc3000.IP2U32(255, 255, 255, 0);
uint32_t defaultGateway = cc3000.IP2U32(10, 0, 1, 1);
uint32_t dns = cc3000.IP2U32(8, 8, 4, 4);
if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) {
Serial.println(F("Failed to set static IP!"));
while(1);
}
#endif
// Attempt to connect to an access point
Serial.print(F("\nAttempting to connect to "));
Serial.print(wlan_ssid); Serial.print(F("..."));
Watchdog.disable();
// try 3 times
if (!cc3000.connectToAP(wlan_ssid, wlan_pass, wlan_security, 3)) {
return false;
}
Watchdog.enable(8000);
Serial.println(F("Connected!"));
uint8_t retries;
#ifndef STATICIP
/* Wait for DHCP to complete */
Serial.println(F("Requesting DHCP"));
retries = 10;
while (!cc3000.checkDHCP())
{
Watchdog.reset();
delay(1000);
retries--;
if (!retries) return false;
}
#endif
/* Display the IP address DNS, Gateway, etc. */
retries = 10;
while (! displayConnectionDetails()) {
Watchdog.reset();
delay(1000);
retries--;
if (!retries) return false;
}
Watchdog.reset();
return true;
}
/**************************************************************************/
/*!
@brief Tries to read the CC3000's internal firmware patch ID
*/
/**************************************************************************/
uint16_t checkFirmwareVersion(void)
{
uint8_t major, minor;
uint16_t version;
if(!cc3000.getFirmwareVersion(&major, &minor))
{
Serial.println(F("Unable to retrieve the firmware version!\r\n"));
version = 0;
}
else
{
Serial.print(F("Firmware V. : "));
Serial.print(major); Serial.print(F(".")); Serial.println(minor);
version = major; version <<= 8; version |= minor;
}
return version;
}
/**************************************************************************/
/*!
@brief Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
{
Serial.println(F("Unable to retrieve the IP Address!\r\n"));
return false;
}
else
{
Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
Serial.println();
return true;
}
}

View File

@ -1,147 +0,0 @@
/***************************************************
Adafruit MQTT Library CC3000 Example
Designed specifically to work with the Adafruit WiFi products:
----> https://www.adafruit.com/products/1469
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution
****************************************************/
#include <Adafruit_SleepyDog.h>
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_CC3000.h"
/*************************** CC3000 Pins ***********************************/
#define ADAFRUIT_CC3000_IRQ 3 // MUST be an interrupt pin!
#define ADAFRUIT_CC3000_VBAT 5 // VBAT & CS can be any digital pins.
#define ADAFRUIT_CC3000_CS 10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
/************************* WiFi Access Point *********************************/
#define WLAN_SSID "...your SSID..." // can't be longer than 32 characters!
#define WLAN_PASS "...your password..."
#define WLAN_SECURITY WLAN_SEC_WPA2 // Can be: WLAN_SEC_UNSEC, WLAN_SEC_WEP,
// WLAN_SEC_WPA or WLAN_SEC_WPA2
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..."
#define AIO_KEY "...your AIO key..."
/************ Global State (you don't need to change this!) ******************/
// Setup the main CC3000 class, just like a normal CC3000 sketch.
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT);
// Setup the CC3000 MQTT class by passing in the CC3000 class and MQTT server and login details.
Adafruit_MQTT_CC3000 mqtt(&cc3000, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// You don't need to change anything below this line!
#define halt(s) { Serial.println(F( s )); while(1); }
// CC3000connect is a helper function that sets up the CC3000 and connects to
// the WiFi network. See the cc3000helper.cpp tab above for the source!
boolean CC3000connect(const char* wlan_ssid, const char* wlan_pass, uint8_t wlan_security);
/****************************** Feeds ***************************************/
// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell");
// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/onoff");
/*************************** Sketch Code ************************************/
void setup() {
Serial.begin(115200);
Serial.println(F("Adafruit MQTT demo"));
Serial.print(F("Free RAM: ")); Serial.println(getFreeRam(), DEC);
// Initialise the CC3000 module
Serial.print(F("\nInit the CC3000..."));
if (!cc3000.begin())
halt("Failed");
mqtt.subscribe(&onoffbutton);
while (! CC3000connect(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
Serial.println(F("Retrying WiFi"));
delay(1000);
}
}
uint32_t x=0;
void loop() {
// Make sure to reset watchdog every loop iteration!
Watchdog.reset();
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
// function definition further below.
MQTT_connect();
// this is our 'wait for incoming subscription packets' busy subloop
Adafruit_MQTT_Subscribe *subscription;
while ((subscription = mqtt.readSubscription(1000))) {
if (subscription == &onoffbutton) {
Serial.print(F("Got: "));
Serial.println((char *)onoffbutton.lastread);
}
}
// Now we can publish stuff!
Serial.print(F("\nSending photocell val "));
Serial.print(x);
Serial.print("...");
if (! photocell.publish(x++)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}
// ping the server to keep the mqtt connection alive
if(! mqtt.ping()) {
Serial.println(F("MQTT Ping failed."));
}
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
if (ret < 0)
CC3000connect(WLAN_SSID, WLAN_PASS, WLAN_SECURITY); // y0w, lets connect to wifi again
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
}
Serial.println("MQTT Connected!");
}

View File

@ -1,5 +1,5 @@
name=Adafruit MQTT Library name=Adafruit MQTT Library
version=0.16.2 version=0.17.0
author=Adafruit author=Adafruit
maintainer=Adafruit <info@adafruit.com> maintainer=Adafruit <info@adafruit.com>
sentence=MQTT library that supports the CC3000, FONA, ESP8266, Yun, and generic Arduino Client hardware. sentence=MQTT library that supports the CC3000, FONA, ESP8266, Yun, and generic Arduino Client hardware.