-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiothub_lights.ino
More file actions
430 lines (349 loc) · 14.4 KB
/
iothub_lights.ino
File metadata and controls
430 lines (349 loc) · 14.4 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Note: PLEASE see https://github.com/Azure/azure-iot-arduino#simple-sample-instructions for detailed sample setup instructions for Azure IoT SDK
// Note2: To use this sample with the esp32, you MUST build the AzureIoTSocket_WiFi library by using the make_sdk.py,
// found in https://github.com/Azure/azure-iot-pal-arduino/tree/master/build_all.
// Command line example: python3 make_sdk.py -o <your-lib-folder>
#include <AzureIoTHub.h>
#include <stdio.h>
#include <stdlib.h>
#include <ArduinoJson.h>
#include <FastLED.h>
#include "iot_configs.h" // You must set your wifi SSID, wifi PWD, and your IoTHub Device Connection String in iot_configs.h
#include "sample_init.h"
#ifdef is_esp_board
#include "Esp.h"
#endif
#ifdef SAMPLE_MQTT
#include "AzureIoTProtocol_MQTT.h"
#include "iothubtransportmqtt.h"
#endif // SAMPLE_MQTT
#ifdef SAMPLE_HTTP
#include "AzureIoTProtocol_HTTP.h"
#include "iothubtransporthttp.h"
#endif // SAMPLE_HTTP
static const char ssid[] = IOT_CONFIG_WIFI_SSID;
static const char pass[] = IOT_CONFIG_WIFI_PASSWORD;
/* Define several constants/global variables */
static const char* connectionString = DEVICE_CONNECTION_STRING;
static bool g_continueRunning = true; // defines whether or not the device maintains its IoT Hub connection after sending (think receiving messages from the cloud)
static size_t g_message_count_send_confirmations = 0;
static bool g_run_demo = true;
IOTHUB_MESSAGE_HANDLE message_handle;
size_t messages_sent = 0;
#define MESSAGE_COUNT 5 // determines the number of times the device tries to send a message to the IoT Hub in the cloud.
const char* telemetry_msg = "test_message";
const char* quit_msg = "quit";
const char* exit_msg = "exit";
IOTHUB_DEVICE_CLIENT_LL_HANDLE device_ll_handle;
static int callbackCounter;
int receiveContext = 0;
////////////////////////////////////////////////////////////////////////////////////////////////
/*********************************** FastLED Defintions ********************************/
#define NUM_LEDS 30
#define DATA_PIN 5
//#define CLOCK_PIN 5
#define CHIPSET WS2812B
#define COLOR_ORDER BRG
const char* on_cmd = "ON";
const char* off_cmd = "OFF";
const char* effect = "solid";
String effectString = "solid";
String oldeffectString = "solid";
/****************************************FOR JSON***************************************/
const int BUFFER_SIZE = JSON_OBJECT_SIZE(10);
//#define MQTT_MAX_PACKET_SIZE 512
/*********************************** FastLED Defintions ********************************/
byte realRed = 0;
byte realGreen = 0;
byte realBlue = 0;
byte red = 255;
byte green = 255;
byte blue = 255;
byte brightness = 255;
/******************************** GLOBALS for fade/flash *******************************/
bool stateOn = true;
bool startFade = true;
bool onbeforeflash = false;
unsigned long lastLoop = 0;
int transitionTime = 0;
int effectSpeed = 0;
bool inFade = false;
int loopCount = 0;
int stepR, stepG, stepB;
int redVal, grnVal, bluVal;
bool flash = false;
bool startFlash = false;
int flashLength = 0;
unsigned long flashStartTime = 0;
byte flashRed = red;
byte flashGreen = green;
byte flashBlue = blue;
byte flashBrightness = brightness;
/********************************** GLOBALS for EFFECTS ******************************/
//RAINBOW
uint8_t thishue = 0; // Starting hue value.
uint8_t deltahue = 10;
//CANDYCANE
CRGBPalette16 currentPalettestriped; //for Candy Cane
CRGBPalette16 gPal; //for fire
//NOISE
static uint16_t dist; // A random number for our noise generator.
uint16_t scale = 30; // Wouldn't recommend changing this on the fly, or the animation will be really blocky.
uint8_t maxChanges = 48; // Value for blending between palettes.
CRGBPalette16 targetPalette(OceanColors_p);
CRGBPalette16 currentPalette(CRGB::Black);
//TWINKLE
#define DENSITY 80
int twinklecounter = 0;
//RIPPLE
uint8_t colour; // Ripple colour is randomized.
int center = 0; // Center of the current ripple.
int step = -1; // -1 is the initializing step.
uint8_t myfade = 255; // Starting brightness.
#define maxsteps 16 // Case statement wouldn't allow a variable.
uint8_t bgcol = 0; // Background colour rotates.
int thisdelay = 20; // Standard delay value.
//DOTS
uint8_t count = 0; // Count up to 255 and then reverts to 0
uint8_t fadeval = 224; // Trail behind the LED's. Lower => faster fade.
uint8_t bpm = 30;
//LIGHTNING
uint8_t frequency = 50; // controls the interval between strikes
uint8_t flashes = 8; //the upper limit of flashes per strike
unsigned int dimmer = 1;
uint8_t ledstart; // Starting location of a flash
uint8_t ledlen;
int lightningcounter = 0;
//FUNKBOX
int idex = 0; //-LED INDEX (0 to NUM_LEDS-1
int TOP_INDEX = int(NUM_LEDS / 2);
int thissat = 255; //-FX LOOPS DELAY VAR
uint8_t thishuepolice = 0;
int antipodal_index(int i) {
int iN = i + TOP_INDEX;
if (i >= TOP_INDEX) {
iN = ( i + TOP_INDEX ) % NUM_LEDS;
}
return iN;
}
//FIRE
#define COOLING 55
#define SPARKING 120
bool gReverseDirection = false;
//BPM
uint8_t gHue = 0;
struct CRGB leds[NUM_LEDS];
////////////////////////////////////////////////////////////////////////////////////////////////
/* -- receive_message_callback --
* Callback method which executes upon receipt of a message originating from the IoT Hub in the cloud.
* Note: Modifying the contents of this method allows one to command the device from the cloud.
*/
static IOTHUBMESSAGE_DISPOSITION_RESULT receive_message_callback(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback)
{
int* counter = (int*)userContextCallback;
const unsigned char* buffer;
size_t size;
const char* messageId;
// Message properties
if ((messageId = IoTHubMessage_GetMessageId(message)) == NULL)
{
messageId = "<null>";
}
// Message content
if (IoTHubMessage_GetByteArray(message, (const unsigned char**)&buffer, &size) != IOTHUB_MESSAGE_OK)
{
LogInfo("unable to retrieve the message data\r\n");
}
else
{
/*buffer is not zero terminated*/
char *strMessage = (char *)malloc(size + 1);
if (strMessage == NULL)
{
return IOTHUBMESSAGE_ABANDONED;
}
strncpy(strMessage, (const char *)buffer, size);
strMessage[size] = '\0';
effectString = strMessage;
LogInfo("Received Message [%d]\r\n Message ID: %s\r\n Data: <<< %s >>> & Size=%d\r\n", *counter, messageId, buffer, (int)size);
free(strMessage);
// If we receive the word 'quit' then we stop running
if (size == (strlen(quit_msg) * sizeof(char)) && memcmp(buffer, quit_msg, size) == 0)
{
g_continueRunning = false;
}
}
/* Some device specific action code goes here... */
(*counter)++;
return IOTHUBMESSAGE_ACCEPTED;
}
/* -- send_confirm_callback --
* Callback method which executes upon confirmation that a message originating from this device has been received by the IoT Hub in the cloud.
*/
static void send_confirm_callback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
{
(void)userContextCallback;
// When a message is sent this callback will get evoked
g_message_count_send_confirmations++;
LogInfo("Confirmation callback received for message %lu with result %s\r\n", (unsigned long)g_message_count_send_confirmations, MU_ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
}
/* -- connection_status_callback --
* Callback method which executes on receipt of a connection status message from the IoT Hub in the cloud.
*/
static void connection_status_callback(IOTHUB_CLIENT_CONNECTION_STATUS result, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void* user_context)
{
(void)reason;
(void)user_context;
// This sample DOES NOT take into consideration network outages.
if (result == IOTHUB_CLIENT_CONNECTION_AUTHENTICATED)
{
LogInfo("The device client is connected to iothub\r\n");
}
else
{
LogInfo("The device client has been disconnected\r\n");
}
}
/* -- reset_esp_helper --
* waits for call of exit_msg over Serial line to reset device
*/
static void reset_esp_helper()
{
#ifdef is_esp_board
// Read from local serial
if (Serial.available()){
String s1 = Serial.readStringUntil('\n');// s1 is String type variable.
Serial.print("Received Data (serial): ");
Serial.println(s1);//display same received Data back in serial monitor.
// Restart device upon receipt of 'exit' call.
int e_start = s1.indexOf('e');
String ebit = (String) s1.substring(e_start, e_start+4);
if(ebit == exit_msg)
{
ESP.restart();
}
}
#endif // is_esp_board
}
/* -- run_demo --
* Runs active task of sending telemetry to IoTHub
* WARNING: only call this function once, as it includes steps to destroy handles and clean up at the end.
*/
static void run_demo()
{
int result = 0;
// action phase of the program, sending messages to the IoT Hub in the cloud.
do
{
if (messages_sent < MESSAGE_COUNT)
{
// Construct the iothub message from a string or a byte array
message_handle = IoTHubMessage_CreateFromString(telemetry_msg);
//message_handle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText)));
// Set Message property
/*(void)IoTHubMessage_SetMessageId(message_handle, "MSG_ID");
(void)IoTHubMessage_SetCorrelationId(message_handle, "CORE_ID");
(void)IoTHubMessage_SetContentTypeSystemProperty(message_handle, "application%2fjson");
(void)IoTHubMessage_SetContentEncodingSystemProperty(message_handle, "utf-8");*/
// Add custom properties to message
// (void)IoTHubMessage_SetProperty(message_handle, "property_key", "property_value");
LogInfo("Sending message %d to IoTHub\r\n", (int)(messages_sent + 1));
result = IoTHubDeviceClient_LL_SendEventAsync(device_ll_handle, message_handle, send_confirm_callback, NULL);
// The message is copied to the sdk so the we can destroy it
IoTHubMessage_Destroy(message_handle);
messages_sent++;
}
else if (g_message_count_send_confirmations >= MESSAGE_COUNT)
{
// After all messages are all received stop running
g_continueRunning = false;
}
IoTHubDeviceClient_LL_DoWork(device_ll_handle);
ThreadAPI_Sleep(3);
reset_esp_helper();
} while (g_continueRunning);
// Clean up the iothub sdk handle
IoTHubDeviceClient_LL_Destroy(device_ll_handle);
// Free all the sdk subsystem
IoTHub_Deinit();
LogInfo("done with sending");
return;
}
void setup() {
// Select the Protocol to use with the connection
#ifdef SAMPLE_MQTT
IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = MQTT_Protocol;
#endif // SAMPLE_MQTT
#ifdef SAMPLE_HTTP
IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol = HTTP_Protocol;
#endif // SAMPLE_HTTP
sample_init(ssid, pass);
FastLED.addLeds<CHIPSET, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
setupStripedPalette( CRGB::Red, CRGB::Red, CRGB::White, CRGB::White); //for CANDY CANE
gPal = HeatColors_p; //for FIRE
// Used to initialize IoTHub SDK subsystem
(void)IoTHub_Init();
// Create the iothub handle here
device_ll_handle = IoTHubDeviceClient_LL_CreateFromConnectionString(connectionString, protocol);
LogInfo("Creating IoTHub Device handle\r\n");
if (device_ll_handle == NULL)
{
LogInfo("Error AZ002: Failure creating Iothub device. Hint: Check you connection string.\r\n");
}
else
{
// Set any option that are necessary.
// For available options please see the iothub_sdk_options.md documentation in the main C SDK
// turn off diagnostic sampling
int diag_off = 0;
IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_DIAGNOSTIC_SAMPLING_PERCENTAGE, &diag_off);
#ifndef SAMPLE_HTTP
// Example sdk status tracing for troubleshooting
bool traceOn = true;
IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_LOG_TRACE, &traceOn);
#endif // SAMPLE_HTTP
// Setting the Trusted Certificate.
IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_TRUSTED_CERT, certificates);
#if defined SAMPLE_MQTT
//Setting the auto URL Encoder (recommended for MQTT). Please use this option unless
//you are URL Encoding inputs yourself.
//ONLY valid for use with MQTT
bool urlEncodeOn = true;
IoTHubDeviceClient_LL_SetOption(device_ll_handle, OPTION_AUTO_URL_ENCODE_DECODE, &urlEncodeOn);
/* Setting Message call back, so we can receive Commands. */
if (IoTHubClient_LL_SetMessageCallback(device_ll_handle, receive_message_callback, &receiveContext) != IOTHUB_CLIENT_OK)
{
LogInfo("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n");
}
#endif // SAMPLE_MQTT
// Setting connection status callback to get indication of connection to iothub
(void)IoTHubDeviceClient_LL_SetConnectionStatusCallback(device_ll_handle, connection_status_callback, NULL);
}
realRed = map(red, 0, 255, 0, brightness);
realGreen = map(green, 0, 255, 0, brightness);
realBlue = map(blue, 0, 255, 0, brightness);
}
void loop(void)
{
// if (g_run_demo)
// {
// run_demo();
// g_run_demo = false;
// }
IoTHubDeviceClient_LL_DoWork(device_ll_handle);
ThreadAPI_Sleep(3);
// startFade = true;
// inFade = false; // Kill the current fade
// if (stateOn) {
// realRed = map(red, 0, 255, 0, brightness);
// realGreen = map(green, 0, 255, 0, brightness);
// realBlue = map(blue, 0, 255, 0, brightness);
// }
// else {
// realRed = 0;
// realGreen = 0;
// realBlue = 0;
// }
led_loop();
// setColor(255,255,255);
reset_esp_helper();
}