├── Adafruit_MQTT_Library-master ├── .gitignore ├── examples │ ├── mqtt_fona │ │ ├── .due.test.skip │ │ ├── .esp8266.test.skip │ │ ├── fonahelper.cpp │ │ └── mqtt_fona.ino │ ├── mqtt_yun │ │ ├── .due.test.skip │ │ ├── .uno.test.skip │ │ ├── .zero.test.skip │ │ ├── .leonardo.test.skip │ │ └── mqtt_yun.ino │ ├── mqtt_esp8266 │ │ ├── .due.test.skip │ │ ├── .uno.test.skip │ │ ├── .zero.test.skip │ │ ├── .leonardo.test.skip │ │ └── mqtt_esp8266.ino │ ├── mqtt_ethernet │ │ ├── .due.test.skip │ │ ├── .esp8266.test.skip │ │ └── mqtt_ethernet.ino │ ├── mqtt_2subs_esp8266 │ │ ├── .due.test.skip │ │ ├── .uno.test.skip │ │ ├── .zero.test.skip │ │ ├── .leonardo.test.skip │ │ └── mqtt_2subs_esp8266.ino │ ├── mqtt_arbitrary_data │ │ ├── .due.test.skip │ │ ├── .uno.test.skip │ │ ├── .zero.test.skip │ │ ├── .leonardo.test.skip │ │ ├── python_subscriber │ │ │ ├── requirements.txt │ │ │ ├── mqtt_figure.png │ │ │ └── subscriber.py │ │ ├── README.md │ │ └── mqtt_arbitrary_data.ino │ ├── adafruitio_time_esp8266 │ │ └── adafruitio_time_esp8266.ino │ ├── adafruitio_anon_time_esp8266 │ │ └── adafruitio_anon_time_esp8266.ino │ ├── mqtt_winc1500 │ │ └── mqtt_winc1500.ino │ ├── adafruitio_secure_esp8266 │ │ └── adafruitio_secure_esp8266.ino │ ├── adafruitio_errors_esp8266 │ │ └── adafruitio_errors_esp8266.ino │ └── mqtt_esp8266_callback │ │ └── mqtt_esp8266_callback.ino ├── library.properties ├── .travis.yml ├── keywords.txt ├── LICENSE ├── .github │ ├── PULL_REQUEST_TEMPLATE.md │ └── ISSUE_TEMPLATE.md ├── Adafruit_MQTT_Client.h ├── README.md ├── Adafruit_MQTT_Client.cpp ├── Adafruit_MQTT_FONA.h ├── Adafruit_MQTT.h └── Adafruit_MQTT.cpp ├── DHT-sensor-library-master ├── library.properties ├── keywords.txt ├── README.md ├── .github │ ├── PULL_REQUEST_TEMPLATE.md │ └── ISSUE_TEMPLATE.md ├── DHT.h ├── examples │ ├── DHTtester │ │ └── DHTtester.ino │ └── DHT_Unified_Sensor │ │ └── DHT_Unified_Sensor.ino ├── DHT_U.h ├── DHT_U.cpp └── DHT.cpp ├── .gitignore ├── .gitattributes └── Local_Home_Automation.ino /Adafruit_MQTT_Library-master/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | *.bts* 3 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_fona/.due.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_yun/.due.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_yun/.uno.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_yun/.zero.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_esp8266/.due.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_esp8266/.uno.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_ethernet/.due.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_fona/.esp8266.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_yun/.leonardo.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_2subs_esp8266/.due.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_2subs_esp8266/.uno.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_2subs_esp8266/.zero.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_arbitrary_data/.due.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_arbitrary_data/.uno.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_arbitrary_data/.zero.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_esp8266/.leonardo.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_ethernet/.esp8266.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_2subs_esp8266/.leonardo.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_arbitrary_data/.leonardo.test.skip: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_arbitrary_data/python_subscriber/requirements.txt: -------------------------------------------------------------------------------- 1 | paho-mqtt>=1.1 2 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_arbitrary_data/python_subscriber/mqtt_figure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techiesms/Home-Automation-based-on-Local-MQTT-server-using-Raspberry-Pi-and-Nodemcu-Board/master/Adafruit_MQTT_Library-master/examples/mqtt_arbitrary_data/python_subscriber/mqtt_figure.png -------------------------------------------------------------------------------- /DHT-sensor-library-master/library.properties: -------------------------------------------------------------------------------- 1 | name=DHT sensor library 2 | version=1.3.0 3 | author=Adafruit 4 | maintainer=Adafruit 5 | sentence=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors 6 | paragraph=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors 7 | category=Sensors 8 | url=https://github.com/adafruit/DHT-sensor-library 9 | architectures=* 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows thumbnail cache files 2 | Thumbs.db 3 | ehthumbs.db 4 | ehthumbs_vista.db 5 | 6 | # Folder config file 7 | Desktop.ini 8 | 9 | # Recycle Bin used on file shares 10 | $RECYCLE.BIN/ 11 | 12 | # Windows Installer files 13 | *.cab 14 | *.msi 15 | *.msm 16 | *.msp 17 | 18 | # Windows shortcuts 19 | *.lnk 20 | 21 | # ========================= 22 | # Operating System Files 23 | # ========================= 24 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/library.properties: -------------------------------------------------------------------------------- 1 | name=Adafruit MQTT Library 2 | version=0.20.1 3 | author=Adafruit 4 | maintainer=Adafruit 5 | sentence=MQTT library that supports the FONA, ESP8266, 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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | sudo: false 3 | before_install: 4 | - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh) 5 | install: 6 | - arduino --install-library "Adafruit SleepyDog Library,Adafruit FONA Library,Adafruit CC3000 Library,Adafruit_WINC1500" 7 | script: 8 | - build_main_platforms 9 | notifications: 10 | email: 11 | on_success: change 12 | on_failure: change 13 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/keywords.txt: -------------------------------------------------------------------------------- 1 | Adafruit_MQTT KEYWORD1 2 | Adafruit_MQTT_CC3000 KEYWORD1 3 | Adafruit_MQTT_FONA KEYWORD1 4 | Adafruit_MQTT_Client KEYWORD1 5 | Adafruit_MQTT_Publish KEYWORD1 6 | Adafruit_MQTT_Subscribe KEYWORD1 7 | connect KEYWORD2 8 | connectErrorString KEYWORD2 9 | disconnect KEYWORD2 10 | connected KEYWORD2 11 | will KEYWORD2 12 | publish KEYWORD2 13 | subscribe KEYWORD2 14 | unsubscribe KEYWORD2 15 | readSubscription KEYWORD2 16 | ping KEYWORD2 17 | setCallback KEYWORD2 18 | connectServer KEYWORD2 19 | disconnectServer KEYWORD2 20 | readPacket KEYWORD2 21 | sendPacket KEYWORD2 22 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/keywords.txt: -------------------------------------------------------------------------------- 1 | ########################################### 2 | # Syntax Coloring Map For DHT-sensor-library 3 | ########################################### 4 | 5 | ########################################### 6 | # Datatypes (KEYWORD1) 7 | ########################################### 8 | 9 | DHT KEYWORD1 10 | 11 | ########################################### 12 | # Methods and Functions (KEYWORD2) 13 | ########################################### 14 | 15 | begin KEYWORD2 16 | readTemperature KEYWORD2 17 | convertCtoF KEYWORD2 18 | convertFtoC KEYWORD2 19 | computeHeatIndex KEYWORD2 20 | readHumidity KEYWORD2 21 | read KEYWORD2 22 | 23 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/README.md: -------------------------------------------------------------------------------- 1 | This is an Arduino library for the DHT series of low cost temperature/humidity sensors. 2 | 3 | Tutorial: https://learn.adafruit.com/dht 4 | 5 | To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder DHT. Check that the DHT folder contains DHT.cpp and DHT.h. Place the DHT library folder your /libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE. 6 | 7 | # Adafruit DHT Humidity & Temperature Unified Sensor Library 8 | 9 | This library also includes an optional class for the 10 | [DHT humidity and temperature sensor](https://learn.adafruit.com/dht/overview) 11 | which is designed to work with the [Adafruit unified sensor library](https://learn.adafruit.com/using-the-adafruit-unified-sensor-driver/introduction). 12 | 13 | You must have the following Arduino libraries installed to use this class: 14 | 15 | - [Adafruit Unified Sensor Library](https://github.com/adafruit/Adafruit_Sensor) 16 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/.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 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/.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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/examples/mqtt_fona/fonahelper.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "Adafruit_FONA.h" 4 | 5 | #define halt(s) { Serial.println(F( s )); while(1); } 6 | 7 | extern Adafruit_FONA fona; 8 | extern SoftwareSerial fonaSS; 9 | 10 | boolean FONAconnect(const __FlashStringHelper *apn, const __FlashStringHelper *username, const __FlashStringHelper *password) { 11 | Watchdog.reset(); 12 | 13 | Serial.println(F("Initializing FONA....(May take 3 seconds)")); 14 | 15 | fonaSS.begin(4800); // if you're using software serial 16 | 17 | if (! fona.begin(fonaSS)) { // can also try fona.begin(Serial1) 18 | Serial.println(F("Couldn't find FONA")); 19 | return false; 20 | } 21 | fonaSS.println("AT+CMEE=2"); 22 | Serial.println(F("FONA is OK")); 23 | Watchdog.reset(); 24 | Serial.println(F("Checking for network...")); 25 | while (fona.getNetworkStatus() != 1) { 26 | delay(500); 27 | } 28 | 29 | Watchdog.reset(); 30 | delay(5000); // wait a few seconds to stabilize connection 31 | Watchdog.reset(); 32 | 33 | fona.setGPRSNetworkSettings(apn, username, password); 34 | 35 | Serial.println(F("Disabling GPRS")); 36 | fona.enableGPRS(false); 37 | 38 | Watchdog.reset(); 39 | delay(5000); // wait a few seconds to stabilize connection 40 | Watchdog.reset(); 41 | 42 | Serial.println(F("Enabling GPRS")); 43 | if (!fona.enableGPRS(true)) { 44 | Serial.println(F("Failed to turn GPRS on")); 45 | return false; 46 | } 47 | Watchdog.reset(); 48 | 49 | return true; 50 | } 51 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/DHT.h: -------------------------------------------------------------------------------- 1 | /* DHT library 2 | 3 | MIT license 4 | written by Adafruit Industries 5 | */ 6 | #ifndef DHT_H 7 | #define DHT_H 8 | 9 | #if ARDUINO >= 100 10 | #include "Arduino.h" 11 | #else 12 | #include "WProgram.h" 13 | #endif 14 | 15 | 16 | // Uncomment to enable printing out nice debug messages. 17 | //#define DHT_DEBUG 18 | 19 | // Define where debug output will be printed. 20 | #define DEBUG_PRINTER Serial 21 | 22 | // Setup debug printing macros. 23 | #ifdef DHT_DEBUG 24 | #define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); } 25 | #define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); } 26 | #else 27 | #define DEBUG_PRINT(...) {} 28 | #define DEBUG_PRINTLN(...) {} 29 | #endif 30 | 31 | // Define types of sensors. 32 | #define DHT11 11 33 | #define DHT22 22 34 | #define DHT21 21 35 | #define AM2301 21 36 | 37 | 38 | class DHT { 39 | public: 40 | DHT(uint8_t pin, uint8_t type, uint8_t count=6); 41 | void begin(void); 42 | float readTemperature(bool S=false, bool force=false); 43 | float convertCtoF(float); 44 | float convertFtoC(float); 45 | float computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit=true); 46 | float readHumidity(bool force=false); 47 | boolean read(bool force=false); 48 | 49 | private: 50 | uint8_t data[5]; 51 | uint8_t _pin, _type; 52 | #ifdef __AVR 53 | // Use direct GPIO access on an 8-bit AVR so keep track of the port and bitmask 54 | // for the digital pin connected to the DHT. Other platforms will use digitalRead. 55 | uint8_t _bit, _port; 56 | #endif 57 | uint32_t _lastreadtime, _maxcycles; 58 | bool _lastresult; 59 | 60 | uint32_t expectPulse(bool level); 61 | 62 | }; 63 | 64 | class InterruptLock { 65 | public: 66 | InterruptLock() { 67 | noInterrupts(); 68 | } 69 | ~InterruptLock() { 70 | interrupts(); 71 | } 72 | 73 | }; 74 | 75 | #endif 76 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/examples/DHTtester/DHTtester.ino: -------------------------------------------------------------------------------- 1 | // Example testing sketch for various DHT humidity/temperature sensors 2 | // Written by ladyada, public domain 3 | 4 | #include "DHT.h" 5 | 6 | #define DHTPIN 2 // what digital pin we're connected to 7 | 8 | // Uncomment whatever type you're using! 9 | //#define DHTTYPE DHT11 // DHT 11 10 | #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 11 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 12 | 13 | // Connect pin 1 (on the left) of the sensor to +5V 14 | // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 15 | // to 3.3V instead of 5V! 16 | // Connect pin 2 of the sensor to whatever your DHTPIN is 17 | // Connect pin 4 (on the right) of the sensor to GROUND 18 | // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor 19 | 20 | // Initialize DHT sensor. 21 | // Note that older versions of this library took an optional third parameter to 22 | // tweak the timings for faster processors. This parameter is no longer needed 23 | // as the current DHT reading algorithm adjusts itself to work on faster procs. 24 | DHT dht(DHTPIN, DHTTYPE); 25 | 26 | void setup() { 27 | Serial.begin(9600); 28 | Serial.println("DHTxx test!"); 29 | 30 | dht.begin(); 31 | } 32 | 33 | void loop() { 34 | // Wait a few seconds between measurements. 35 | delay(2000); 36 | 37 | // Reading temperature or humidity takes about 250 milliseconds! 38 | // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) 39 | float h = dht.readHumidity(); 40 | // Read temperature as Celsius (the default) 41 | float t = dht.readTemperature(); 42 | // Read temperature as Fahrenheit (isFahrenheit = true) 43 | float f = dht.readTemperature(true); 44 | 45 | // Check if any reads failed and exit early (to try again). 46 | if (isnan(h) || isnan(t) || isnan(f)) { 47 | Serial.println("Failed to read from DHT sensor!"); 48 | return; 49 | } 50 | 51 | // Compute heat index in Fahrenheit (the default) 52 | float hif = dht.computeHeatIndex(f, h); 53 | // Compute heat index in Celsius (isFahreheit = false) 54 | float hic = dht.computeHeatIndex(t, h, false); 55 | 56 | Serial.print("Humidity: "); 57 | Serial.print(h); 58 | Serial.print(" %\t"); 59 | Serial.print("Temperature: "); 60 | Serial.print(t); 61 | Serial.print(" *C "); 62 | Serial.print(f); 63 | Serial.print(" *F\t"); 64 | Serial.print("Heat index: "); 65 | Serial.print(hic); 66 | Serial.print(" *C "); 67 | Serial.print(hif); 68 | Serial.println(" *F"); 69 | } 70 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/DHT_U.h: -------------------------------------------------------------------------------- 1 | // DHT Temperature & Humidity Unified Sensor Library 2 | // Copyright (c) 2014 Adafruit Industries 3 | // Author: Tony DiCola 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 | #ifndef DHT_U_H 23 | #define DHT_U_H 24 | 25 | #include 26 | #include 27 | 28 | #define DHT_SENSOR_VERSION 1 29 | 30 | class DHT_Unified { 31 | public: 32 | DHT_Unified(uint8_t pin, uint8_t type, uint8_t count=6, int32_t tempSensorId=-1, int32_t humiditySensorId=-1); 33 | void begin(); 34 | 35 | class Temperature : public Adafruit_Sensor { 36 | public: 37 | Temperature(DHT_Unified* parent, int32_t id); 38 | bool getEvent(sensors_event_t* event); 39 | void getSensor(sensor_t* sensor); 40 | 41 | private: 42 | DHT_Unified* _parent; 43 | int32_t _id; 44 | 45 | }; 46 | 47 | class Humidity : public Adafruit_Sensor { 48 | public: 49 | Humidity(DHT_Unified* parent, int32_t id); 50 | bool getEvent(sensors_event_t* event); 51 | void getSensor(sensor_t* sensor); 52 | 53 | private: 54 | DHT_Unified* _parent; 55 | int32_t _id; 56 | 57 | }; 58 | 59 | Temperature temperature() { 60 | return _temp; 61 | } 62 | 63 | Humidity humidity() { 64 | return _humidity; 65 | } 66 | 67 | private: 68 | DHT _dht; 69 | uint8_t _type; 70 | Temperature _temp; 71 | Humidity _humidity; 72 | 73 | void setName(sensor_t* sensor); 74 | void setMinDelay(sensor_t* sensor); 75 | 76 | }; 77 | 78 | #endif 79 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 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 | #ifndef _ADAFRUIT_MQTT_CLIENT_H_ 23 | #define _ADAFRUIT_MQTT_CLIENT_H_ 24 | 25 | #include "Client.h" 26 | #include "Adafruit_MQTT.h" 27 | 28 | 29 | // How long to delay waiting for new data to be available in readPacket. 30 | #define MQTT_CLIENT_READINTERVAL_MS 10 31 | 32 | 33 | // MQTT client implementation for a generic Arduino Client interface. Can work 34 | // with almost all Arduino network hardware like ethernet shield, wifi shield, 35 | // and even other platforms like ESP8266. 36 | class Adafruit_MQTT_Client : public Adafruit_MQTT { 37 | public: 38 | Adafruit_MQTT_Client(Client *client, const char *server, uint16_t port, 39 | const char *cid, const char *user, const char *pass): 40 | Adafruit_MQTT(server, port, cid, user, pass), 41 | client(client) 42 | {} 43 | 44 | Adafruit_MQTT_Client(Client *client, const char *server, uint16_t port, 45 | const char *user="", const char *pass=""): 46 | Adafruit_MQTT(server, port, user, pass), 47 | client(client) 48 | {} 49 | 50 | bool connectServer(); 51 | bool disconnectServer(); 52 | bool connected(); 53 | uint16_t readPacket(uint8_t *buffer, uint16_t maxlen, int16_t timeout); 54 | bool sendPacket(uint8_t *buffer, uint16_t len); 55 | 56 | private: 57 | Client* client; 58 | }; 59 | 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/README.md: -------------------------------------------------------------------------------- 1 | # Adafruit MQTT Library [![Build Status](https://travis-ci.org/adafruit/Adafruit_MQTT_Library.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_MQTT_Library) 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 | ATtiny85 @ 16MHz | | | X | 40 | ATtiny85 @ 8MHz | | | X | 41 | Intel Curie @ 32MHz | | | X | 42 | STM32F2 | | | X | 43 | 44 | * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini 45 | * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V 46 | * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 47 | * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro 48 | * ESP8266 : Adafruit Huzzah 49 | * ATmega2560 @ 16MHz : Arduino Mega 50 | * ATSAM3X8E : Arduino Due 51 | * ATSAM21D : Arduino Zero, M0 Pro 52 | * ATtiny85 @ 16MHz : Adafruit Trinket 5V 53 | * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V 54 | 55 | 56 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/.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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/.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 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino: -------------------------------------------------------------------------------- 1 | // DHT Temperature & Humidity Sensor 2 | // Unified Sensor Library Example 3 | // Written by Tony DiCola for Adafruit Industries 4 | // Released under an MIT license. 5 | 6 | // Depends on the following Arduino libraries: 7 | // - Adafruit Unified Sensor Library: https://github.com/adafruit/Adafruit_Sensor 8 | // - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | #define DHTPIN 2 // Pin which is connected to the DHT sensor. 15 | 16 | // Uncomment the type of sensor in use: 17 | //#define DHTTYPE DHT11 // DHT 11 18 | #define DHTTYPE DHT22 // DHT 22 (AM2302) 19 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 20 | 21 | // See guide for details on sensor wiring and usage: 22 | // https://learn.adafruit.com/dht/overview 23 | 24 | DHT_Unified dht(DHTPIN, DHTTYPE); 25 | 26 | uint32_t delayMS; 27 | 28 | void setup() { 29 | Serial.begin(9600); 30 | // Initialize device. 31 | dht.begin(); 32 | Serial.println("DHTxx Unified Sensor Example"); 33 | // Print temperature sensor details. 34 | sensor_t sensor; 35 | dht.temperature().getSensor(&sensor); 36 | Serial.println("------------------------------------"); 37 | Serial.println("Temperature"); 38 | Serial.print ("Sensor: "); Serial.println(sensor.name); 39 | Serial.print ("Driver Ver: "); Serial.println(sensor.version); 40 | Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); 41 | Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" *C"); 42 | Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" *C"); 43 | Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" *C"); 44 | Serial.println("------------------------------------"); 45 | // Print humidity sensor details. 46 | dht.humidity().getSensor(&sensor); 47 | Serial.println("------------------------------------"); 48 | Serial.println("Humidity"); 49 | Serial.print ("Sensor: "); Serial.println(sensor.name); 50 | Serial.print ("Driver Ver: "); Serial.println(sensor.version); 51 | Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); 52 | Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println("%"); 53 | Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println("%"); 54 | Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println("%"); 55 | Serial.println("------------------------------------"); 56 | // Set delay between sensor readings based on sensor details. 57 | delayMS = sensor.min_delay / 1000; 58 | } 59 | 60 | void loop() { 61 | // Delay between measurements. 62 | delay(delayMS); 63 | // Get temperature event and print its value. 64 | sensors_event_t event; 65 | dht.temperature().getEvent(&event); 66 | if (isnan(event.temperature)) { 67 | Serial.println("Error reading temperature!"); 68 | } 69 | else { 70 | Serial.print("Temperature: "); 71 | Serial.print(event.temperature); 72 | Serial.println(" *C"); 73 | } 74 | // Get humidity event and print its value. 75 | dht.humidity().getEvent(&event); 76 | if (isnan(event.relative_humidity)) { 77 | Serial.println("Error reading humidity!"); 78 | } 79 | else { 80 | Serial.print("Humidity: "); 81 | Serial.print(event.relative_humidity); 82 | Serial.println("%"); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 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 | #include "Adafruit_MQTT_Client.h" 23 | 24 | 25 | bool Adafruit_MQTT_Client::connectServer() { 26 | // Grab server name from flash and copy to buffer for name resolution. 27 | memset(buffer, 0, sizeof(buffer)); 28 | strcpy((char *)buffer, servername); 29 | DEBUG_PRINT(F("Connecting to: ")); 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: ")); DEBUG_PRINTLN(r); 33 | return r != 0; 34 | } 35 | 36 | bool Adafruit_MQTT_Client::disconnectServer() { 37 | // Stop connection if connected and return success (stop has no indication of 38 | // failure). 39 | if (client->connected()) { 40 | client->stop(); 41 | } 42 | return true; 43 | } 44 | 45 | bool Adafruit_MQTT_Client::connected() { 46 | // Return true if connected, false if not connected. 47 | return client->connected(); 48 | } 49 | 50 | uint16_t Adafruit_MQTT_Client::readPacket(uint8_t *buffer, uint16_t maxlen, 51 | int16_t timeout) { 52 | /* Read data until either the connection is closed, or the idle timeout is reached. */ 53 | uint16_t len = 0; 54 | int16_t t = timeout; 55 | 56 | while (client->connected() && (timeout >= 0)) { 57 | //DEBUG_PRINT('.'); 58 | while (client->available()) { 59 | //DEBUG_PRINT('!'); 60 | char c = client->read(); 61 | timeout = t; // reset the timeout 62 | buffer[len] = c; 63 | //DEBUG_PRINTLN((uint8_t)c, HEX); 64 | len++; 65 | if (len == maxlen) { // we read all we want, bail 66 | DEBUG_PRINT(F("Read data:\t")); 67 | DEBUG_PRINTBUFFER(buffer, len); 68 | return len; 69 | } 70 | } 71 | timeout -= MQTT_CLIENT_READINTERVAL_MS; 72 | delay(MQTT_CLIENT_READINTERVAL_MS); 73 | } 74 | return len; 75 | } 76 | 77 | bool Adafruit_MQTT_Client::sendPacket(uint8_t *buffer, uint16_t len) { 78 | uint16_t ret = 0; 79 | 80 | while (len > 0) { 81 | if (client->connected()) { 82 | // send 250 bytes at most at a time, can adjust this later based on Client 83 | 84 | uint16_t sendlen = len > 250 ? 250 : len; 85 | //Serial.print("Sending: "); Serial.println(sendlen); 86 | ret = client->write(buffer, sendlen); 87 | DEBUG_PRINT(F("Client sendPacket returned: ")); DEBUG_PRINTLN(ret); 88 | len -= ret; 89 | 90 | if (ret != sendlen) { 91 | DEBUG_PRINTLN("Failed to send packet."); 92 | return false; 93 | } 94 | } else { 95 | DEBUG_PRINTLN(F("Connection failed!")); 96 | return false; 97 | } 98 | } 99 | return true; 100 | } 101 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | } -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 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 | #ifndef _ADAFRUIT_MQTT_FONA_H_ 23 | #define _ADAFRUIT_MQTT_FONA_H_ 24 | 25 | #include 26 | #include "Adafruit_MQTT.h" 27 | 28 | #define MQTT_FONA_INTERAVAILDELAY 100 29 | #define MQTT_FONA_QUERYDELAY 500 30 | 31 | 32 | // FONA-specific version of the Adafruit_MQTT class. 33 | // Note that this is defined as a header-only class to prevent issues with using 34 | // the library on non-FONA platforms (since Arduino will include all .cpp files 35 | // in the compilation of the library). 36 | class Adafruit_MQTT_FONA : public Adafruit_MQTT { 37 | public: 38 | Adafruit_MQTT_FONA(Adafruit_FONA *f, const char *server, uint16_t port, 39 | const char *cid, const char *user, const char *pass): 40 | Adafruit_MQTT(server, port, cid, user, pass), 41 | fona(f) 42 | {} 43 | 44 | Adafruit_MQTT_FONA(Adafruit_FONA *f, const char *server, uint16_t port, 45 | const char *user="", const char *pass=""): 46 | Adafruit_MQTT(server, port, user, pass), 47 | fona(f) 48 | {} 49 | 50 | bool connectServer() { 51 | char server[40]; 52 | strncpy(server, servername, 40); 53 | #ifdef ADAFRUIT_SLEEPYDOG_H 54 | Watchdog.reset(); 55 | #endif 56 | 57 | // connect to server 58 | DEBUG_PRINTLN(F("Connecting to TCP")); 59 | return fona->TCPconnect(server, portnum); 60 | } 61 | 62 | bool disconnectServer() { 63 | return fona->TCPclose(); 64 | } 65 | 66 | bool connected() { 67 | // Return true if connected, false if not connected. 68 | return fona->TCPconnected(); 69 | } 70 | 71 | uint16_t readPacket(uint8_t *buffer, uint16_t maxlen, int16_t timeout) { 72 | uint8_t *buffp = buffer; 73 | DEBUG_PRINTLN(F("Reading data..")); 74 | 75 | if (!fona->TCPconnected()) return 0; 76 | 77 | 78 | /* Read data until either the connection is closed, or the idle timeout is reached. */ 79 | uint16_t len = 0; 80 | int16_t t = timeout; 81 | uint16_t avail; 82 | 83 | while (fona->TCPconnected() && (timeout >= 0)) { 84 | //DEBUG_PRINT('.'); 85 | while (avail = fona->TCPavailable()) { 86 | //DEBUG_PRINT('!'); 87 | 88 | if (len + avail > maxlen) { 89 | avail = maxlen - len; 90 | if (avail == 0) return len; 91 | } 92 | 93 | // try to read the data into the end of the pointer 94 | if (! fona->TCPread(buffp, avail)) return len; 95 | 96 | // read it! advance pointer 97 | buffp += avail; 98 | len += avail; 99 | timeout = t; // reset the timeout 100 | 101 | //DEBUG_PRINTLN((uint8_t)c, HEX); 102 | 103 | if (len == maxlen) { // we read all we want, bail 104 | DEBUG_PRINT(F("Read:\t")); 105 | DEBUG_PRINTBUFFER(buffer, len); 106 | return len; 107 | } 108 | } 109 | #ifdef ADAFRUIT_SLEEPYDOG_H 110 | Watchdog.reset(); 111 | #endif 112 | timeout -= MQTT_FONA_INTERAVAILDELAY; 113 | timeout -= MQTT_FONA_QUERYDELAY; // this is how long it takes to query the FONA for avail() 114 | delay(MQTT_FONA_INTERAVAILDELAY); 115 | } 116 | 117 | return len; 118 | } 119 | 120 | bool sendPacket(uint8_t *buffer, uint16_t len) { 121 | DEBUG_PRINTLN(F("Writing packet")); 122 | if (fona->TCPconnected()) { 123 | boolean ret = fona->TCPsend((char *)buffer, len); 124 | //DEBUG_PRINT(F("sendPacket returned: ")); DEBUG_PRINTLN(ret); 125 | if (!ret) { 126 | DEBUG_PRINTLN("Failed to send packet."); 127 | return false; 128 | } 129 | } else { 130 | DEBUG_PRINTLN(F("Connection failed!")); 131 | return false; 132 | } 133 | return true; 134 | } 135 | 136 | private: 137 | uint32_t serverip; 138 | Adafruit_FONA *fona; 139 | }; 140 | 141 | 142 | #endif 143 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 WiFiFlientSecure 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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 "...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 8883 // 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 | // WiFiFlientSecure for SSL/TLS support 38 | WiFiClientSecure client; 39 | 40 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 41 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 42 | 43 | // io.adafruit.com SHA1 fingerprint. Current fingerprint can be verified via: 44 | // echo | openssl s_client -connect io.adafruit.com:443 |& openssl x509 -fingerprint -noout 45 | #define AIO_SSL_FINGERPRINT "77 00 54 2D DA E7 D8 03 27 31 23 99 EB 27 DB CB A5 4C 57 18" 46 | 47 | /****************************** Feeds ***************************************/ 48 | 49 | // Setup a feed called 'test' for publishing. 50 | // Notice MQTT paths for AIO follow the form: /feeds/ 51 | Adafruit_MQTT_Publish test = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/test"); 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 | void verifyFingerprint(); 59 | 60 | void setup() { 61 | Serial.begin(115200); 62 | delay(10); 63 | 64 | Serial.println(F("Adafruit IO MQTTS (SSL/TLS) Example")); 65 | 66 | // Connect to WiFi access point. 67 | Serial.println(); Serial.println(); 68 | Serial.print("Connecting to "); 69 | Serial.println(WLAN_SSID); 70 | 71 | delay(1000); 72 | 73 | WiFi.begin(WLAN_SSID, WLAN_PASS); 74 | delay(2000); 75 | 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 | // check the fingerprint of io.adafruit.com's SSL cert 86 | verifyFingerprint(); 87 | 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 | // Now we can publish stuff! 99 | Serial.print(F("\nSending val ")); 100 | Serial.print(x); 101 | Serial.print(F(" to test feed...")); 102 | if (! test.publish(x++)) { 103 | Serial.println(F("Failed")); 104 | } else { 105 | Serial.println(F("OK!")); 106 | } 107 | 108 | // wait a couple seconds to avoid rate limit 109 | delay(2000); 110 | 111 | } 112 | 113 | 114 | void verifyFingerprint() { 115 | 116 | const char* host = AIO_SERVER; 117 | 118 | Serial.print("Connecting to "); 119 | Serial.println(host); 120 | 121 | if (! client.connect(host, AIO_SERVERPORT)) { 122 | Serial.println("Connection failed. Halting execution."); 123 | while(1); 124 | } 125 | 126 | if (client.verify(fingerprint, host)) { 127 | Serial.println("Connection secure."); 128 | } else { 129 | Serial.println("Connection insecure! Halting execution."); 130 | while(1); 131 | } 132 | 133 | } 134 | 135 | // Function to connect and reconnect as necessary to the MQTT server. 136 | // Should be called in the loop function and it will take care if connecting. 137 | void MQTT_connect() { 138 | int8_t ret; 139 | 140 | // Stop if already connected. 141 | if (mqtt.connected()) { 142 | return; 143 | } 144 | 145 | Serial.print("Connecting to MQTT... "); 146 | 147 | uint8_t retries = 3; 148 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 149 | Serial.println(mqtt.connectErrorString(ret)); 150 | Serial.println("Retrying MQTT connection in 5 seconds..."); 151 | mqtt.disconnect(); 152 | delay(5000); // wait 5 seconds 153 | retries--; 154 | if (retries == 0) { 155 | // basically die and wait for WDT to reset me 156 | while (1); 157 | } 158 | } 159 | 160 | Serial.println("MQTT Connected!"); 161 | } 162 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/DHT_U.cpp: -------------------------------------------------------------------------------- 1 | // DHT Temperature & Humidity Unified Sensor Library 2 | // Copyright (c) 2014 Adafruit Industries 3 | // Author: Tony DiCola 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 | #include "DHT_U.h" 23 | 24 | DHT_Unified::DHT_Unified(uint8_t pin, uint8_t type, uint8_t count, int32_t tempSensorId, int32_t humiditySensorId): 25 | _dht(pin, type, count), 26 | _type(type), 27 | _temp(this, tempSensorId), 28 | _humidity(this, humiditySensorId) 29 | {} 30 | 31 | void DHT_Unified::begin() { 32 | _dht.begin(); 33 | } 34 | 35 | void DHT_Unified::setName(sensor_t* sensor) { 36 | switch(_type) { 37 | case DHT11: 38 | strncpy(sensor->name, "DHT11", sizeof(sensor->name) - 1); 39 | break; 40 | case DHT21: 41 | strncpy(sensor->name, "DHT21", sizeof(sensor->name) - 1); 42 | break; 43 | case DHT22: 44 | strncpy(sensor->name, "DHT22", sizeof(sensor->name) - 1); 45 | break; 46 | default: 47 | // TODO: Perhaps this should be an error? However main DHT library doesn't enforce 48 | // restrictions on the sensor type value. Pick a generic name for now. 49 | strncpy(sensor->name, "DHT?", sizeof(sensor->name) - 1); 50 | break; 51 | } 52 | sensor->name[sizeof(sensor->name)- 1] = 0; 53 | } 54 | 55 | void DHT_Unified::setMinDelay(sensor_t* sensor) { 56 | switch(_type) { 57 | case DHT11: 58 | sensor->min_delay = 1000000L; // 1 second (in microseconds) 59 | break; 60 | case DHT21: 61 | sensor->min_delay = 2000000L; // 2 seconds (in microseconds) 62 | break; 63 | case DHT22: 64 | sensor->min_delay = 2000000L; // 2 seconds (in microseconds) 65 | break; 66 | default: 67 | // Default to slowest sample rate in case of unknown type. 68 | sensor->min_delay = 2000000L; // 2 seconds (in microseconds) 69 | break; 70 | } 71 | } 72 | 73 | DHT_Unified::Temperature::Temperature(DHT_Unified* parent, int32_t id): 74 | _parent(parent), 75 | _id(id) 76 | {} 77 | 78 | bool DHT_Unified::Temperature::getEvent(sensors_event_t* event) { 79 | // Clear event definition. 80 | memset(event, 0, sizeof(sensors_event_t)); 81 | // Populate sensor reading values. 82 | event->version = sizeof(sensors_event_t); 83 | event->sensor_id = _id; 84 | event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; 85 | event->timestamp = millis(); 86 | event->temperature = _parent->_dht.readTemperature(); 87 | 88 | return true; 89 | } 90 | 91 | void DHT_Unified::Temperature::getSensor(sensor_t* sensor) { 92 | // Clear sensor definition. 93 | memset(sensor, 0, sizeof(sensor_t)); 94 | // Set sensor name. 95 | _parent->setName(sensor); 96 | // Set version and ID 97 | sensor->version = DHT_SENSOR_VERSION; 98 | sensor->sensor_id = _id; 99 | // Set type and characteristics. 100 | sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; 101 | _parent->setMinDelay(sensor); 102 | switch (_parent->_type) { 103 | case DHT11: 104 | sensor->max_value = 50.0F; 105 | sensor->min_value = 0.0F; 106 | sensor->resolution = 2.0F; 107 | break; 108 | case DHT21: 109 | sensor->max_value = 80.0F; 110 | sensor->min_value = -40.0F; 111 | sensor->resolution = 0.1F; 112 | break; 113 | case DHT22: 114 | sensor->max_value = 125.0F; 115 | sensor->min_value = -40.0F; 116 | sensor->resolution = 0.1F; 117 | break; 118 | default: 119 | // Unknown type, default to 0. 120 | sensor->max_value = 0.0F; 121 | sensor->min_value = 0.0F; 122 | sensor->resolution = 0.0F; 123 | break; 124 | } 125 | } 126 | 127 | DHT_Unified::Humidity::Humidity(DHT_Unified* parent, int32_t id): 128 | _parent(parent), 129 | _id(id) 130 | {} 131 | 132 | bool DHT_Unified::Humidity::getEvent(sensors_event_t* event) { 133 | // Clear event definition. 134 | memset(event, 0, sizeof(sensors_event_t)); 135 | // Populate sensor reading values. 136 | event->version = sizeof(sensors_event_t); 137 | event->sensor_id = _id; 138 | event->type = SENSOR_TYPE_RELATIVE_HUMIDITY; 139 | event->timestamp = millis(); 140 | event->relative_humidity = _parent->_dht.readHumidity(); 141 | 142 | return true; 143 | } 144 | 145 | void DHT_Unified::Humidity::getSensor(sensor_t* sensor) { 146 | // Clear sensor definition. 147 | memset(sensor, 0, sizeof(sensor_t)); 148 | // Set sensor name. 149 | _parent->setName(sensor); 150 | // Set version and ID 151 | sensor->version = DHT_SENSOR_VERSION; 152 | sensor->sensor_id = _id; 153 | // Set type and characteristics. 154 | sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY; 155 | _parent->setMinDelay(sensor); 156 | switch (_parent->_type) { 157 | case DHT11: 158 | sensor->max_value = 80.0F; 159 | sensor->min_value = 20.0F; 160 | sensor->resolution = 5.0F; 161 | break; 162 | case DHT21: 163 | sensor->max_value = 100.0F; 164 | sensor->min_value = 0.0F; 165 | sensor->resolution = 0.1F; 166 | break; 167 | case DHT22: 168 | sensor->max_value = 100.0F; 169 | sensor->min_value = 0.0F; 170 | sensor->resolution = 0.1F; 171 | break; 172 | default: 173 | // Unknown type, default to 0. 174 | sensor->max_value = 0.0F; 175 | sensor->min_value = 0.0F; 176 | sensor->resolution = 0.0F; 177 | break; 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 | -------------------------------------------------------------------------------- /Local_Home_Automation.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 | Code is edited by Sachin Soni for it's project called 19 | Ultimate Home Automation 20 | 21 | For Project video, visit his YouTube channel named "techiesms" 22 | 23 | Website:- http://www.techiesms.com 24 | 25 | #techiesms 26 | explore | learn | share 27 | 28 | ****************************************************/ 29 | #include 30 | #include "Adafruit_MQTT.h" 31 | #include "Adafruit_MQTT_Client.h" 32 | #include "DHT.h" 33 | 34 | /************************* Pin Definition *********************************/ 35 | 36 | //Relays for switching appliances 37 | #define Relay1 D6 38 | #define Relay2 D2 39 | #define Relay3 D1 40 | #define Relay4 D5 41 | 42 | //DHT11 for reading temperature and humidity value 43 | #define DHTPIN D7 44 | 45 | 46 | /************************* WiFi Access Point *********************************/ 47 | 48 | #define WLAN_SSID "SSID" 49 | #define WLAN_PASS "PASSWORD" 50 | 51 | /************************* Adafruit.io Setup *********************************/ 52 | 53 | #define AIO_SERVER "0.0.0.0" //IP address of RPi 54 | #define AIO_SERVERPORT 1883 // use 8883 for SSL 55 | #define AIO_USERNAME "" 56 | #define AIO_KEY "" 57 | 58 | /************ Global State (you don't need to change this!) ******************/ 59 | 60 | // Create an ESP8266 WiFiClient class to connect to the MQTT server. 61 | WiFiClient client; 62 | // or... use WiFiFlientSecure for SSL 63 | //WiFiClientSecure client; 64 | 65 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 66 | Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); 67 | 68 | /****************************** Feeds ***************************************/ 69 | 70 | // Notice MQTT paths for AIO follow the form: /feeds/ 71 | Adafruit_MQTT_Publish Humidity = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/humidity"); 72 | Adafruit_MQTT_Publish Temperature = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temperature"); 73 | 74 | // Setup a feed called 'onoff' for subscribing to changes. 75 | Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay1"); 76 | Adafruit_MQTT_Subscribe Fan1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay2"); 77 | Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay3"); 78 | Adafruit_MQTT_Subscribe Fan2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/relay4"); 79 | 80 | 81 | 82 | /************ Necessary declaration for DHT11 ******************/ 83 | #define DHTTYPE DHT11 // DHT 11 84 | 85 | DHT dht(DHTPIN, DHTTYPE); 86 | uint32_t delayMS; 87 | 88 | 89 | /*************************** Sketch Code ************************************/ 90 | 91 | // Bug workaround for Arduino 1.6.6, it seems to need a function declaration 92 | // for some reason (only affects ESP8266, likely an arduino-builder bug). 93 | void MQTT_connect(); 94 | //Servo myservo; 95 | void setup() { 96 | Serial.begin(115200); 97 | 98 | delay(10); 99 | pinMode(Relay1, OUTPUT); 100 | pinMode(Relay2, OUTPUT); 101 | pinMode(Relay3, OUTPUT); 102 | pinMode(Relay4, OUTPUT); 103 | 104 | Serial.println(F("Adafruit MQTT demo")); 105 | 106 | // Connect to WiFi access point. 107 | Serial.println(); Serial.println(); 108 | Serial.print("Connecting to "); 109 | Serial.println(WLAN_SSID); 110 | 111 | WiFi.begin(WLAN_SSID, WLAN_PASS); 112 | while (WiFi.status() != WL_CONNECTED) { 113 | delay(500); 114 | Serial.print("."); 115 | } 116 | Serial.println(); 117 | 118 | Serial.println("WiFi connected"); 119 | Serial.println("IP address: "); Serial.println(WiFi.localIP()); 120 | 121 | //Setting up DHT sensor 122 | dht.begin(); 123 | 124 | // Setup MQTT subscription for onoff feed. 125 | mqtt.subscribe(&Light1); 126 | mqtt.subscribe(&Fan1); 127 | mqtt.subscribe(&Light2); 128 | mqtt.subscribe(&Fan2); 129 | } 130 | 131 | uint32_t x = 0; 132 | 133 | void loop() { 134 | // Ensure the connection to the MQTT server is alive (this will make the first 135 | // connection and automatically reconnect when disconnected). See the MQTT_connect 136 | // function definition further below. 137 | MQTT_connect(); 138 | // this is our 'wait for incoming subscription packets' busy subloop 139 | // try to spend your time here 140 | 141 | Adafruit_MQTT_Subscribe *subscription; 142 | while ((subscription = mqtt.readSubscription(20000))) { 143 | if (subscription == &Light1) { 144 | Serial.print(F("Got: ")); 145 | Serial.println((char *)Light1.lastread); 146 | int Light1_State = atoi((char *)Light1.lastread); 147 | digitalWrite(Relay1, Light1_State); 148 | 149 | } 150 | if (subscription == &Light2) { 151 | Serial.print(F("Got: ")); 152 | Serial.println((char *)Light2.lastread); 153 | int Light2_State = atoi((char *)Light2.lastread); 154 | digitalWrite(Relay2, Light2_State); 155 | } 156 | if (subscription == &Fan1) { 157 | Serial.print(F("Got: ")); 158 | Serial.println((char *)Fan1.lastread); 159 | int Fan1_State = atoi((char *)Fan1.lastread); 160 | digitalWrite(Relay3, Fan1_State); 161 | } 162 | if (subscription == &Fan2) { 163 | Serial.print(F("Got: ")); 164 | Serial.println((char *)Fan2.lastread); 165 | int Fan2_State = atoi((char *)Fan2.lastread); 166 | digitalWrite(Relay4, Fan2_State); 167 | 168 | } 169 | } 170 | 171 | 172 | 173 | // Reading temperature or humidity takes about 250 milliseconds! 174 | // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) 175 | float h = dht.readHumidity(); 176 | // Read temperature as Celsius (the default) 177 | float t = dht.readTemperature(); 178 | // Read temperature as Fahrenheit (isFahrenheit = true) 179 | float f = dht.readTemperature(true); 180 | 181 | // Check if any reads failed and exit early (to try again). 182 | if (isnan(h) || isnan(t) || isnan(f)) { 183 | Serial.println("Failed to read from DHT sensor!"); 184 | return; 185 | } 186 | if (! Humidity.publish(h)) { 187 | Serial.println(F("Failed")); 188 | } else { 189 | Serial.println(F("OK!")); 190 | } 191 | if (! Temperature.publish(t)) { 192 | Serial.println(F("Failed")); 193 | } else { 194 | Serial.println(F("OK!")); 195 | } 196 | 197 | 198 | // ping the server to keep the mqtt connection alive 199 | // NOT required if you are publishing once every KEEPALIVE seconds 200 | /* 201 | if(! mqtt.ping()) { 202 | mqtt.disconnect(); 203 | } 204 | */ 205 | } 206 | 207 | // Function to connect and reconnect as necessary to the MQTT server. 208 | // Should be called in the loop function and it will take care if connecting. 209 | void MQTT_connect() { 210 | int8_t ret; 211 | 212 | // Stop if already connected. 213 | if (mqtt.connected()) { 214 | return; 215 | } 216 | 217 | Serial.print("Connecting to MQTT... "); 218 | 219 | uint8_t retries = 3; 220 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 221 | Serial.println(mqtt.connectErrorString(ret)); 222 | Serial.println("Retrying MQTT connection in 5 seconds..."); 223 | mqtt.disconnect(); 224 | delay(5000); // wait 5 seconds 225 | retries--; 226 | if (retries == 0) { 227 | // basically die and wait for WDT to reset me 228 | while (1); 229 | } 230 | } 231 | Serial.println("MQTT Connected!"); 232 | } 233 | -------------------------------------------------------------------------------- /DHT-sensor-library-master/DHT.cpp: -------------------------------------------------------------------------------- 1 | /* DHT library 2 | 3 | MIT license 4 | written by Adafruit Industries 5 | */ 6 | 7 | #include "DHT.h" 8 | 9 | #define MIN_INTERVAL 2000 10 | 11 | DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) { 12 | _pin = pin; 13 | _type = type; 14 | #ifdef __AVR 15 | _bit = digitalPinToBitMask(pin); 16 | _port = digitalPinToPort(pin); 17 | #endif 18 | _maxcycles = microsecondsToClockCycles(1000); // 1 millisecond timeout for 19 | // reading pulses from DHT sensor. 20 | // Note that count is now ignored as the DHT reading algorithm adjusts itself 21 | // basd on the speed of the processor. 22 | } 23 | 24 | void DHT::begin(void) { 25 | // set up the pins! 26 | pinMode(_pin, INPUT_PULLUP); 27 | // Using this value makes sure that millis() - lastreadtime will be 28 | // >= MIN_INTERVAL right away. Note that this assignment wraps around, 29 | // but so will the subtraction. 30 | _lastreadtime = -MIN_INTERVAL; 31 | DEBUG_PRINT("Max clock cycles: "); DEBUG_PRINTLN(_maxcycles, DEC); 32 | } 33 | 34 | //boolean S == Scale. True == Fahrenheit; False == Celcius 35 | float DHT::readTemperature(bool S, bool force) { 36 | float f = NAN; 37 | 38 | if (read(force)) { 39 | switch (_type) { 40 | case DHT11: 41 | f = data[2]; 42 | if(S) { 43 | f = convertCtoF(f); 44 | } 45 | break; 46 | case DHT22: 47 | case DHT21: 48 | f = data[2] & 0x7F; 49 | f *= 256; 50 | f += data[3]; 51 | f *= 0.1; 52 | if (data[2] & 0x80) { 53 | f *= -1; 54 | } 55 | if(S) { 56 | f = convertCtoF(f); 57 | } 58 | break; 59 | } 60 | } 61 | return f; 62 | } 63 | 64 | float DHT::convertCtoF(float c) { 65 | return c * 1.8 + 32; 66 | } 67 | 68 | float DHT::convertFtoC(float f) { 69 | return (f - 32) * 0.55555; 70 | } 71 | 72 | float DHT::readHumidity(bool force) { 73 | float f = NAN; 74 | if (read()) { 75 | switch (_type) { 76 | case DHT11: 77 | f = data[0]; 78 | break; 79 | case DHT22: 80 | case DHT21: 81 | f = data[0]; 82 | f *= 256; 83 | f += data[1]; 84 | f *= 0.1; 85 | break; 86 | } 87 | } 88 | return f; 89 | } 90 | 91 | //boolean isFahrenheit: True == Fahrenheit; False == Celcius 92 | float DHT::computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit) { 93 | // Using both Rothfusz and Steadman's equations 94 | // http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml 95 | float hi; 96 | 97 | if (!isFahrenheit) 98 | temperature = convertCtoF(temperature); 99 | 100 | hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (percentHumidity * 0.094)); 101 | 102 | if (hi > 79) { 103 | hi = -42.379 + 104 | 2.04901523 * temperature + 105 | 10.14333127 * percentHumidity + 106 | -0.22475541 * temperature*percentHumidity + 107 | -0.00683783 * pow(temperature, 2) + 108 | -0.05481717 * pow(percentHumidity, 2) + 109 | 0.00122874 * pow(temperature, 2) * percentHumidity + 110 | 0.00085282 * temperature*pow(percentHumidity, 2) + 111 | -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2); 112 | 113 | if((percentHumidity < 13) && (temperature >= 80.0) && (temperature <= 112.0)) 114 | hi -= ((13.0 - percentHumidity) * 0.25) * sqrt((17.0 - abs(temperature - 95.0)) * 0.05882); 115 | 116 | else if((percentHumidity > 85.0) && (temperature >= 80.0) && (temperature <= 87.0)) 117 | hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2); 118 | } 119 | 120 | return isFahrenheit ? hi : convertFtoC(hi); 121 | } 122 | 123 | boolean DHT::read(bool force) { 124 | // Check if sensor was read less than two seconds ago and return early 125 | // to use last reading. 126 | uint32_t currenttime = millis(); 127 | if (!force && ((currenttime - _lastreadtime) < 2000)) { 128 | return _lastresult; // return last correct measurement 129 | } 130 | _lastreadtime = currenttime; 131 | 132 | // Reset 40 bits of received data to zero. 133 | data[0] = data[1] = data[2] = data[3] = data[4] = 0; 134 | 135 | // Send start signal. See DHT datasheet for full signal diagram: 136 | // http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf 137 | 138 | // Go into high impedence state to let pull-up raise data line level and 139 | // start the reading process. 140 | digitalWrite(_pin, HIGH); 141 | delay(250); 142 | 143 | // First set data line low for 20 milliseconds. 144 | pinMode(_pin, OUTPUT); 145 | digitalWrite(_pin, LOW); 146 | delay(20); 147 | 148 | uint32_t cycles[80]; 149 | { 150 | // Turn off interrupts temporarily because the next sections are timing critical 151 | // and we don't want any interruptions. 152 | InterruptLock lock; 153 | 154 | // End the start signal by setting data line high for 40 microseconds. 155 | digitalWrite(_pin, HIGH); 156 | delayMicroseconds(40); 157 | 158 | // Now start reading the data line to get the value from the DHT sensor. 159 | pinMode(_pin, INPUT_PULLUP); 160 | delayMicroseconds(10); // Delay a bit to let sensor pull data line low. 161 | 162 | // First expect a low signal for ~80 microseconds followed by a high signal 163 | // for ~80 microseconds again. 164 | if (expectPulse(LOW) == 0) { 165 | DEBUG_PRINTLN(F("Timeout waiting for start signal low pulse.")); 166 | _lastresult = false; 167 | return _lastresult; 168 | } 169 | if (expectPulse(HIGH) == 0) { 170 | DEBUG_PRINTLN(F("Timeout waiting for start signal high pulse.")); 171 | _lastresult = false; 172 | return _lastresult; 173 | } 174 | 175 | // Now read the 40 bits sent by the sensor. Each bit is sent as a 50 176 | // microsecond low pulse followed by a variable length high pulse. If the 177 | // high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds 178 | // then it's a 1. We measure the cycle count of the initial 50us low pulse 179 | // and use that to compare to the cycle count of the high pulse to determine 180 | // if the bit is a 0 (high state cycle count < low state cycle count), or a 181 | // 1 (high state cycle count > low state cycle count). Note that for speed all 182 | // the pulses are read into a array and then examined in a later step. 183 | for (int i=0; i<80; i+=2) { 184 | cycles[i] = expectPulse(LOW); 185 | cycles[i+1] = expectPulse(HIGH); 186 | } 187 | } // Timing critical code is now complete. 188 | 189 | // Inspect pulses and determine which ones are 0 (high state cycle count < low 190 | // state cycle count), or 1 (high state cycle count > low state cycle count). 191 | for (int i=0; i<40; ++i) { 192 | uint32_t lowCycles = cycles[2*i]; 193 | uint32_t highCycles = cycles[2*i+1]; 194 | if ((lowCycles == 0) || (highCycles == 0)) { 195 | DEBUG_PRINTLN(F("Timeout waiting for pulse.")); 196 | _lastresult = false; 197 | return _lastresult; 198 | } 199 | data[i/8] <<= 1; 200 | // Now compare the low and high cycle times to see if the bit is a 0 or 1. 201 | if (highCycles > lowCycles) { 202 | // High cycles are greater than 50us low cycle count, must be a 1. 203 | data[i/8] |= 1; 204 | } 205 | // Else high cycles are less than (or equal to, a weird case) the 50us low 206 | // cycle count so this must be a zero. Nothing needs to be changed in the 207 | // stored data. 208 | } 209 | 210 | DEBUG_PRINTLN(F("Received:")); 211 | DEBUG_PRINT(data[0], HEX); DEBUG_PRINT(F(", ")); 212 | DEBUG_PRINT(data[1], HEX); DEBUG_PRINT(F(", ")); 213 | DEBUG_PRINT(data[2], HEX); DEBUG_PRINT(F(", ")); 214 | DEBUG_PRINT(data[3], HEX); DEBUG_PRINT(F(", ")); 215 | DEBUG_PRINT(data[4], HEX); DEBUG_PRINT(F(" =? ")); 216 | DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0xFF, HEX); 217 | 218 | // Check we read 40 bits and that the checksum matches. 219 | if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) { 220 | _lastresult = true; 221 | return _lastresult; 222 | } 223 | else { 224 | DEBUG_PRINTLN(F("Checksum failure!")); 225 | _lastresult = false; 226 | return _lastresult; 227 | } 228 | } 229 | 230 | // Expect the signal line to be at the specified level for a period of time and 231 | // return a count of loop cycles spent at that level (this cycle count can be 232 | // used to compare the relative time of two pulses). If more than a millisecond 233 | // ellapses without the level changing then the call fails with a 0 response. 234 | // This is adapted from Arduino's pulseInLong function (which is only available 235 | // in the very latest IDE versions): 236 | // https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c 237 | uint32_t DHT::expectPulse(bool level) { 238 | uint32_t count = 0; 239 | // On AVR platforms use direct GPIO port access as it's much faster and better 240 | // for catching pulses that are 10's of microseconds in length: 241 | #ifdef __AVR 242 | uint8_t portState = level ? _bit : 0; 243 | while ((*portInputRegister(_port) & _bit) == portState) { 244 | if (count++ >= _maxcycles) { 245 | return 0; // Exceeded timeout, fail. 246 | } 247 | } 248 | // Otherwise fall back to using digitalRead (this seems to be necessary on ESP8266 249 | // right now, perhaps bugs in direct port access functions?). 250 | #else 251 | while (digitalRead(_pin) == level) { 252 | if (count++ >= _maxcycles) { 253 | return 0; // Exceeded timeout, fail. 254 | } 255 | } 256 | #endif 257 | 258 | return count; 259 | } 260 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 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 | #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(...) { DEBUG_PRINTER.print(__VA_ARGS__); } 48 | #define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); } 49 | #define DEBUG_PRINTBUFFER(buffer, len) { printBuffer(buffer, len); } 50 | #else 51 | #define DEBUG_PRINT(...) {} 52 | #define DEBUG_PRINTLN(...) {} 53 | #define DEBUG_PRINTBUFFER(buffer, len) {} 54 | #endif 55 | 56 | #ifdef MQTT_ERROR 57 | #define ERROR_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); } 58 | #define ERROR_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); } 59 | #define ERROR_PRINTBUFFER(buffer, len) { printBuffer(buffer, len); } 60 | #else 61 | #define ERROR_PRINT(...) {} 62 | #define ERROR_PRINTLN(...) {} 63 | #define ERROR_PRINTBUFFER(buffer, len) {} 64 | #endif 65 | 66 | // Use 3 (MQTT 3.0) or 4 (MQTT 3.1.1) 67 | #define MQTT_PROTOCOL_LEVEL 4 68 | 69 | #define MQTT_CTRL_CONNECT 0x1 70 | #define MQTT_CTRL_CONNECTACK 0x2 71 | #define MQTT_CTRL_PUBLISH 0x3 72 | #define MQTT_CTRL_PUBACK 0x4 73 | #define MQTT_CTRL_PUBREC 0x5 74 | #define MQTT_CTRL_PUBREL 0x6 75 | #define MQTT_CTRL_PUBCOMP 0x7 76 | #define MQTT_CTRL_SUBSCRIBE 0x8 77 | #define MQTT_CTRL_SUBACK 0x9 78 | #define MQTT_CTRL_UNSUBSCRIBE 0xA 79 | #define MQTT_CTRL_UNSUBACK 0xB 80 | #define MQTT_CTRL_PINGREQ 0xC 81 | #define MQTT_CTRL_PINGRESP 0xD 82 | #define MQTT_CTRL_DISCONNECT 0xE 83 | 84 | #define MQTT_QOS_1 0x1 85 | #define MQTT_QOS_0 0x0 86 | 87 | #define CONNECT_TIMEOUT_MS 6000 88 | #define PUBLISH_TIMEOUT_MS 500 89 | #define PING_TIMEOUT_MS 500 90 | #define SUBACK_TIMEOUT_MS 500 91 | 92 | // Adjust as necessary, in seconds. Default to 5 minutes. 93 | #define MQTT_CONN_KEEPALIVE 300 94 | 95 | // Largest full packet we're able to send. 96 | // Need to be able to store at least ~90 chars for a connect packet with full 97 | // 23 char client ID. 98 | #define MAXBUFFERSIZE (150) 99 | 100 | #define MQTT_CONN_USERNAMEFLAG 0x80 101 | #define MQTT_CONN_PASSWORDFLAG 0x40 102 | #define MQTT_CONN_WILLRETAIN 0x20 103 | #define MQTT_CONN_WILLQOS_1 0x08 104 | #define MQTT_CONN_WILLQOS_2 0x18 105 | #define MQTT_CONN_WILLFLAG 0x04 106 | #define MQTT_CONN_CLEANSESSION 0x02 107 | 108 | // how many subscriptions we want to be able to track 109 | #define MAXSUBSCRIPTIONS 10 110 | 111 | // how much data we save in a subscription object 112 | // eg max-subscription-payload-size 113 | #if defined (__AVR_ATmega32U4__) || defined(__AVR_ATmega328P__) 114 | #define SUBSCRIPTIONDATALEN 20 115 | #else 116 | #define SUBSCRIPTIONDATALEN 100 117 | #endif 118 | 119 | class AdafruitIO_MQTT; // forward decl 120 | 121 | //Function pointer that returns an int 122 | typedef void (*SubscribeCallbackUInt32Type)(uint32_t); 123 | // returns a double 124 | typedef void (*SubscribeCallbackDoubleType)(double); 125 | // returns a chunk of raw data 126 | typedef void (*SubscribeCallbackBufferType)(char *str, uint16_t len); 127 | // returns an io data wrapper instance 128 | typedef void (AdafruitIO_MQTT::*SubscribeCallbackIOType)(char *str, uint16_t len); 129 | 130 | extern void printBuffer(uint8_t *buffer, uint16_t len); 131 | 132 | class Adafruit_MQTT_Subscribe; // forward decl 133 | 134 | class Adafruit_MQTT { 135 | public: 136 | Adafruit_MQTT(const char *server, 137 | uint16_t port, 138 | const char *cid, 139 | const char *user, 140 | const char *pass); 141 | 142 | Adafruit_MQTT(const char *server, 143 | uint16_t port, 144 | const char *user = "", 145 | const char *pass = ""); 146 | virtual ~Adafruit_MQTT() {} 147 | 148 | // Connect to the MQTT server. Returns 0 on success, otherwise an error code 149 | // that indicates something went wrong: 150 | // -1 = Error connecting to server 151 | // 1 = Wrong protocol 152 | // 2 = ID rejected 153 | // 3 = Server unavailable 154 | // 4 = Bad username or password 155 | // 5 = Not authenticated 156 | // 6 = Failed to subscribe 157 | // Use connectErrorString() to get a printable string version of the 158 | // error. 159 | int8_t connect(); 160 | int8_t connect(const char *user, const char *pass); 161 | 162 | // Return a printable string version of the error code returned by 163 | // connect(). This returns a __FlashStringHelper*, which points to a 164 | // string stored in flash, but can be directly passed to e.g. 165 | // Serial.println without any further processing. 166 | const __FlashStringHelper* connectErrorString(int8_t code); 167 | 168 | // Sends MQTT disconnect packet and calls disconnectServer() 169 | bool disconnect(); 170 | 171 | // Return true if connected to the MQTT server, otherwise false. 172 | virtual bool connected() = 0; // Subclasses need to fill this in! 173 | 174 | // Set MQTT last will topic, payload, QOS, and retain. This needs 175 | // to be called before connect() because it is sent as part of the 176 | // connect control packet. 177 | bool will(const char *topic, const char *payload, uint8_t qos = 0, uint8_t retain = 0); 178 | 179 | // Publish a message to a topic using the specified QoS level. Returns true 180 | // if the message was published, false otherwise. 181 | bool publish(const char *topic, const char *payload, uint8_t qos = 0); 182 | bool publish(const char *topic, uint8_t *payload, uint16_t bLen, uint8_t qos = 0); 183 | 184 | // Add a subscription to receive messages for a topic. Returns true if the 185 | // subscription could be added or was already present, false otherwise. 186 | // Must be called before connect(), subscribing after the connection 187 | // is made is not currently supported. 188 | bool subscribe(Adafruit_MQTT_Subscribe *sub); 189 | 190 | // Unsubscribe from a previously subscribed MQTT topic. 191 | bool unsubscribe(Adafruit_MQTT_Subscribe *sub); 192 | 193 | // Check if any subscriptions have new messages. Will return a reference to 194 | // an Adafruit_MQTT_Subscribe object which has a new message. Should be called 195 | // in the sketch's loop function to ensure new messages are recevied. Note 196 | // that subscribe should be called first for each topic that receives messages! 197 | Adafruit_MQTT_Subscribe *readSubscription(int16_t timeout=0); 198 | 199 | void processPackets(int16_t timeout); 200 | 201 | // Ping the server to ensure the connection is still alive. 202 | bool ping(uint8_t n = 1); 203 | 204 | protected: 205 | // Interface that subclasses need to implement: 206 | 207 | // Connect to the server and return true if successful, false otherwise. 208 | virtual bool connectServer() = 0; 209 | 210 | // Disconnect from the MQTT server. Returns true if disconnected, false otherwise. 211 | virtual bool disconnectServer() = 0; // Subclasses need to fill this in! 212 | 213 | // Send data to the server specified by the buffer and length of data. 214 | virtual bool sendPacket(uint8_t *buffer, uint16_t len) = 0; 215 | 216 | // Read MQTT packet from the server. Will read up to maxlen bytes and store 217 | // the data in the provided buffer. Waits up to the specified timeout (in 218 | // milliseconds) for data to be available. 219 | virtual uint16_t readPacket(uint8_t *buffer, uint16_t maxlen, int16_t timeout) = 0; 220 | 221 | // Read a full packet, keeping note of the correct length 222 | uint16_t readFullPacket(uint8_t *buffer, uint16_t maxsize, uint16_t timeout); 223 | // Properly process packets until you get to one you want 224 | uint16_t processPacketsUntil(uint8_t *buffer, uint8_t waitforpackettype, uint16_t timeout); 225 | 226 | // Shared state that subclasses can use: 227 | const char *servername; 228 | int16_t portnum; 229 | const char *clientid; 230 | const char *username; 231 | const char *password; 232 | const char *will_topic; 233 | const char *will_payload; 234 | uint8_t will_qos; 235 | uint8_t will_retain; 236 | uint8_t buffer[MAXBUFFERSIZE]; // one buffer, used for all incoming/outgoing 237 | uint16_t packet_id_counter; 238 | 239 | private: 240 | Adafruit_MQTT_Subscribe *subscriptions[MAXSUBSCRIPTIONS]; 241 | 242 | void flushIncoming(uint16_t timeout); 243 | 244 | // Functions to generate MQTT packets. 245 | uint8_t connectPacket(uint8_t *packet); 246 | uint8_t disconnectPacket(uint8_t *packet); 247 | uint16_t publishPacket(uint8_t *packet, const char *topic, uint8_t *payload, uint16_t bLen, uint8_t qos); 248 | uint8_t subscribePacket(uint8_t *packet, const char *topic, uint8_t qos); 249 | uint8_t unsubscribePacket(uint8_t *packet, const char *topic); 250 | uint8_t pingPacket(uint8_t *packet); 251 | uint8_t pubackPacket(uint8_t *packet, uint16_t packetid); 252 | }; 253 | 254 | 255 | class Adafruit_MQTT_Publish { 256 | public: 257 | Adafruit_MQTT_Publish(Adafruit_MQTT *mqttserver, const char *feed, uint8_t qos = 0); 258 | 259 | bool publish(const char *s); 260 | bool publish(double f, uint8_t precision=2); // Precision controls the minimum number of digits after decimal. 261 | // This might be ignored and a higher precision value sent. 262 | bool publish(int32_t i); 263 | bool publish(uint32_t i); 264 | bool publish(uint8_t *b, uint16_t bLen); 265 | 266 | 267 | private: 268 | Adafruit_MQTT *mqtt; 269 | const char *topic; 270 | uint8_t qos; 271 | }; 272 | 273 | class Adafruit_MQTT_Subscribe { 274 | public: 275 | Adafruit_MQTT_Subscribe(Adafruit_MQTT *mqttserver, const char *feedname, uint8_t q=0); 276 | 277 | void setCallback(SubscribeCallbackUInt32Type callb); 278 | void setCallback(SubscribeCallbackDoubleType callb); 279 | void setCallback(SubscribeCallbackBufferType callb); 280 | void setCallback(AdafruitIO_MQTT *io, SubscribeCallbackIOType callb); 281 | void removeCallback(void); 282 | 283 | const char *topic; 284 | uint8_t qos; 285 | 286 | uint8_t lastread[SUBSCRIPTIONDATALEN]; 287 | // Number valid bytes in lastread. Limited to SUBSCRIPTIONDATALEN-1 to 288 | // ensure nul terminating lastread. 289 | uint16_t datalen; 290 | 291 | SubscribeCallbackUInt32Type callback_uint32t; 292 | SubscribeCallbackDoubleType callback_double; 293 | SubscribeCallbackBufferType callback_buffer; 294 | SubscribeCallbackIOType callback_io; 295 | 296 | AdafruitIO_MQTT *io_mqtt; 297 | 298 | private: 299 | Adafruit_MQTT *mqtt; 300 | }; 301 | 302 | 303 | #endif 304 | -------------------------------------------------------------------------------- /Adafruit_MQTT_Library-master/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 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 | #include "Adafruit_MQTT.h" 23 | 24 | #if defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) 25 | static char *dtostrf (double val, signed char width, unsigned char prec, char *sout) { 26 | char fmt[20]; 27 | sprintf(fmt, "%%%d.%df", width, prec); 28 | sprintf(sout, fmt, val); 29 | return sout; 30 | } 31 | #endif 32 | 33 | #if defined(ESP8266) 34 | int strncasecmp(const char * str1, const char * str2, int len) { 35 | int d = 0; 36 | while(len--) { 37 | int c1 = tolower(*str1++); 38 | int c2 = tolower(*str2++); 39 | if(((d = c1 - c2) != 0) || (c2 == '\0')) { 40 | return d; 41 | } 42 | } 43 | return 0; 44 | } 45 | #endif 46 | 47 | 48 | void printBuffer(uint8_t *buffer, uint16_t len) { 49 | DEBUG_PRINTER.print('\t'); 50 | for (uint16_t i=0; i> 8; p++; 71 | p[0] = len & 0xFF; p++; 72 | memmove(p, s, len); 73 | return p+len; 74 | } 75 | */ 76 | 77 | static uint8_t *stringprint(uint8_t *p, const char *s, uint16_t maxlen=0) { 78 | // If maxlen is specified (has a non-zero value) then use it as the maximum 79 | // length of the source string to write to the buffer. Otherwise write 80 | // the entire source string. 81 | uint16_t len = strlen(s); 82 | if (maxlen > 0 && len > maxlen) { 83 | len = maxlen; 84 | } 85 | /* 86 | for (uint8_t i=0; i> 8; p++; 91 | p[0] = len & 0xFF; p++; 92 | strncpy((char *)p, s, len); 93 | return p+len; 94 | } 95 | 96 | 97 | // Adafruit_MQTT Definition //////////////////////////////////////////////////// 98 | 99 | Adafruit_MQTT::Adafruit_MQTT(const char *server, 100 | uint16_t port, 101 | const char *cid, 102 | const char *user, 103 | const char *pass) { 104 | servername = server; 105 | portnum = port; 106 | clientid = cid; 107 | username = user; 108 | password = pass; 109 | 110 | // reset subscriptions 111 | for (uint8_t i=0; itopic, subscriptions[i]->qos); 177 | if (!sendPacket(buffer, len)) 178 | return -1; 179 | 180 | if(MQTT_PROTOCOL_LEVEL < 3) // older versions didn't suback 181 | break; 182 | 183 | // Check for SUBACK if using MQTT 3.1.1 or higher 184 | // TODO: The Server is permitted to start sending PUBLISH packets matching the 185 | // Subscription before the Server sends the SUBACK Packet. (will really need to use callbacks - ada) 186 | 187 | //Serial.println("\t**looking for suback"); 188 | if (processPacketsUntil(buffer, MQTT_CTRL_SUBACK, SUBACK_TIMEOUT_MS)) { 189 | success = true; 190 | break; 191 | } 192 | //Serial.println("\t**failed, retrying!"); 193 | } 194 | if (! success) return -2; // failed to sub for some reason 195 | } 196 | 197 | return 0; 198 | } 199 | 200 | int8_t Adafruit_MQTT::connect(const char *user, const char *pass) 201 | { 202 | username = user; 203 | password = pass; 204 | return connect(); 205 | } 206 | 207 | uint16_t Adafruit_MQTT::processPacketsUntil(uint8_t *buffer, uint8_t waitforpackettype, uint16_t timeout) { 208 | uint16_t len; 209 | while (len = readFullPacket(buffer, MAXBUFFERSIZE, timeout)) { 210 | 211 | //DEBUG_PRINT("Packet read size: "); DEBUG_PRINTLN(len); 212 | // TODO: add subscription reading & call back processing here 213 | 214 | if ((buffer[0] >> 4) == waitforpackettype) { 215 | //DEBUG_PRINTLN(F("Found right packet")); 216 | return len; 217 | } else { 218 | ERROR_PRINTLN(F("Dropped a packet")); 219 | } 220 | } 221 | return 0; 222 | } 223 | 224 | uint16_t Adafruit_MQTT::readFullPacket(uint8_t *buffer, uint16_t maxsize, uint16_t timeout) { 225 | // will read a packet and Do The Right Thing with length 226 | uint8_t *pbuff = buffer; 227 | 228 | uint8_t rlen; 229 | 230 | // read the packet type: 231 | rlen = readPacket(pbuff, 1, timeout); 232 | if (rlen != 1) return 0; 233 | 234 | DEBUG_PRINT(F("Packet Type:\t")); DEBUG_PRINTBUFFER(pbuff, rlen); 235 | pbuff++; 236 | 237 | uint32_t value = 0; 238 | uint32_t multiplier = 1; 239 | uint8_t encodedByte; 240 | 241 | do { 242 | rlen = readPacket(pbuff, 1, timeout); 243 | if (rlen != 1) return 0; 244 | encodedByte = pbuff[0]; // save the last read val 245 | pbuff++; // get ready for reading the next byte 246 | uint32_t intermediate = encodedByte & 0x7F; 247 | intermediate *= multiplier; 248 | value += intermediate; 249 | multiplier *= 128; 250 | if (multiplier > (128UL*128UL*128UL)) { 251 | DEBUG_PRINT(F("Malformed packet len\n")); 252 | return 0; 253 | } 254 | } while (encodedByte & 0x80); 255 | 256 | DEBUG_PRINT(F("Packet Length:\t")); DEBUG_PRINTLN(value); 257 | 258 | if (value > (maxsize - (pbuff-buffer) - 1)) { 259 | DEBUG_PRINTLN(F("Packet too big for buffer")); 260 | rlen = readPacket(pbuff, (maxsize - (pbuff-buffer) - 1), timeout); 261 | } else { 262 | rlen = readPacket(pbuff, value, timeout); 263 | } 264 | //DEBUG_PRINT(F("Remaining packet:\t")); DEBUG_PRINTBUFFER(pbuff, rlen); 265 | 266 | return ((pbuff - buffer)+rlen); 267 | } 268 | 269 | const __FlashStringHelper* Adafruit_MQTT::connectErrorString(int8_t code) { 270 | switch (code) { 271 | case 1: return F("The Server does not support the level of the MQTT protocol requested"); 272 | case 2: return F("The Client identifier is correct UTF-8 but not allowed by the Server"); 273 | case 3: return F("The MQTT service is unavailable"); 274 | case 4: return F("The data in the user name or password is malformed"); 275 | case 5: return F("Not authorized to connect"); 276 | case 6: return F("Exceeded reconnect rate limit. Please try again later."); 277 | case 7: return F("You have been banned from connecting. Please contact the MQTT server administrator for more details."); 278 | case -1: return F("Connection failed"); 279 | case -2: return F("Failed to subscribe"); 280 | default: return F("Unknown error"); 281 | } 282 | } 283 | 284 | bool Adafruit_MQTT::disconnect() { 285 | 286 | // Construct and send disconnect packet. 287 | uint8_t len = disconnectPacket(buffer); 288 | if (! sendPacket(buffer, len)) 289 | DEBUG_PRINTLN(F("Unable to send disconnect packet")); 290 | 291 | return disconnectServer(); 292 | 293 | } 294 | 295 | 296 | bool Adafruit_MQTT::publish(const char *topic, const char *data, uint8_t qos) { 297 | return publish(topic, (uint8_t*)(data), strlen(data), qos); 298 | } 299 | 300 | bool Adafruit_MQTT::publish(const char *topic, uint8_t *data, uint16_t bLen, uint8_t qos) { 301 | // Construct and send publish packet. 302 | uint16_t len = publishPacket(buffer, topic, data, bLen, qos); 303 | if (!sendPacket(buffer, len)) 304 | return false; 305 | 306 | // If QOS level is high enough verify the response packet. 307 | if (qos > 0) { 308 | len = readFullPacket(buffer, MAXBUFFERSIZE, PUBLISH_TIMEOUT_MS); 309 | DEBUG_PRINT(F("Publish QOS1+ reply:\t")); 310 | DEBUG_PRINTBUFFER(buffer, len); 311 | if (len != 4) 312 | return false; 313 | if ((buffer[0] >> 4) != MQTT_CTRL_PUBACK) 314 | return false; 315 | uint16_t packnum = buffer[2]; 316 | packnum <<= 8; 317 | packnum |= buffer[3]; 318 | 319 | // we increment the packet_id_counter right after publishing so inc here too to match 320 | packnum++; 321 | if (packnum != packet_id_counter) 322 | return false; 323 | } 324 | 325 | return true; 326 | } 327 | 328 | bool Adafruit_MQTT::will(const char *topic, const char *payload, uint8_t qos, uint8_t retain) { 329 | 330 | if (connected()) { 331 | DEBUG_PRINT(F("Will defined after connect")); 332 | return false; 333 | } 334 | 335 | will_topic = topic; 336 | will_payload = payload; 337 | will_qos = qos; 338 | will_retain = retain; 339 | 340 | return true; 341 | 342 | } 343 | 344 | bool Adafruit_MQTT::subscribe(Adafruit_MQTT_Subscribe *sub) { 345 | uint8_t i; 346 | // see if we are already subscribed 347 | for (i=0; itopic); 379 | 380 | // sending unsubscribe failed 381 | if (! sendPacket(buffer, len)) 382 | return false; 383 | 384 | // if QoS for this subscription is 1 or 2, we need 385 | // to wait for the unsuback to confirm unsubscription 386 | if(subscriptions[i]->qos > 0 && MQTT_PROTOCOL_LEVEL > 3) { 387 | 388 | // wait for UNSUBACK 389 | len = readFullPacket(buffer, MAXBUFFERSIZE, CONNECT_TIMEOUT_MS); 390 | DEBUG_PRINT(F("UNSUBACK:\t")); 391 | DEBUG_PRINTBUFFER(buffer, len); 392 | 393 | if ((len != 5) || (buffer[0] != (MQTT_CTRL_UNSUBACK << 4))) { 394 | return false; // failure to unsubscribe 395 | } 396 | } 397 | 398 | subscriptions[i] = 0; 399 | return true; 400 | } 401 | 402 | } 403 | 404 | // subscription not found, so we are unsubscribed 405 | return true; 406 | 407 | } 408 | 409 | void Adafruit_MQTT::processPackets(int16_t timeout) { 410 | uint16_t len; 411 | 412 | uint32_t elapsed = 0, endtime, starttime = millis(); 413 | 414 | while (elapsed < (uint32_t)timeout) { 415 | Adafruit_MQTT_Subscribe *sub = readSubscription(timeout - elapsed); 416 | if (sub) { 417 | //Serial.println("**** sub packet received"); 418 | if (sub->callback_uint32t != NULL) { 419 | // huh lets do the callback in integer mode 420 | uint32_t data = 0; 421 | data = atoi((char *)sub->lastread); 422 | //Serial.print("*** calling int callback with : "); Serial.println(data); 423 | sub->callback_uint32t(data); 424 | } 425 | else if (sub->callback_double != NULL) { 426 | // huh lets do the callback in doublefloat mode 427 | double data = 0; 428 | data = atof((char *)sub->lastread); 429 | //Serial.print("*** calling double callback with : "); Serial.println(data); 430 | sub->callback_double(data); 431 | } 432 | else if (sub->callback_buffer != NULL) { 433 | // huh lets do the callback in buffer mode 434 | //Serial.print("*** calling buffer callback with : "); Serial.println((char *)sub->lastread); 435 | sub->callback_buffer((char *)sub->lastread, sub->datalen); 436 | } 437 | else if (sub->callback_io != NULL) { 438 | // huh lets do the callback in io mode 439 | //Serial.print("*** calling io instance callback with : "); Serial.println((char *)sub->lastread); 440 | ((sub->io_mqtt)->*(sub->callback_io))((char *)sub->lastread, sub->datalen); 441 | } 442 | } 443 | 444 | // keep track over elapsed time 445 | endtime = millis(); 446 | if (endtime < starttime) { 447 | starttime = endtime; // looped around!") 448 | } 449 | elapsed += (endtime - starttime); 450 | } 451 | } 452 | 453 | Adafruit_MQTT_Subscribe *Adafruit_MQTT::readSubscription(int16_t timeout) { 454 | uint16_t i, topiclen, datalen; 455 | 456 | // Check if data is available to read. 457 | uint16_t len = readFullPacket(buffer, MAXBUFFERSIZE, timeout); // return one full packet 458 | if (!len) 459 | return NULL; // No data available, just quit. 460 | DEBUG_PRINT("Packet len: "); DEBUG_PRINTLN(len); 461 | DEBUG_PRINTBUFFER(buffer, len); 462 | 463 | // Parse out length of packet. 464 | topiclen = buffer[3]; 465 | DEBUG_PRINT(F("Looking for subscription len ")); DEBUG_PRINTLN(topiclen); 466 | 467 | // Find subscription associated with this packet. 468 | for (i=0; itopic) != topiclen) 473 | continue; 474 | // Stop if the subscription topic matches the received topic. Be careful 475 | // to make comparison case insensitive. 476 | if (strncasecmp((char*)buffer+4, subscriptions[i]->topic, topiclen) == 0) { 477 | DEBUG_PRINT(F("Found sub #")); DEBUG_PRINTLN(i); 478 | break; 479 | } 480 | } 481 | } 482 | if (i==MAXSUBSCRIPTIONS) return NULL; // matching sub not found ??? 483 | 484 | uint8_t packet_id_len = 0; 485 | uint16_t packetid; 486 | // Check if it is QoS 1, TODO: we dont support QoS 2 487 | if ((buffer[0] & 0x6) == 0x2) { 488 | packet_id_len = 2; 489 | packetid = buffer[topiclen+4]; 490 | packetid <<= 8; 491 | packetid |= buffer[topiclen+5]; 492 | } 493 | 494 | // zero out the old data 495 | memset(subscriptions[i]->lastread, 0, SUBSCRIPTIONDATALEN); 496 | 497 | datalen = len - topiclen - packet_id_len - 4; 498 | if (datalen > SUBSCRIPTIONDATALEN) { 499 | datalen = SUBSCRIPTIONDATALEN-1; // cut it off 500 | } 501 | // extract out just the data, into the subscription object itself 502 | memmove(subscriptions[i]->lastread, buffer+4+topiclen+packet_id_len, datalen); 503 | subscriptions[i]->datalen = datalen; 504 | DEBUG_PRINT(F("Data len: ")); DEBUG_PRINTLN(datalen); 505 | DEBUG_PRINT(F("Data: ")); DEBUG_PRINTLN((char *)subscriptions[i]->lastread); 506 | 507 | if ((MQTT_PROTOCOL_LEVEL > 3) &&(buffer[0] & 0x6) == 0x2) { 508 | uint8_t ackpacket[4]; 509 | 510 | // Construct and send puback packet. 511 | uint8_t len = pubackPacket(ackpacket, packetid); 512 | if (!sendPacket(ackpacket, len)) 513 | DEBUG_PRINT(F("Failed")); 514 | } 515 | 516 | // return the valid matching subscription 517 | return subscriptions[i]; 518 | } 519 | 520 | void Adafruit_MQTT::flushIncoming(uint16_t timeout) { 521 | // flush input! 522 | DEBUG_PRINTLN(F("Flushing input buffer")); 523 | while (readPacket(buffer, MAXBUFFERSIZE, timeout)); 524 | } 525 | 526 | bool Adafruit_MQTT::ping(uint8_t num) { 527 | //flushIncoming(100); 528 | 529 | while (num--) { 530 | // Construct and send ping packet. 531 | uint8_t len = pingPacket(buffer); 532 | if (!sendPacket(buffer, len)) 533 | continue; 534 | 535 | // Process ping reply. 536 | len = processPacketsUntil(buffer, MQTT_CTRL_PINGRESP, PING_TIMEOUT_MS); 537 | if (buffer[0] == (MQTT_CTRL_PINGRESP << 4)) 538 | return true; 539 | } 540 | 541 | return false; 542 | } 543 | 544 | // Packet Generation Functions ///////////////////////////////////////////////// 545 | 546 | // The current MQTT spec is 3.1.1 and available here: 547 | // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028 548 | // However this connect packet and code follows the MQTT 3.1 spec here (some 549 | // small differences in the protocol): 550 | // http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html#connect 551 | uint8_t Adafruit_MQTT::connectPacket(uint8_t *packet) { 552 | uint8_t *p = packet; 553 | uint16_t len; 554 | 555 | // fixed header, connection messsage no flags 556 | p[0] = (MQTT_CTRL_CONNECT << 4) | 0x0; 557 | p+=2; 558 | // fill in packet[1] last 559 | 560 | #if MQTT_PROTOCOL_LEVEL == 3 561 | p = stringprint(p, "MQIsdp"); 562 | #elif MQTT_PROTOCOL_LEVEL == 4 563 | p = stringprint(p, "MQTT"); 564 | #else 565 | #error "MQTT level not supported" 566 | #endif 567 | 568 | p[0] = MQTT_PROTOCOL_LEVEL; 569 | p++; 570 | 571 | // always clean the session 572 | p[0] = MQTT_CONN_CLEANSESSION; 573 | 574 | // set the will flags if needed 575 | if (will_topic && pgm_read_byte(will_topic) != 0) { 576 | 577 | p[0] |= MQTT_CONN_WILLFLAG; 578 | 579 | if(will_qos == 1) 580 | p[0] |= MQTT_CONN_WILLQOS_1; 581 | else if(will_qos == 2) 582 | p[0] |= MQTT_CONN_WILLQOS_2; 583 | 584 | if(will_retain == 1) 585 | p[0] |= MQTT_CONN_WILLRETAIN; 586 | 587 | } 588 | 589 | if (pgm_read_byte(username) != 0) 590 | p[0] |= MQTT_CONN_USERNAMEFLAG; 591 | if (pgm_read_byte(password) != 0) 592 | p[0] |= MQTT_CONN_PASSWORDFLAG; 593 | p++; 594 | 595 | p[0] = MQTT_CONN_KEEPALIVE >> 8; 596 | p++; 597 | p[0] = MQTT_CONN_KEEPALIVE & 0xFF; 598 | p++; 599 | 600 | if(MQTT_PROTOCOL_LEVEL == 3) { 601 | p = stringprint(p, clientid, 23); // Limit client ID to first 23 characters. 602 | } else { 603 | if (pgm_read_byte(clientid) != 0) { 604 | p = stringprint(p, clientid); 605 | } else { 606 | p[0] = 0x0; 607 | p++; 608 | p[0] = 0x0; 609 | p++; 610 | DEBUG_PRINTLN(F("SERVER GENERATING CLIENT ID")); 611 | } 612 | } 613 | 614 | if (will_topic && pgm_read_byte(will_topic) != 0) { 615 | p = stringprint(p, will_topic); 616 | p = stringprint(p, will_payload); 617 | } 618 | 619 | if (pgm_read_byte(username) != 0) { 620 | p = stringprint(p, username); 621 | } 622 | if (pgm_read_byte(password) != 0) { 623 | p = stringprint(p, password); 624 | } 625 | 626 | len = p - packet; 627 | 628 | packet[1] = len-2; // don't include the 2 bytes of fixed header data 629 | DEBUG_PRINTLN(F("MQTT connect packet:")); 630 | DEBUG_PRINTBUFFER(buffer, len); 631 | return len; 632 | } 633 | 634 | 635 | // as per http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718040 636 | uint16_t Adafruit_MQTT::publishPacket(uint8_t *packet, const char *topic, 637 | uint8_t *data, uint16_t bLen, uint8_t qos) { 638 | uint8_t *p = packet; 639 | uint16_t len=0; 640 | 641 | // calc length of non-header data 642 | len += 2; // two bytes to set the topic size 643 | len += strlen(topic); // topic length 644 | if(qos > 0) { 645 | len += 2; // qos packet id 646 | } 647 | len += bLen; // payload length 648 | 649 | // Now you can start generating the packet! 650 | p[0] = MQTT_CTRL_PUBLISH << 4 | qos << 1; 651 | p++; 652 | 653 | // fill in packet[1] last 654 | do { 655 | uint8_t encodedByte = len % 128; 656 | len /= 128; 657 | // if there are more data to encode, set the top bit of this byte 658 | if ( len > 0 ) { 659 | encodedByte |= 0x80; 660 | } 661 | p[0] = encodedByte; 662 | p++; 663 | } while ( len > 0 ); 664 | 665 | // topic comes before packet identifier 666 | p = stringprint(p, topic); 667 | 668 | // add packet identifier. used for checking PUBACK in QOS > 0 669 | if(qos > 0) { 670 | p[0] = (packet_id_counter >> 8) & 0xFF; 671 | p[1] = packet_id_counter & 0xFF; 672 | p+=2; 673 | 674 | // increment the packet id 675 | packet_id_counter++; 676 | } 677 | 678 | memmove(p, data, bLen); 679 | p+= bLen; 680 | len = p - packet; 681 | DEBUG_PRINTLN(F("MQTT publish packet:")); 682 | DEBUG_PRINTBUFFER(buffer, len); 683 | return len; 684 | } 685 | 686 | uint8_t Adafruit_MQTT::subscribePacket(uint8_t *packet, const char *topic, 687 | uint8_t qos) { 688 | uint8_t *p = packet; 689 | uint16_t len; 690 | 691 | p[0] = MQTT_CTRL_SUBSCRIBE << 4 | MQTT_QOS_1 << 1; 692 | // fill in packet[1] last 693 | p+=2; 694 | 695 | // packet identifier. used for checking SUBACK 696 | p[0] = (packet_id_counter >> 8) & 0xFF; 697 | p[1] = packet_id_counter & 0xFF; 698 | p+=2; 699 | 700 | // increment the packet id 701 | packet_id_counter++; 702 | 703 | p = stringprint(p, topic); 704 | 705 | p[0] = qos; 706 | p++; 707 | 708 | len = p - packet; 709 | packet[1] = len-2; // don't include the 2 bytes of fixed header data 710 | DEBUG_PRINTLN(F("MQTT subscription packet:")); 711 | DEBUG_PRINTBUFFER(buffer, len); 712 | return len; 713 | } 714 | 715 | 716 | 717 | uint8_t Adafruit_MQTT::unsubscribePacket(uint8_t *packet, const char *topic) { 718 | 719 | uint8_t *p = packet; 720 | uint16_t len; 721 | 722 | p[0] = MQTT_CTRL_UNSUBSCRIBE << 4 | 0x1; 723 | // fill in packet[1] last 724 | p+=2; 725 | 726 | // packet identifier. used for checking UNSUBACK 727 | p[0] = (packet_id_counter >> 8) & 0xFF; 728 | p[1] = packet_id_counter & 0xFF; 729 | p+=2; 730 | 731 | // increment the packet id 732 | packet_id_counter++; 733 | 734 | p = stringprint(p, topic); 735 | 736 | len = p - packet; 737 | packet[1] = len-2; // don't include the 2 bytes of fixed header data 738 | DEBUG_PRINTLN(F("MQTT unsubscription packet:")); 739 | DEBUG_PRINTBUFFER(buffer, len); 740 | return len; 741 | 742 | } 743 | 744 | uint8_t Adafruit_MQTT::pingPacket(uint8_t *packet) { 745 | packet[0] = MQTT_CTRL_PINGREQ << 4; 746 | packet[1] = 0; 747 | DEBUG_PRINTLN(F("MQTT ping packet:")); 748 | DEBUG_PRINTBUFFER(buffer, 2); 749 | return 2; 750 | } 751 | 752 | uint8_t Adafruit_MQTT::pubackPacket(uint8_t *packet, uint16_t packetid) { 753 | packet[0] = MQTT_CTRL_PUBACK << 4; 754 | packet[1] = 2; 755 | packet[2] = packetid >> 8; 756 | packet[3] = packetid; 757 | DEBUG_PRINTLN(F("MQTT puback packet:")); 758 | DEBUG_PRINTBUFFER(buffer, 4); 759 | return 4; 760 | } 761 | 762 | uint8_t Adafruit_MQTT::disconnectPacket(uint8_t *packet) { 763 | packet[0] = MQTT_CTRL_DISCONNECT << 4; 764 | packet[1] = 0; 765 | DEBUG_PRINTLN(F("MQTT disconnect packet:")); 766 | DEBUG_PRINTBUFFER(buffer, 2); 767 | return 2; 768 | } 769 | 770 | // Adafruit_MQTT_Publish Definition //////////////////////////////////////////// 771 | 772 | Adafruit_MQTT_Publish::Adafruit_MQTT_Publish(Adafruit_MQTT *mqttserver, 773 | const char *feed, uint8_t q) { 774 | mqtt = mqttserver; 775 | topic = feed; 776 | qos = q; 777 | } 778 | bool Adafruit_MQTT_Publish::publish(int32_t i) { 779 | char payload[12]; 780 | ltoa(i, payload, 10); 781 | return mqtt->publish(topic, payload, qos); 782 | } 783 | 784 | bool Adafruit_MQTT_Publish::publish(uint32_t i) { 785 | char payload[11]; 786 | ultoa(i, payload, 10); 787 | return mqtt->publish(topic, payload, qos); 788 | } 789 | 790 | bool Adafruit_MQTT_Publish::publish(double f, uint8_t precision) { 791 | char payload[41]; // Need to technically hold float max, 39 digits and minus sign. 792 | dtostrf(f, 0, precision, payload); 793 | return mqtt->publish(topic, payload, qos); 794 | } 795 | 796 | bool Adafruit_MQTT_Publish::publish(const char *payload) { 797 | return mqtt->publish(topic, payload, qos); 798 | } 799 | 800 | //publish buffer of arbitrary length 801 | bool Adafruit_MQTT_Publish::publish(uint8_t *payload, uint16_t bLen) { 802 | 803 | return mqtt->publish(topic, payload, bLen, qos); 804 | } 805 | 806 | 807 | // Adafruit_MQTT_Subscribe Definition ////////////////////////////////////////// 808 | 809 | Adafruit_MQTT_Subscribe::Adafruit_MQTT_Subscribe(Adafruit_MQTT *mqttserver, 810 | const char *feed, uint8_t q) { 811 | mqtt = mqttserver; 812 | topic = feed; 813 | qos = q; 814 | datalen = 0; 815 | callback_uint32t = 0; 816 | callback_buffer = 0; 817 | callback_double = 0; 818 | callback_io = 0; 819 | io_mqtt = 0; 820 | } 821 | 822 | void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackUInt32Type cb) { 823 | callback_uint32t = cb; 824 | } 825 | 826 | void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackDoubleType cb) { 827 | callback_double = cb; 828 | } 829 | 830 | void Adafruit_MQTT_Subscribe::setCallback(SubscribeCallbackBufferType cb) { 831 | callback_buffer = cb; 832 | } 833 | 834 | void Adafruit_MQTT_Subscribe::setCallback(AdafruitIO_MQTT *io, SubscribeCallbackIOType cb) { 835 | callback_io = cb; 836 | io_mqtt= io; 837 | } 838 | 839 | void Adafruit_MQTT_Subscribe::removeCallback(void) { 840 | callback_uint32t = 0; 841 | callback_buffer = 0; 842 | callback_double = 0; 843 | callback_io = 0; 844 | io_mqtt = 0; 845 | } 846 | --------------------------------------------------------------------------------