-
Notifications
You must be signed in to change notification settings - Fork 1
/
Azure-IoT-ESP8266.ino
409 lines (331 loc) · 9.75 KB
/
Azure-IoT-ESP8266.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#define USEDHT22 1
#include <FS.h>
#include <MQTTClient.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <NTPClient.h>
#ifdef USEDHT22
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#endif
#include "sha256.h"
#include "ConnectionStringHelper.h"
/* ----------------------------------------------------------------------------- *
* This Sample Code is provided for the purpose of illustration only and is not *
* intended to be used in a production environment. THIS SAMPLE CODE AND ANY *
* RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER *
* EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. *
* ----------------------------------------------------------------------------- */
/*
*
* Demonstrates connecting an ESP8266 to an Azure IoT hub using a third party MQTT stack.
* See: https://azure.microsoft.com/en-us/documentation/articles/iot-hub-mqtt-support/#using-the-mqtt-protocol-directly
*
*/
const uint INTERVAL = 20; // SAS token validity period in minutes
const int REFRESHPERCENTAGE = 80; // Percentage of SAS token validity used when reauthentication is attempted
const int MISSEDTOOMANY = 10; // Reconnect to MQTT when consecutively missed this many messages
const int BLINKER = BUILTIN_LED;
const int BLINKTIME = 700;
const int BLINKOFF = HIGH;
const int BLINKON = LOW; // Set to BLINKOFF to disable LED
#ifdef USEDHT22
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
#endif
WiFiUDP ntpUDP;
WiFiClientSecure net;
NTPClient timeClient(ntpUDP);
MQTTClient client(256);
ConnectionStringHelper *csHelper = NULL;
String pubTopic;
String subTopic;
int32_t refreshTime = 0;
bool shouldSaveConfig = false;
//
// Code included to assist debugging
/*
extern "C"
{
void dump_buffer(uint8_t length, unsigned char *buffer)
{
char hex[4];
for (int i = 0; i < length; i += 16)
{
int j;
uint8_t chunk = (length - i < 16)? length - i : 16;
for (j = i; j < i + chunk; j++)
{
sprintf(hex, " %02x", buffer[j]);
Serial.print(hex);
}
Serial.print(" ");
if (chunk < 16)
{
for (j = chunk; j < 16; j++)
Serial.print(" ");
}
for (j = i; j < i + chunk; j++)
{
Serial.write((isprint(buffer[j]))? buffer[j] : '.');
}
Serial.println();
}
}
}
*/
//void softwareReboot()
//{
// Serial.println("Rebooting...");
// wdt_enable(WDTO_250MS);
// while(true);
//}
void saveConfigCallback()
{
Serial.println("Config needs to be saved");
shouldSaveConfig = true;
}
void configModeCallback(WiFiManager *wifiManager)
{
Serial.println("Entering configuration mode");
Serial.println(WiFi.softAPIP());
}
void setupWiFi()
{
bool forceConfig = false;
Serial.println("Mounting SPIFFS");
if (SPIFFS.begin())
{
if (SPIFFS.exists("/config.txt"))
{
Serial.println("Opening config.txt");
File configFile = SPIFFS.open("/config.txt", "r");
if (configFile)
{
Serial.println("Found config.txt");
size_t size = configFile.size();
char *configData = new char[size];
configFile.readBytes(configData, size);
csHelper = new ConnectionStringHelper(configData);
Serial.print("Connection string = ");
Serial.println(configData);
delete [] configData;
configFile.close();
}
else
{
Serial.println("Failed to open config.txt");
forceConfig = true; // May not help any
}
}
else
{
Serial.println("File config.txt not found");
forceConfig = true;
}
}
else
{
Serial.println("Failed to mount SPIFFS");
forceConfig = true;
}
WiFiManagerParameter connectionStringParm("connectionString", "Connection String", NULL, 150);
WiFiManager wifiManager;
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.setAPCallback(configModeCallback);
wifiManager.addParameter(&connectionStringParm);
Serial.println("Connecting or configuring");
bool connected = false;
if (forceConfig)
{
// Don't bother trying to connect we need more info
connected = wifiManager.startConfigPortal("ESP8266Config", "ESP8266");
}
else
{
connected = wifiManager.autoConnect("ESP8266Config", "ESP8266");
}
if (!connected)
{
Serial.println("Failed to connect to Wi-Fi");
ESP.reset();
}
Serial.println(WiFi.SSID());
Serial.println();
Serial.print("IP Address = ");
Serial.println(WiFi.localIP());
if (shouldSaveConfig)
{
Serial.println("Saving config.txt");
File configFile = SPIFFS.open("/config.txt", "w");
if (!configFile)
{
Serial.println("Failed to open config.txt");
}
Serial.println(configFile.write((const uint8_t *)connectionStringParm.getValue(), strlen(connectionStringParm.getValue()) + 1));
configFile.close();
// Sanity check
if (!SPIFFS.exists("/config.txt"))
{
Serial.println("WTF... where is my new file?");
}
csHelper = new ConnectionStringHelper(connectionStringParm.getValue());
Serial.println("Saved config.txt");
}
}
void setupMQTT(uint interval)
{
long now = timeClient.getEpochTime();
long epochTime = now + (interval * 60);
String mqttUserName = csHelper->getKeywordValue("hostname") + "/" + csHelper->getKeywordValue("deviceid");
String mqttClientId = csHelper->getKeywordValue("deviceid");
String mqttServer = csHelper->getKeywordValue("hostname");
String mqttPassword = "";
csHelper->generatePassword(mqttServer, mqttClientId, csHelper->getKeywordValue("SharedAccessKey"), epochTime, mqttPassword);
refreshTime = now + (interval * 60 * REFRESHPERCENTAGE / 100);
Serial.print("Time is now ");
Serial.println(now, DEC);
Serial.print("SAS token expires at ");
Serial.println(epochTime, DEC);
Serial.print("Will refresh at ");
Serial.println(refreshTime, DEC);
// Serial.print("MQTT_Server=");
// Serial.println(mqttServer);
// Serial.print("MQTT_ClientId=");
// Serial.println(mqttClientId);
// Serial.print("MQTT_UserName=");
// Serial.println(mqttUserName);
// Serial.print("MQTT_Password=");
// Serial.println(mqttPassword);
uint8_t ret;
client.begin(mqttServer.c_str(), 8883, net);
client.setOptions(240, 0, 1000);
client.onMessage(messageReceived);
int counter = 20;
// If we can't connect in 20 attempts then reboot
while (!client.connect(mqttClientId.c_str(), mqttUserName.c_str(), mqttPassword.c_str()))
{
Serial.print(".");
delay(1000);
if (0 >= --counter)
{
ESP.reset();
}
}
Serial.println("MQTT connected");
pubTopic = "devices/" + mqttClientId + "/messages/events/";
subTopic = "devices/" + mqttClientId + "/messages/devicebound/#";
if (!client.subscribe(subTopic.c_str(), 1))
Serial.println("Subscribe failed");
}
void setup()
{
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
Serial.println("Start Test");
pinMode(BLINKER, OUTPUT);
digitalWrite(BLINKER, BLINKOFF);
setupWiFi();
timeClient.begin();
// Cannot continue until we have a clock update
while (!timeClient.update())
{
Serial.println("Initial clock update failed");
delay(250);
}
delay(1000);
setupMQTT(INTERVAL);
}
void loop() {
static uint32_t counter = 0;
static uint32_t lastMsg = 0;
static uint32_t missedMessageCount = 0;
static uint32_t ledOffAt = 0;
uint32_t currMillis;
#ifdef USEDHT22
double temp;
double humidity;
char convBuf[20];
#endif
while (!timeClient.update())
{
Serial.println("NTP update failed");
delay(250);
}
client.loop();
// Refresh the SAS token if necessary
if (timeClient.getEpochTime() > refreshTime)
{
Serial.println("Reconnecting to refresh SAS token");
client.disconnect();
setupMQTT(INTERVAL);
missedMessageCount = 0;
}
currMillis = millis();
if (ledOffAt && currMillis >= ledOffAt)
{
digitalWrite(BLINKER, BLINKOFF);
ledOffAt = 0;
}
// Check for wrap (around every 50 days)
if (currMillis < lastMsg)
lastMsg = 0;
// Send a message about every three seconds
if (currMillis - lastMsg > 3000)
{
lastMsg = currMillis;
String msg;
bool skipMsg = false;
#ifdef USEDHT22
temp = dht.readTemperature();
humidity = dht.readHumidity();
if (isnan(temp) || isnan(humidity))
{
Serial.println("Bad reading from DHT22 - message skipped");
skipMsg = true;
}
else
{
msg = "{ \"deviceid\": " + String(csHelper->getKeywordValue("deviceid")) +
" \"status\": { \"temperature\": " + dtostrf(dht.convertCtoF(temp), 4, 2, convBuf) +
" \"humidity\": " + dtostrf(humidity, 4, 2, convBuf) +
" } }";
Serial.println(msg);
}
#else
msg = "{ \"counter\": " + String(counter++) + ", \"epoch\": " + String(timeClient.getEpochTime()) + ", \"millis\": " + String(currMillis) + " }";
#endif
if (!skipMsg)
{
if (!client.publish(pubTopic.c_str(), msg.c_str(), false, 1))
{
Serial.println("Publish failed");
if (++missedMessageCount > MISSEDTOOMANY)
{
missedMessageCount = 0;
client.disconnect();
setupMQTT(INTERVAL);
}
}
else
{
missedMessageCount = 0;
digitalWrite(BLINKER, BLINKON);
ledOffAt = currMillis + BLINKTIME;
}
}
}
}
void messageReceived(String &topic, String &payload)
{
Serial.println("Message received");
Serial.println("\tTopic: " + topic + "\n\tPayload: " + payload);
}