├── .gitattributes ├── .gitignore ├── ESP_MQTT_ADAFRUIT_LIBRARY └── ESP_MQTT_ADAFRUIT_LIBRARY.ino ├── ESP_MQTT_ESPMQTT_LIBRARY └── ESP_MQTT_ESPMQTT_LIBRARY.ino ├── ESP_MQTT_PUBSUB_LIBRARY └── ESP_MQTT_PUBSUB_LIBRARY.ino └── README.md /.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 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /ESP_MQTT_ADAFRUIT_LIBRARY/ESP_MQTT_ADAFRUIT_LIBRARY.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 | * 18 | * Code by Andreas Spiess 19 | */ 20 | #include 21 | #include "Adafruit_MQTT.h" 22 | #include "Adafruit_MQTT_Client.h" 23 | #include "credentials_CloudMQTT.h" 24 | 25 | /* 26 | * I save my credentials in a file to protect them. Please comment this line and fill out 27 | * your credentials below 28 | * 29 | */ 30 | //#include "credentials_Adafruit_IO.h" 31 | 32 | #define LED 15 33 | 34 | 35 | /* definition of credentials and feeds 36 | * 37 | #define ssid "..." 38 | #define password "..." 39 | 40 | 41 | 42 | 43 | #define SERVER "io.adafruit.com" 44 | #define SERVERPORT 1883 45 | #define MQTT_USERNAME "..." 46 | #define MQTT_KEY "..." 47 | 48 | #define USERNAME "sensorsiot/" 49 | #define PREAMBLE "feeds/" 50 | #define T_LUMINOSITY "luminosity" 51 | #define T_CLIENTSTATUS "clientStatus" 52 | #define T_COMMAND "command" 53 | * 54 | */ 55 | 56 | unsigned long entry; 57 | bool clientStatus, prevClientStatus; 58 | float luminosity, prevLumiosity; 59 | unsigned long entryL, entryS; 60 | 61 | 62 | 63 | #define userID "sensorsiot" 64 | 65 | 66 | // Create an ESP8266 WiFiClient class to connect to the MQTT server. 67 | WiFiClient client; 68 | 69 | // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. 70 | Adafruit_MQTT_Client mqtt(&client, SERVER, SERVERPORT, MQTT_USERNAME, MQTT_KEY); 71 | 72 | /****************************** Feeds ***************************************/ 73 | 74 | // Setup a feed called 'photocell' for publishing. 75 | // Notice MQTT paths for AIO follow the form: /feeds/ 76 | const char LUMINOSITY_FEED[] PROGMEM = USERNAME PREAMBLE T_LUMINOSITY; 77 | Adafruit_MQTT_Publish tLuminosity = Adafruit_MQTT_Publish(&mqtt, LUMINOSITY_FEED); 78 | 79 | // Setup a feed called 'clientStatus' for publishing. 80 | // Notice MQTT paths for AIO follow the form: /feeds/ 81 | const char CLIENTSTATUS_FEED[] PROGMEM = USERNAME PREAMBLE T_CLIENTSTATUS; 82 | Adafruit_MQTT_Publish tClientStatus = Adafruit_MQTT_Publish(&mqtt, CLIENTSTATUS_FEED); 83 | 84 | // Setup a feed called 'command' for subscribing to changes. 85 | const char COMMAND_FEED[] PROGMEM = USERNAME PREAMBLE T_COMMAND; 86 | Adafruit_MQTT_Subscribe tCommand = Adafruit_MQTT_Subscribe(&mqtt, COMMAND_FEED); 87 | 88 | // Setup a feed called 'test' for subscribing to changes. 89 | const char TEST_FEED[] PROGMEM = USERNAME PREAMBLE "test"; 90 | Adafruit_MQTT_Subscribe tTest = Adafruit_MQTT_Subscribe(&mqtt, TEST_FEED); 91 | 92 | 93 | 94 | // 95 | void setup() { 96 | Serial.begin(115200); 97 | delay(100); 98 | pinMode(LED, OUTPUT); 99 | 100 | 101 | 102 | connectWLAN(); 103 | 104 | Serial.println("Connecting to MQTT server"); 105 | entry = 0; 106 | Serial.begin(115200); 107 | delay(10); 108 | // connect to WiFi 109 | connectWLAN(); 110 | 111 | // Setup MQTT subscription for onoff feed. 112 | mqtt.subscribe(&tCommand); 113 | mqtt.subscribe(&tTest); 114 | 115 | Serial.println(USERNAME PREAMBLE T_COMMAND); 116 | 117 | } 118 | 119 | // 120 | void loop() { 121 | yield(); 122 | // Ensure the connection to the MQTT server is alive (this will make the first 123 | // connection and automatically reconnect when disconnected). See the MQTT_connect 124 | // function definition further below. 125 | connectMQTT(); 126 | 127 | int hi = receiveCommand(); 128 | if (hi == 1) clientStatus = true; 129 | if (hi == 0) clientStatus = false; 130 | 131 | int luminosity = analogRead(A0); 132 | 133 | if (abs(luminosity - prevLumiosity) > 90 || (millis() - entryL > 1000)) { // publish if value changed or after 1 second 134 | // Serial.print(" LUMinosity: "); 135 | // Serial.println(abs(luminosity - prevLumiosity)); 136 | if (publishLuminosity(luminosity)) entryL = millis(); 137 | prevLumiosity = luminosity; 138 | entryL = millis(); 139 | } 140 | 141 | if (clientStatus != prevClientStatus || (millis() - entryS > 1000)) { // publish if value changed or after 1 second 142 | // Serial.print(clientStatus ); 143 | // Serial.print(" STATUS "); 144 | // Serial.println(prevClientStatus); 145 | publishClientStatus(clientStatus); 146 | prevClientStatus = clientStatus; 147 | entryS = millis(); 148 | } 149 | } 150 | 151 | void connectWLAN() { 152 | // Connect to WiFi access point. 153 | Serial.println(); 154 | Serial.println(); 155 | Serial.print("Connecting to "); 156 | Serial.println(ssid); 157 | 158 | 159 | WiFi.begin(ssid, password); 160 | 161 | while (WiFi.status() != WL_CONNECTED) { 162 | delay(500); 163 | Serial.print("."); 164 | } 165 | 166 | Serial.println(""); 167 | Serial.println("WiFi connected"); 168 | Serial.println("IP address: "); 169 | Serial.println(WiFi.localIP()); 170 | } 171 | 172 | 173 | void connectMQTT() { 174 | int8_t ret; 175 | 176 | // Stop if already connected. 177 | if (mqtt.connected()) { 178 | return; 179 | } 180 | Serial.print("Connecting to MQTT... "); 181 | 182 | while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected 183 | Serial.println(mqtt.connectErrorString(ret)); 184 | Serial.println("Retrying MQTT connection in 5 seconds..."); 185 | mqtt.disconnect(); 186 | delay(5000); // wait 5 seconds 187 | } 188 | Serial.println("MQTT Connected!"); 189 | } 190 | 191 | 192 | bool publishLuminosity(float value) { 193 | // Now we can publish stuff! 194 | bool success = false; 195 | Serial.print(F("\nSending Luminosity ")); 196 | Serial.print(value); 197 | Serial.print("..."); 198 | if (! tLuminosity.publish(value, 1)) { 199 | Serial.println(F("Failed")); 200 | } else { 201 | Serial.println(F("OK!")); 202 | } 203 | return success; 204 | } 205 | 206 | bool publishClientStatus(bool clientStat) { 207 | bool success = false; 208 | Serial.print(F("\nSending clientStatus ")); 209 | Serial.print(clientStat); 210 | Serial.print("..."); 211 | 212 | if (! tClientStatus.publish(clientStat, 1)) Serial.println(F("Failed")); 213 | else { 214 | Serial.println(F(" OK!")); 215 | success = true; 216 | } 217 | return success; 218 | } 219 | 220 | 221 | 222 | int receiveCommand() { 223 | int clientSt = 99; 224 | // this is our 'wait for incoming subscription packets' busy subloop 225 | Adafruit_MQTT_Subscribe *subscription; 226 | while ((subscription = mqtt.readSubscription(10))) { 227 | if (subscription == &tCommand) { 228 | Serial.print(F("Got: ")); 229 | Serial.println((char*)tCommand.lastread); 230 | 231 | // Switch on the LED if an 1 was received as first character 232 | if (tCommand.lastread[1] == 'N') { 233 | clientSt = true; 234 | digitalWrite(LED, HIGH); 235 | //digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level 236 | // but actually the LED is on; this is because 237 | // it is acive low on the ESP-01) 238 | } 239 | if (tCommand.lastread[1] == 'F') { 240 | clientSt = false; 241 | digitalWrite(LED, LOW); 242 | //digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH 243 | } 244 | 245 | } 246 | if (subscription == &tTest) { 247 | Serial.print(F("Got: ")); 248 | Serial.println((char*)tCommand.lastread); 249 | 250 | // Switch on the LED if an 1 was received as first character 251 | if (tTest.lastread[1] == 'N') { 252 | clientSt = true; 253 | digitalWrite(LED, HIGH); 254 | //digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level 255 | // but actually the LED is on; this is because 256 | // it is acive low on the ESP-01) 257 | } 258 | if (tTest.lastread[1] == 'F') { 259 | clientSt = false; 260 | digitalWrite(LED, LOW); 261 | //digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH 262 | } 263 | } 264 | } 265 | return clientSt; 266 | } 267 | -------------------------------------------------------------------------------- /ESP_MQTT_ESPMQTT_LIBRARY/ESP_MQTT_ESPMQTT_LIBRARY.ino: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Library used: 4 | * https://github.com/i-n-g-o/esp-mqtt-arduino 5 | * 6 | * 7 | * Code by Andreas Spiess 8 | * 9 | * 10 | * 11 | */ 12 | 13 | 14 | 15 | 16 | 17 | 18 | #include 19 | #include 20 | 21 | 22 | /* 23 | * I save my credentials in a file to protect them. Please comment this line and fill out 24 | * your credentials below 25 | * 26 | */ 27 | //#include "credentials_CloudMQTT.h" 28 | #include "credentials_Adafruit_IO.h" 29 | 30 | /* 31 | * 32 | #define ssid "..." 33 | #define password "..." 34 | 35 | #define SERVER "io.adafruit.com" 36 | #define SERVERPORT 1883 37 | #define MQTT_USERNAME "..." 38 | #define MQTT_KEY "..." 39 | 40 | #define USERNAME "sensorsiot/" 41 | #define PREAMBLE "feeds/" 42 | #define T_LUMINOSITY "luminosity" 43 | #define T_CLIENTSTATUS "clientStatus" 44 | #define T_COMMAND "command" 45 | * 46 | */ 47 | 48 | unsigned long entry; 49 | bool clientStatu; 50 | float luminosity; 51 | 52 | 53 | // create MQTT object 54 | MQTT myMqtt(USERNAME, SERVER, SERVERPORT); 55 | 56 | // 57 | void setup() { 58 | Serial.begin(115200); 59 | delay(100); 60 | Serial.print("Connecting to "); 61 | Serial.println(ssid); 62 | 63 | 64 | WiFi.begin(ssid, password); 65 | 66 | while (WiFi.status() != WL_CONNECTED) { 67 | delay(500); 68 | Serial.print("."); 69 | } 70 | 71 | Serial.println(""); 72 | Serial.println("WiFi connected"); 73 | Serial.println("IP address: "); 74 | Serial.println(WiFi.localIP()); 75 | 76 | Serial.println("Connecting to MQTT server"); 77 | 78 | // setup callbacks 79 | myMqtt.onConnected(myConnectedCb); 80 | myMqtt.onDisconnected(myDisconnectedCb); 81 | myMqtt.onPublished(myPublishedCb); 82 | myMqtt.onData(myDataCb); 83 | 84 | Serial.println("connect mqtt..."); 85 | myMqtt.setUserPwd(MQTT_USERNAME, MQTT_KEY); 86 | myMqtt.connect(); 87 | delay(10); 88 | } 89 | 90 | // 91 | void loop() { 92 | yield(); 93 | int luminosity = analogRead(A0); 94 | 95 | String valueStr(luminosity); 96 | String statStr(clientStatu); 97 | 98 | // publish value to topic 99 | myMqtt.publish(USERNAME PREAMBLE T_LUMINOSITY, valueStr); 100 | myMqtt.publish(USERNAME PREAMBLE T_CLIENTSTATUS, statStr); 101 | 102 | delay(1000); 103 | } 104 | 105 | 106 | //---------------------------------------------------------------------- 107 | void myConnectedCb() { 108 | Serial.println("connected to MQTT server"); 109 | 110 | Serial.println("subscribe to topic..."); 111 | myMqtt.subscribe(USERNAME PREAMBLE T_COMMAND,1); 112 | } 113 | 114 | void myDisconnectedCb() { 115 | Serial.println("disconnected. try to reconnect..."); 116 | 117 | delay(500); 118 | myMqtt.connect(); 119 | } 120 | 121 | void myPublishedCb() { 122 | // Serial.println("published."); 123 | } 124 | 125 | void myDataCb(String& topic, String& data) { 126 | 127 | Serial.print(topic); 128 | Serial.print(": "); 129 | Serial.println(data); 130 | if (data[1] == 'F') clientStatu = false; 131 | if (data[1] == 'N') clientStatu = true; 132 | } 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /ESP_MQTT_PUBSUB_LIBRARY/ESP_MQTT_PUBSUB_LIBRARY.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | PUBSUB MQTT library 4 | 5 | 6 | Basic ESP8266 MQTT example 7 | 8 | This sketch demonstrates the capabilities of the pubsub library in combination 9 | with the ESP8266 board/library. 10 | 11 | It connects to an MQTT server then: 12 | - publishes "hello world" to the topic "outTopic" every two seconds 13 | - subscribes to the topic "inTopic", printing out any messages 14 | it receives. NB - it assumes the received payloads are strings not binary 15 | - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led, 16 | else switch it off 17 | 18 | It will reconnect to the server if the connection is lost using a blocking 19 | reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to 20 | achieve the same result without blocking the main loop. 21 | 22 | To install the ESP8266 board, (using Arduino 1.6.4+): 23 | - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs": 24 | http://arduino.esp8266.com/stable/package_esp8266com_index.json 25 | - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266" 26 | - Select your ESP8266 in "Tools -> Board" 27 | 28 | Code from Andreas Spiess 29 | 30 | */ 31 | 32 | #define LEDBLUE 13 33 | 34 | #include 35 | #include 36 | 37 | 38 | /* 39 | * I save my credentials in a file to protect them. Please comment this line and fill out 40 | * your credentials below 41 | * 42 | */ 43 | //#include "credentials_CloudMQTT.h" 44 | #include "credentials_Adafruit_IO.h" 45 | 46 | 47 | 48 | /* 49 | * 50 | #define ssid "..." 51 | #define password "..." 52 | 53 | #define SERVER "io.adafruit.com" 54 | #define SERVERPORT 1883 55 | #define MQTT_USERNAME "..." 56 | #define MQTT_KEY "..." 57 | 58 | #define USERNAME "sensorsiot/" 59 | #define PREAMBLE "feeds/" 60 | #define T_LUMINOSITY "luminosity" 61 | #define T_CLIENTSTATUS "clientStatus" 62 | #define T_COMMAND "command" 63 | * 64 | */ 65 | 66 | 67 | unsigned long entry; 68 | byte clientStatus, prevClientStatus = 99; 69 | float luminosity, prevLumiosity = -1; 70 | char valueStr[5]; 71 | 72 | WiFiClient WiFiClient; 73 | // create MQTT object 74 | PubSubClient client(WiFiClient); 75 | 76 | 77 | // 78 | void setup() { 79 | 80 | pinMode(LEDBLUE, OUTPUT); 81 | Serial.begin(115200); 82 | delay(100); 83 | Serial.println(); 84 | Serial.println(); 85 | Serial.print("Connecting to "); 86 | Serial.println(ssid); 87 | WiFi.begin(ssid, password); 88 | 89 | while (WiFi.status() != WL_CONNECTED) { 90 | delay(500); 91 | Serial.print("."); 92 | } 93 | 94 | Serial.println(""); 95 | Serial.println("WiFi connected"); 96 | Serial.println("IP address: "); 97 | Serial.println(WiFi.localIP()); 98 | WiFi.printDiag(Serial); 99 | 100 | client.setServer(SERVER, SERVERPORT); 101 | client.setCallback(callback); 102 | } 103 | 104 | // 105 | void loop() { 106 | //Serial.println("loop"); 107 | yield(); 108 | if (!client.connected()) { 109 | Serial.println("Attempting MQTT connection..."); 110 | // Attempt to connect 111 | if (client.connect("", MQTT_USERNAME, MQTT_KEY)) { 112 | Serial.println("connected"); 113 | // ... and resubscribe 114 | client.subscribe(USERNAME PREAMBLE T_COMMAND, 1); 115 | client.subscribe(USERNAME PREAMBLE "test", 1); 116 | } else { 117 | Serial.print("failed, rc="); 118 | Serial.print(client.state()); 119 | Serial.println(" try again in 5 seconds"); 120 | // Wait 5 seconds before retrying 121 | delay(5000); 122 | } 123 | } 124 | 125 | if (millis() - entry > 1200) { 126 | Serial.println("Measure"); 127 | entry = millis(); 128 | luminosity = analogRead(A0); 129 | } 130 | 131 | if (client.connected() && prevLumiosity != luminosity) { 132 | Serial.println("Publish Luminosity"); 133 | String hi = (String)luminosity; 134 | hi.toCharArray(valueStr, 5); 135 | client.publish(USERNAME PREAMBLE T_LUMINOSITY, valueStr); 136 | prevLumiosity = luminosity; 137 | delay(500); 138 | } 139 | 140 | if (client.connected()&& prevClientStatus != clientStatus ) { 141 | Serial.println("Publish Status"); 142 | 143 | String hi = (String)clientStatus; 144 | hi.toCharArray(valueStr, 2); 145 | client.publish(USERNAME PREAMBLE T_CLIENTSTATUS, valueStr); 146 | prevClientStatus = clientStatus; 147 | } 148 | client.loop(); 149 | } 150 | 151 | 152 | //---------------------------------------------------------------------- 153 | 154 | 155 | void callback(char* topic, byte * data, unsigned int length) { 156 | // handle message arrived { 157 | 158 | Serial.print(topic); 159 | Serial.print(": "); 160 | for (int i = 0; i < length; i++) { 161 | Serial.print((char)data[i]); 162 | } 163 | Serial.println(); 164 | if (data[1] == 'F') { 165 | clientStatus = 0; 166 | digitalWrite(LEDBLUE, LOW); 167 | } else { 168 | clientStatus = 1; 169 | digitalWrite(LEDBLUE, HIGH); 170 | } 171 | } 172 | 173 | 174 | 175 | 176 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MQTT-Examples 2 | ESP8266 Examples for youTube video with three different libraries 3 | 4 | Video: https://youtu.be/9G-nMGcELG8 5 | --------------------------------------------------------------------------------