diff --git a/examples/CrossListening/CrossListening-esp32/CrossListening-esp32.ino b/examples/CrossListening/CrossListening-esp32/CrossListening-esp32.ino index 48d38a7..daf5c31 100644 --- a/examples/CrossListening/CrossListening-esp32/CrossListening-esp32.ino +++ b/examples/CrossListening/CrossListening-esp32/CrossListening-esp32.ino @@ -28,8 +28,8 @@ String apiKey = "YOUR-PROJECT-APIKEY"; String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Handles our 5 second timer in loop(). unsigned long currentTime = millis(); @@ -49,11 +49,12 @@ void startWiFi(void); // Handles Grandeur connection/disconnection events. void GrandeurConnectionCallback(bool state); // Data get/set/update callback functions: -void initializeStatePin(const char* code, bool state); -void setStatePinToNewValue(const char* path, bool state); -void afterVoltageIsUpdated(const char* code, int voltage); +void initializeStatePin(const char *code, bool state); +void setStatePinToNewValue(const char *path, bool state); +void afterVoltageIsUpdated(const char *code, int voltage); -void setup() { +void setup() +{ .begin(9600); startWiFi(); // This initializes the SDK's configurations and returns reference to your project. @@ -69,11 +70,14 @@ void setup() { Serial.println("Listening for state update from Grandeur..."); } -void loop() { +void loop() +{ // In this loop() function, after every five seconds, we send the updated values of our // device's voltage to Grandeur. - if(project.isConnected()) { - if(millis() - currentTime >= 5000) { + if (project.isConnected()) + { + if (millis() - currentTime >= 5000) + { // This if-condition makes sure that the code inside this block runs only after // every five seconds. @@ -89,25 +93,30 @@ void loop() { } // This runs the SDK only when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void WiFiEventCallback(WiFiEvent_t event) { - switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - break; - default: break; +void WiFiEventCallback(WiFiEvent_t event) +{ + switch (event) + { + case SYSTEM_EVENT_STA_GOT_IP: + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + break; + default: + break; } } -void startWiFi(void) { +void startWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers @@ -119,29 +128,33 @@ void startWiFi(void) { Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void GrandeurConnectionCallback(bool status) { - switch(status) { - case CONNECTED: // Expands to true. - Serial.println("Device is connected with Grandeur."); - // On successful connection with Grandeur, we initialize the device's *state*. - // To do that, we get device state from Grandeur and set the *state pin* to its - // value. - data.get("state", initializeStatePin); - - // Initializing the millis counter for the five - // seconds timer. - currentTime = millis(); - break; - case DISCONNECTED: // Expands to false. - Serial.println("Device's connection with Grandeur is broken."); - break; +void GrandeurConnectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: // Expands to true. + Serial.println("Device is connected with Grandeur."); + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we get device state from Grandeur and set the *state pin* to its + // value. + data.get("state", initializeStatePin); + + // Initializing the millis counter for the five + // seconds timer. + currentTime = millis(); + break; + case DISCONNECTED: // Expands to false. + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void initializeStatePin(const char* code, bool state) { +void initializeStatePin(const char *code, bool state) +{ // This function sets the *state pin* to the *state value* that we received in data // from Grandeur. - if(strcmp(code, "DEVICE-DATA-FETCHED") == 0) { + if (strcmp(code, "DEVICE-DATA-FETCHED") == 0) + { Serial.printf("State is: %d\n", state); digitalWrite(statePin, state); return; @@ -151,16 +164,19 @@ void initializeStatePin(const char* code, bool state) { return; } -void setStatePinToNewValue(const char* path, bool state) { +void setStatePinToNewValue(const char *path, bool state) +{ // This function sets the *state pin* to state value. Serial.printf("Updated State is: %d\n", state); digitalWrite(statePin, state); } -void afterVoltageIsUpdated(const char* code, int voltage) { - if(strcmp(code, "DEVICE-DATA-UPDATED") == 0) { +void afterVoltageIsUpdated(const char *code, int voltage) +{ + if (strcmp(code, "DEVICE-DATA-UPDATED") == 0) + { Serial.printf("Voltage is updated to: %d\n", voltage); - + /* You can set some pins or trigger events here which depend on successful ** voltage update. */ diff --git a/examples/CrossListening/CrossListening-esp8266/CrossListening-esp8266.ino b/examples/CrossListening/CrossListening-esp8266/CrossListening-esp8266.ino index a80827a..45213c8 100644 --- a/examples/CrossListening/CrossListening-esp8266/CrossListening-esp8266.ino +++ b/examples/CrossListening/CrossListening-esp8266/CrossListening-esp8266.ino @@ -28,8 +28,8 @@ String apiKey = "YOUR-PROJECT-APIKEY"; String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Handles our 5 second timer in loop(). unsigned long currentTime = millis(); @@ -50,11 +50,12 @@ void startWiFi(void); // Handles Grandeur connection/disconnection events. void GrandeurConnectionCallback(bool state); // Data get/set/update callback functions: -void initializeStatePin(const char* code, bool state); -void setStatePinToNewValue(const char* path, bool state); -void afterVoltageIsUpdated(const char* code, int voltage); +void initializeStatePin(const char *code, bool state); +void setStatePinToNewValue(const char *path, bool state); +void afterVoltageIsUpdated(const char *code, int voltage); -void setup() { +void setup() +{ Serial.begin(9600); startWiFi(); // This initializes the SDK's configurations and returns reference to your project. @@ -70,11 +71,14 @@ void setup() { Serial.println("Listening for state update from Grandeur..."); } -void loop() { +void loop() +{ // In this loop() function, after every five seconds, we send the updated values of our // device's voltage to Grandeur. - if(project.isConnected()) { - if(millis() - currentTime >= 5000) { + if (project.isConnected()) + { + if (millis() - currentTime >= 5000) + { // This if-condition makes sure that the code inside this block runs only after // every five seconds. @@ -90,52 +94,60 @@ void loop() { } // This runs the SDK only when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void startWiFi(void) { +void startWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers WiFi.mode(WIFI_STA); // Setting WiFi event handlers - onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& event) { - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - }); - onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& event) { - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - }); + onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP &event) + { + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + }); + onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected &event) + { + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + }); // Begin connecting to WiFi WiFi.begin(ssid, passphrase); Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid.c_str(), passphrase.c_str()); } -void GrandeurConnectionCallback(bool status) { - switch(status) { - case CONNECTED: // Expands to true. - Serial.println("Device is connected with Grandeur."); - // On successful connection with Grandeur, we initialize the device's *state*. - // To do that, we get device state from Grandeur and set the *state pin* to its - // value. - data.get("state", initializeStatePin); - - // Initializing the millis counter for the five - // seconds timer. - currentTime = millis(); - break; - case DISCONNECTED: // Expands to false. - Serial.println("Device's connection with Grandeur is broken."); - break; +void GrandeurConnectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: // Expands to true. + Serial.println("Device is connected with Grandeur."); + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we get device state from Grandeur and set the *state pin* to its + // value. + data.get("state", initializeStatePin); + + // Initializing the millis counter for the five + // seconds timer. + currentTime = millis(); + break; + case DISCONNECTED: // Expands to false. + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void initializeStatePin(const char* code, bool state) { +void initializeStatePin(const char *code, bool state) +{ // This function sets the *state pin* to the *state value* that we received in data // from Grandeur. - if(strcmp(code, "DEVICE-DATA-FETCHED") == 0) { + if (strcmp(code, "DEVICE-DATA-FETCHED") == 0) + { Serial.printf("State is: %d\n", state); digitalWrite(statePin, state); return; @@ -145,16 +157,19 @@ void initializeStatePin(const char* code, bool state) { return; } -void setStatePinToNewValue(const char* path, bool state) { +void setStatePinToNewValue(const char *path, bool state) +{ // This function sets the *state pin* to state value. Serial.printf("Updated State is: %d\n", state); digitalWrite(statePin, state); } -void afterVoltageIsUpdated(const char* code, int voltage) { - if(strcmp(code, "DEVICE-DATA-UPDATED") == 0) { +void afterVoltageIsUpdated(const char *code, int voltage) +{ + if (strcmp(code, "DEVICE-DATA-UPDATED") == 0) + { Serial.printf("Voltage is updated to: %d\n", voltage); - + /* You can set some pins or trigger events here which depend on successful ** voltage update. */ diff --git a/examples/DashListening-App/DashListening-App-esp32/DashListening-App-esp32.ino b/examples/DashListening-App/DashListening-App-esp32/DashListening-App-esp32.ino index f7dc00a..397b45a 100644 --- a/examples/DashListening-App/DashListening-App-esp32/DashListening-App-esp32.ino +++ b/examples/DashListening-App/DashListening-App-esp32/DashListening-App-esp32.ino @@ -25,8 +25,8 @@ String apiKey = "YOUR-PROJECT-APIKEY"; String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Handles our 5 second timer in loop(). unsigned long currentTime = millis(); @@ -46,9 +46,10 @@ void startWiFi(void); // Handles Grandeur connection/disconnection events. void GrandeurConnectionCallback(bool state); // Function to call when acknowledgement for voltage update arrives from Grandeur. -void afterVoltageIsUpdated(const char* code, int voltage); +void afterVoltageIsUpdated(const char *code, int voltage); -void setup() { +void setup() +{ Serial.begin(9600); startWiFi(); // This initializes the SDK's configurations and returns reference to your project. @@ -60,11 +61,14 @@ void setup() { project.onConnection(GrandeurConnectionCallback); } -void loop() { +void loop() +{ // In this loop() function, after every five seconds, we send the updated values of our // device's voltage to Grandeur. - if(project.isConnected()) { - if(millis() - currentTime >= 5000) { + if (project.isConnected()) + { + if (millis() - currentTime >= 5000) + { // This if-condition makes sure that the code inside this block runs only after // every five seconds. @@ -80,25 +84,30 @@ void loop() { } // This runs the SDK only when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void WiFiEventCallback(WiFiEvent_t event) { - switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - break; - default: break; +void WiFiEventCallback(WiFiEvent_t event) +{ + switch (event) + { + case SYSTEM_EVENT_STA_GOT_IP: + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + break; + default: + break; } } -void startWiFi(void) { +void startWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers @@ -110,25 +119,29 @@ void startWiFi(void) { Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void GrandeurConnectionCallback(bool status) { - switch(status) { - case CONNECTED: // Expands to true. - Serial.println("Device is connected with Grandeur."); +void GrandeurConnectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: // Expands to true. + Serial.println("Device is connected with Grandeur."); - // Initializing the millis counter for the five - // seconds timer. - currentTime = millis(); - break; - case DISCONNECTED: // Expands to false. - Serial.println("Device's connection with Grandeur is broken."); - break; + // Initializing the millis counter for the five + // seconds timer. + currentTime = millis(); + break; + case DISCONNECTED: // Expands to false. + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void afterVoltageIsUpdated(const char* code, int voltage) { - if(strcmp(code, "DEVICE-DATA-UPDATED") == 0) { +void afterVoltageIsUpdated(const char *code, int voltage) +{ + if (strcmp(code, "DEVICE-DATA-UPDATED") == 0) + { Serial.printf("Voltage is updated to: %d\n", voltage); - + /* You can set some pins or trigger events here which depend on successful ** voltage update. */ diff --git a/examples/DashListening-App/DashListening-App-esp8266/DashListening-App-esp8266.ino b/examples/DashListening-App/DashListening-App-esp8266/DashListening-App-esp8266.ino index 77ab57d..7c35207 100644 --- a/examples/DashListening-App/DashListening-App-esp8266/DashListening-App-esp8266.ino +++ b/examples/DashListening-App/DashListening-App-esp8266/DashListening-App-esp8266.ino @@ -25,8 +25,8 @@ String apiKey = "YOUR-PROJECT-APIKEY"; String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Handles our 5 second timer in loop(). unsigned long currentTime = millis(); @@ -35,37 +35,47 @@ Grandeur::Project project; // Device data object to get/set/subscribe to device variables. Grandeur::Project::Device::Data data; // State and voltage pins to set. -int statePin = 4; -int voltagePin = 2; +int statePin = D0; +int voltagePin = A0; // FUNCTION PROTOTYPES: -// Handles WiFi connection/disconnection events. +// These handle WiFi connection/disconnection events. WiFiEventHandler onWiFiConnectedHandler; WiFiEventHandler onWiFiDisconnectedHandler; // Starts the device WiFi. void startWiFi(void); // Handles Grandeur connection/disconnection events. void GrandeurConnectionCallback(bool state); -// Function to call when acknowledgement for voltage update arrives from Grandeur. -void afterVoltageIsUpdated(const char* code, int voltage); +// Data get/set/update callback functions: +void initializeStatePin(const char *code, bool state); +void setStatePinToNewValue(const char *path, bool state); +void afterVoltageIsUpdated(const char *code, int voltage); -void setup() { +void setup() +{ Serial.begin(9600); startWiFi(); // This initializes the SDK's configurations and returns reference to your project. project = grandeur.init(apiKey, token); // Getting object of your device data. data = project.device(deviceID).data(); - // This schedules the GrandeurConnectionCallback() function to be called when connection with Grandeur + // This schedules the connectionCallback() function to be called when connection with Grandeur // is made/broken. project.onConnection(GrandeurConnectionCallback); + // This schedules setStatePinToNewValue() function to be called when a change in device state occurs + // on Grandeur. + data.on("state", setStatePinToNewValue); + Serial.println("Listening for state update from Grandeur..."); } -void loop() { +void loop() +{ // In this loop() function, after every five seconds, we send the updated values of our // device's voltage to Grandeur. - if(project.isConnected()) { - if(millis() - currentTime >= 5000) { + if (project.isConnected()) + { + if (millis() - currentTime >= 5000) + { // This if-condition makes sure that the code inside this block runs only after // every five seconds. @@ -81,48 +91,82 @@ void loop() { } // This runs the SDK only when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void startWiFi(void) { +void startWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers WiFi.mode(WIFI_STA); // Setting WiFi event handlers - onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& event) { - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - }); - onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& event) { - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - }); + onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP &event) + { + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + }); + onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected &event) + { + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + }); // Begin connecting to WiFi WiFi.begin(ssid, passphrase); - Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid.c_str(), passphrase.c_str()); + Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void GrandeurConnectionCallback(bool status) { - switch(status) { - case CONNECTED: // Expands to true. - Serial.println("Device is connected with Grandeur."); +void GrandeurConnectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: // Expands to true. + Serial.println("Device is connected with Grandeur."); + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we get device state from Grandeur and set the *state pin* to its + // value. + data.get("state", initializeStatePin); - // Initializing the millis counter for the five - // seconds timer. - currentTime = millis(); - break; - case DISCONNECTED: // Expands to false. - Serial.println("Device's connection with Grandeur is broken."); - break; + // Initializing the millis counter for the five + // seconds timer. + currentTime = millis(); + break; + case DISCONNECTED: // Expands to false. + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void afterVoltageIsUpdated(const char* code, int voltage) { - if(strcmp(code, "DEVICE-DATA-UPDATED") == 0) { +void initializeStatePin(const char *code, bool state) +{ + // This function sets the *state pin* to the *state value* that we received in data + // from Grandeur. + if (strcmp(code, "DEVICE-DATA-FETCHED") == 0) + { + Serial.printf("State is: %d\n", state); + digitalWrite(statePin, state); + return; + } + // If the data could not be fetched. + Serial.println("Failed to Fetch State"); + return; +} + +void setStatePinToNewValue(const char *path, bool state) +{ + // This function sets the *state pin* to state value. + Serial.printf("Updated State is: %d\n", state); + digitalWrite(statePin, state); +} + +void afterVoltageIsUpdated(const char *code, int voltage) +{ + if (strcmp(code, "DEVICE-DATA-UPDATED") == 0) + { Serial.printf("Voltage is updated to: %d\n", voltage); - + /* You can set some pins or trigger events here which depend on successful ** voltage update. */ diff --git a/examples/DashListening-Device/DashListening-Device-esp32/DashListening-Device-esp32.ino b/examples/DashListening-Device/DashListening-Device-esp32/DashListening-Device-esp32.ino index a9ee703..3560d0b 100644 --- a/examples/DashListening-Device/DashListening-Device-esp32/DashListening-Device-esp32.ino +++ b/examples/DashListening-Device/DashListening-Device-esp32/DashListening-Device-esp32.ino @@ -25,8 +25,8 @@ String apiKey = "YOUR-PROJECT-APIKEY"; String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Handles our 5 second timer in loop(). unsigned long currentTime = millis(); @@ -45,10 +45,11 @@ void startWiFi(void); // Handles Grandeur connection/disconnection events. void GrandeurConnectionCallback(bool state); // Data get/set/update callback functions: -void initializeStatePin(const char* code, bool state); -void setStatePinToNewValue(const char* path, bool state); +void initializeStatePin(const char *code, bool state); +void setStatePinToNewValue(const char *path, bool state); -void setup() { +void setup() +{ Serial.begin(9600); startWiFi(); // This initializes the SDK's configurations and returns reference to your project. @@ -63,27 +64,33 @@ void setup() { data.on("state", setStatePinToNewValue); } -void loop() { +void loop() +{ // The SDK only runs when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void WiFiEventCallback(WiFiEvent_t event) { - switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - break; - default: break; +void WiFiEventCallback(WiFiEvent_t event) +{ + switch (event) + { + case SYSTEM_EVENT_STA_GOT_IP: + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + break; + default: + break; } } -void startWiFi(void) { +void startWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers @@ -95,30 +102,34 @@ void startWiFi(void) { Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void GrandeurConnectionCallback(bool status) { - switch(status) { - case CONNECTED: // Expands to true. - Serial.println("Device is connected with Grandeur."); - // On successful connection with Grandeur, we initialize the device's *state*. - // To do that, we get device state from Grandeur and set the *state pin* to its - // value. - data.get("state", initializeStatePin); - Serial.println("Listening for state update from Grandeur..."); +void GrandeurConnectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: // Expands to true. + Serial.println("Device is connected with Grandeur."); + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we get device state from Grandeur and set the *state pin* to its + // value. + data.get("state", initializeStatePin); + Serial.println("Listening for state update from Grandeur..."); - // Initializing the millis counter for the five - // seconds timer. - currentTime = millis(); - break; - case DISCONNECTED: // Expands to false. - Serial.println("Device's connection with Grandeur is broken."); - break; + // Initializing the millis counter for the five + // seconds timer. + currentTime = millis(); + break; + case DISCONNECTED: // Expands to false. + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void initializeStatePin(const char* code, bool state) { +void initializeStatePin(const char *code, bool state) +{ // This function sets the *state pin* to the *state value* that we received in data // from Grandeur. - if(code == "DEVICE-DATA-FETCHED") { + if (code == "DEVICE-DATA-FETCHED") + { Serial.printf("State is: %d\n", state); digitalWrite(statePin, state); return; @@ -128,7 +139,8 @@ void initializeStatePin(const char* code, bool state) { return; } -void setStatePinToNewValue(const char* path, bool state) { +void setStatePinToNewValue(const char *path, bool state) +{ // This function sets the *state pin* to state value. Serial.printf("Updated State is: %d\n", state); digitalWrite(statePin, state); diff --git a/examples/DashListening-Device/DashListening-Device-esp8266/DashListening-Device-esp8266.ino b/examples/DashListening-Device/DashListening-Device-esp8266/DashListening-Device-esp8266.ino index d8e2d9b..f980bfe 100644 --- a/examples/DashListening-Device/DashListening-Device-esp8266/DashListening-Device-esp8266.ino +++ b/examples/DashListening-Device/DashListening-Device-esp8266/DashListening-Device-esp8266.ino @@ -24,8 +24,8 @@ String apiKey = "YOUR-PROJECT-APIKEY"; String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Handles our 5 second timer in loop(). unsigned long currentTime = millis(); @@ -45,10 +45,11 @@ void startWiFi(void); // Handles Grandeur connection/disconnection events. void GrandeurConnectionCallback(bool state); // Data get/set/update callback functions: -void initializeStatePin(const char* code, bool state); -void setStatePinToNewValue(const char* path, bool state); +void initializeStatePin(const char *code, bool state); +void setStatePinToNewValue(const char *path, bool state); -void setup() { +void setup() +{ Serial.begin(9600); startWiFi(); // This initializes the SDK's configurations and returns reference to your project. @@ -63,55 +64,64 @@ void setup() { data.on("state", setStatePinToNewValue); } -void loop() { +void loop() +{ // The SDK only runs when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void setupWiFi(void) { +void startWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers WiFi.mode(WIFI_STA); // Setting WiFi event handlers - onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& event) { - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - }); - onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& event) { - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - }); + onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP &event) + { + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + }); + onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected &event) + { + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + }); // Begin connecting to WiFi WiFi.begin(ssid, passphrase); - Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid.c_str(), passphrase.c_str()); + Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void GrandeurConnectionCallback(bool status) { - switch(status) { - case CONNECTED: // Expands to true. - Serial.println("Device is connected with Grandeur."); - // On successful connection with Grandeur, we initialize the device's *state*. - // To do that, we get device state from Grandeur and set the *state pin* to its - // value. - data.get("state", initializeStatePin); - Serial.println("Listening for state update from Grandeur..."); +void GrandeurConnectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: // Expands to true. + Serial.println("Device is connected with Grandeur."); + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we get device state from Grandeur and set the *state pin* to its + // value. + data.get("state", initializeStatePin); + Serial.println("Listening for state update from Grandeur..."); - // Initializing the millis counter for the five - // seconds timer. - currentTime = millis(); - break; - case DISCONNECTED: // Expands to false. - Serial.println("Device's connection with Grandeur is broken."); - break; + // Initializing the millis counter for the five + // seconds timer. + currentTime = millis(); + break; + case DISCONNECTED: // Expands to false. + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void initializeStatePin(const char* code, bool state) { +void initializeStatePin(const char *code, bool state) +{ // This function sets the *state pin* to the *state value* that we received in data // from Grandeur. - if(code == "DEVICE-DATA-FETCHED") { + if (code == "DEVICE-DATA-FETCHED") + { Serial.printf("State is: %d\n", state); digitalWrite(statePin, state); return; @@ -121,7 +131,8 @@ void initializeStatePin(const char* code, bool state) { return; } -void setStatePinToNewValue(const char* path, bool state) { +void setStatePinToNewValue(const char *path, bool state) +{ // This function sets the *state pin* to state value. Serial.printf("Updated State is: %d\n", state); digitalWrite(statePin, state); diff --git a/examples/Datastore/Logging/Logging-esp32/Logging-esp32.ino b/examples/Datastore/Logging/Logging-esp32/Logging-esp32.ino index 79119f3..dabf7dd 100644 --- a/examples/Datastore/Logging/Logging-esp32/Logging-esp32.ino +++ b/examples/Datastore/Logging/Logging-esp32/Logging-esp32.ino @@ -19,8 +19,8 @@ // Device's connection configurations String apiKey = "YOUR-PROJECT-APIKEY"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Declaring and initializing other variables Grandeur::Project myProject; @@ -32,9 +32,10 @@ unsigned long current = millis(); void WiFiEventCallback(WiFiEvent_t event); void setupWiFi(void); void connectionCallback(bool status); -void insertCallback(const char* code); +void insertCallback(const char *code); -void setup() { +void setup() +{ Serial.begin(9600); // This sets up the device WiFi. setupWiFi(); @@ -47,9 +48,12 @@ void setup() { myProject.onConnection(connectionCallback); } -void loop() { - if(myProject.isConnected()) { - if(millis() - current >= 5000) { +void loop() +{ + if (myProject.isConnected()) + { + if (millis() - current >= 5000) + { // This if-condition makes sure that the code inside this block runs only after // every five seconds. Var logs; @@ -60,27 +64,32 @@ void loop() { current = millis(); } } - + // The SDK only runs when the WiFi is connected. - myProject.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void WiFiEventCallback(WiFiEvent_t event) { - switch(event) { - case SYSTEM_EVENT_STA_GOT_IP: - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - break; - default: break; +void WiFiEventCallback(WiFiEvent_t event) +{ + switch (event) + { + case SYSTEM_EVENT_STA_GOT_IP: + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + break; + default: + break; } } -void setupWiFi(void) { +void setupWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers @@ -92,23 +101,27 @@ void setupWiFi(void) { Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void connectionCallback(bool status) { - switch(status) { - case CONNECTED: - // On successful connection with Grandeur, we initialize the device's *state*. - // To do that, we set the *state pin* to the value of *state* from Grandeur. - Serial.println("Device is connected with Grandeur."); - Serial.println("Logging voltage to Grandeur..."); - break; - case DISCONNECTED: - Serial.println("Device's connection with Grandeur is broken."); - break; +void connectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we set the *state pin* to the value of *state* from Grandeur. + Serial.println("Device is connected with Grandeur."); + Serial.println("Logging voltage to Grandeur..."); + break; + case DISCONNECTED: + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void insertCallback(const char* code) { +void insertCallback(const char *code) +{ // This function prints if the logs were successfully inserted into the datastore or not. - if(strcmp(code, "DATASTORE-DOCUMENTS-INSERTED") == 0) { + if (strcmp(code, "DATASTORE-DOCUMENTS-INSERTED") == 0) + { Serial.printf("Voltage is successfully logged to Grandeur."); return; } diff --git a/examples/Datastore/Logging/Logging-esp8266/Logging-esp8266.ino b/examples/Datastore/Logging/Logging-esp8266/Logging-esp8266.ino index dca3f3c..f7dee4b 100644 --- a/examples/Datastore/Logging/Logging-esp8266/Logging-esp8266.ino +++ b/examples/Datastore/Logging/Logging-esp8266/Logging-esp8266.ino @@ -18,9 +18,10 @@ // Device's connection configurations String apiKey = "YOUR-PROJECT-APIKEY"; +String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -String ssid = "YOUR-WIFI-SSID"; -String passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Declaring and initializing other variables Grandeur::Project myProject; @@ -33,9 +34,10 @@ unsigned long current = millis(); // Function prototypes void setupWiFi(void); void connectionCallback(bool status); -void insertCallback(const char* code); +void insertCallback(const char *code); -void setup() { +void setup() +{ Serial.begin(9600); // This sets up the device WiFi. setupWiFi(); @@ -48,9 +50,12 @@ void setup() { myProject.onConnection(connectionCallback); } -void loop() { - if(myProject.isConnected()) { - if(millis() - current >= 5000) { +void loop() +{ + if (myProject.isConnected()) + { + if (millis() - current >= 5000) + { // This if-condition makes sure that the code inside this block runs only after // every five seconds. Var logs; @@ -61,49 +66,57 @@ void loop() { current = millis(); } } - + // The SDK only runs when the WiFi is connected. - myProject.loop(WiFi.status() == WL_CONNECTED); + if (WiFi.status() == WL_CONNECTED) + project.loop(); } -void setupWiFi(void) { +void setupWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers WiFi.mode(WIFI_STA); // Setting WiFi event handlers - onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& event) { - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - }); - onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& event) { - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - }); + onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP &event) + { + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + }); + onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected &event) + { + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + }); // Begin connecting to WiFi WiFi.begin(ssid, passphrase); - Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid.c_str(), passphrase.c_str()); + Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void connectionCallback(bool status) { - switch(status) { - case CONNECTED: - // On successful connection with Grandeur, we initialize the device's *state*. - // To do that, we set the *state pin* to the value of *state* from Grandeur. - Serial.println("Device is connected with Grandeur."); - Serial.println("Logging voltage to Grandeur..."); - break; - case DISCONNECTED: - Serial.println("Device's connection with Grandeur is broken."); - break; +void connectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we set the *state pin* to the value of *state* from Grandeur. + Serial.println("Device is connected with Grandeur."); + Serial.println("Logging voltage to Grandeur..."); + break; + case DISCONNECTED: + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void insertCallback(const char* code) { +void insertCallback(const char *code) +{ // This function prints if the logs were successfully inserted into the datastore or not. - if(strcmp(code, "DATASTORE-DOCUMENTS-INSERTED") == 0) { - Serial.printf("Voltage is successfully logged to Grandeur."); + if (strcmp(code, "DATASTORE-DOCUMENTS-INSERTED") == 0) + { + Serial.printf("Voltage is successfully logged to Grandeur.\n"); return; } // If insertion is not successful. diff --git a/examples/Datastore/Searching/Searching-esp32/Searching-esp32.ino b/examples/Datastore/Searching/Searching-esp32/Searching-esp32.ino index 33cb1f4..4cb6c26 100644 --- a/examples/Datastore/Searching/Searching-esp32/Searching-esp32.ino +++ b/examples/Datastore/Searching/Searching-esp32/Searching-esp32.ino @@ -63,7 +63,7 @@ void loop() { } // The SDK only runs when the WiFi is connected. - myProject.loop(WiFi.status() == WL_CONNECTED); + if(WiFi.status() == WL_CONNECTED) project.loop(); } void WiFiEventCallback(WiFiEvent_t event) { diff --git a/examples/Datastore/Searching/Searching-esp8266/Searching-esp8266.ino b/examples/Datastore/Searching/Searching-esp8266/Searching-esp8266.ino index 9de8819..30ff895 100644 --- a/examples/Datastore/Searching/Searching-esp8266/Searching-esp8266.ino +++ b/examples/Datastore/Searching/Searching-esp8266/Searching-esp8266.ino @@ -33,9 +33,10 @@ unsigned long current = millis(); // Function prototypes void setupWiFi(void); void connectionCallback(bool status); -void searchCallback(const char* code, Var result); +void searchCallback(const char *code, Var result); -void setup() { +void setup() +{ Serial.begin(9600); // This sets up the device WiFi. setupWiFi(); @@ -48,9 +49,12 @@ void setup() { myProject.onConnection(connectionCallback); } -void loop() { - if(myProject.isConnected()) { - if(millis() - current >= 5000) { +void loop() +{ + if (myProject.isConnected()) + { + if (millis() - current >= 5000) + { // This if-condition makes sure that the code inside this block runs only after // every five seconds. // This fetches 1st page of all the documents stored in the datastore. @@ -60,57 +64,68 @@ void loop() { current = millis(); } } - + // The SDK only runs when the WiFi is connected. - myProject.loop(WiFi.status() == WL_CONNECTED); + if(WiFi.status() == WL_CONNECTED) project.loop(); } -void setupWiFi(void) { +void setupWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers WiFi.mode(WIFI_STA); // Setting WiFi event handlers - onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP& event) { - // This runs when the device connects with WiFi. - Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", - WiFi.localIP().toString().c_str()); - }); - onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected& event) { - // This runs when the device disconnects with WiFi. - Serial.println("Device is disconnected from WiFi."); - }); + onWiFiConnectedHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP &event) + { + // This runs when the device connects with WiFi. + Serial.printf("\nDevice has successfully connected to WiFi. Its IP Address is: %s\n", + WiFi.localIP().toString().c_str()); + }); + onWiFiDisconnectedHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected &event) + { + // This runs when the device disconnects with WiFi. + Serial.println("Device is disconnected from WiFi."); + }); // Begin connecting to WiFi WiFi.begin(ssid, passphrase); - Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid.c_str(), passphrase.c_str()); + Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); } -void connectionCallback(bool status) { - switch(status) { - case CONNECTED: - // On successful connection with Grandeur, we initialize the device's *state*. - // To do that, we set the *state pin* to the value of *state* from Grandeur. - Serial.println("Device is connected with Grandeur."); - Serial.println("Logging voltage to Grandeur..."); - break; - case DISCONNECTED: - Serial.println("Device's connection with Grandeur is broken."); - break; +void connectionCallback(bool status) +{ + switch (status) + { + case CONNECTED: + // On successful connection with Grandeur, we initialize the device's *state*. + // To do that, we set the *state pin* to the value of *state* from Grandeur. + Serial.println("Device is connected with Grandeur."); + Serial.println("Searching documents on Grandeur..."); + break; + case DISCONNECTED: + Serial.println("Device's connection with Grandeur is broken."); + break; } } -void searchCallback(const char* code, Var result) { +void searchCallback(const char *code, Var result) +{ // This function prints if the datastore search for the docs was successfully or not. - if(searchResult["code"] == "DATASTORE-DOCUMENTS-FETCHED") { - Serial.print("Documents fetched from Grandeur: "); - Serial.println(searchResult["documents"].size()); + if (strcmp(code, "DATASTORE-DOCUMENTS-FETCHED") == 0) + { + Serial.print("Total number of documents that matched the query: "); + Serial.println(result["nDocuments"]); + Serial.print("Number of documents fetched: "); // Will always be 20 if nDocuments > 20 + Serial.println(result["documents"].length()); + Serial.println("------------------------DOCUMENTS------------------------"); // Printing all the fetched documents. - for(int i = 0; i < searchResult["documents"].size(); i++) { - Serial.println(JSON.stringify(searchResult["documents"][i]).c_str()); + for (int i = 0; i < result["documents"].length(); i++) + { + Serial.println(JSON.stringify(result["documents"][i]).c_str()); // Just to keep the watchdog timer from tripping. delay(1); } - Serial.println(""); + Serial.println("---------------------------------------------------------"); return; } // If search is not successful. diff --git a/examples/HelloGrandeur/HelloGrandeur-esp32/HelloGrandeur-esp32.ino b/examples/HelloGrandeur/HelloGrandeur-esp32/HelloGrandeur-esp32.ino index 6ecc2bb..8972d69 100644 --- a/examples/HelloGrandeur/HelloGrandeur-esp32/HelloGrandeur-esp32.ino +++ b/examples/HelloGrandeur/HelloGrandeur-esp32/HelloGrandeur-esp32.ino @@ -57,7 +57,7 @@ void loop() { Serial.println("Also checkout other examples: \n- DashListening-Device \n- DashListening-App \n- CrossListening.\n"); } // This runs the SDK only when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if(WiFi.status() == WL_CONNECTED) project.loop(); } void startWiFi(void) { diff --git a/examples/HelloGrandeur/HelloGrandeur-esp8266/HelloGrandeur-esp8266.ino b/examples/HelloGrandeur/HelloGrandeur-esp8266/HelloGrandeur-esp8266.ino index 76bf5e9..c1a6a23 100644 --- a/examples/HelloGrandeur/HelloGrandeur-esp8266/HelloGrandeur-esp8266.ino +++ b/examples/HelloGrandeur/HelloGrandeur-esp8266/HelloGrandeur-esp8266.ino @@ -19,8 +19,8 @@ String apiKey = "YOUR-PROJECT-APIKEY"; String deviceID = "YOUR-DEVICE-ID"; String token = "YOUR-ACCESS-TOKEN"; -const char* ssid = "YOUR-WIFI-SSID"; -const char* passphrase = "YOUR-WIFI-PASSWORD"; +const char *ssid = "YOUR-WIFI-SSID"; +const char *passphrase = "YOUR-WIFI-PASSWORD"; // Object of Grandeur project. Grandeur::Project project; @@ -28,7 +28,8 @@ Grandeur::Project project; // Starts the device WiFi. void startWiFi(void); -void setup() { +void setup() +{ Serial.begin(9600); startWiFi(); // This initializes the SDK's configurations and returns a new object of Project class. @@ -36,8 +37,10 @@ void setup() { Serial.printf("\nDevice %s is saying hello to Grandeur using API Key %s and Access Token %s.\n", deviceID.c_str(), apiKey.c_str(), token.c_str()); } -void loop() { - if(project.isConnected()) { +void loop() +{ + if (project.isConnected()) + { // When the device's connection with Grandeur is established, this if-block runs. Serial.println("\nDevice has made a successful connection with Grandeur!"); Serial.println("Grandeur says hi. Grandeur will now respond to your commands..."); @@ -57,19 +60,21 @@ void loop() { Serial.println("Also checkout other examples: \n- DashListening-Device \n- DashListening-App \n- CrossListening.\n"); } // This runs the SDK only when the WiFi is connected. - project.loop(WiFi.status() == WL_CONNECTED); + if(WiFi.status() == WL_CONNECTED) project.loop(); } -void setupWiFi(void) { +void startWiFi(void) +{ // Disconnecting WiFi if it"s already connected WiFi.disconnect(); // Setting it to Station mode which basically scans for nearby WiFi routers WiFi.mode(WIFI_STA); // Begin connecting to WiFi WiFi.begin(ssid, passphrase); - Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid.c_str(), passphrase.c_str()); + Serial.printf("\nDevice is connecting to WiFi using SSID %s and Passphrase %s.\n", ssid, passphrase); // Device program gets in the while loop as long as the WiFi isn't connected. - while(WiFi.status() != WL_CONNECTED) { + while (WiFi.status() != WL_CONNECTED) + { delay(500); } // This gets printed after the WiFi is connected. diff --git a/library.properties b/library.properties index 9f76c7e..3de0426 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=Grandeur -version=1.0.4 +version=1.0.5 author=Grandeur Technologies maintainer=Grandeur Technologies sentence=Let your arduinos and ESPs communicate with Grandeur in realtime. diff --git a/src/Arduino_JSON/JSONVar.cpp b/src/Arduino_JSON/JSONVar.cpp index b0db585..4df37e0 100644 --- a/src/Arduino_JSON/JSONVar.cpp +++ b/src/Arduino_JSON/JSONVar.cpp @@ -21,64 +21,56 @@ #include "JSONVar.h" -JSONVar::JSONVar(struct cJSON* json, struct cJSON* parent) : - _json(json), - _parent(parent) +JSONVar::JSONVar(struct cJSON *json, struct cJSON *parent) : _json(json), + _parent(parent) { } -JSONVar::JSONVar(bool b) : - JSONVar() +JSONVar::JSONVar(bool b) : JSONVar() { *this = b; } -JSONVar::JSONVar(int i) : - JSONVar() +JSONVar::JSONVar(int i) : JSONVar() { *this = i; } -JSONVar::JSONVar(long l) : - JSONVar() +JSONVar::JSONVar(long l) : JSONVar() { *this = l; } -JSONVar::JSONVar(unsigned long ul) : - JSONVar() +JSONVar::JSONVar(unsigned long ul) : JSONVar() { *this = ul; } -JSONVar::JSONVar(double d) : - JSONVar() +JSONVar::JSONVar(double d) : JSONVar() { *this = d; } -JSONVar::JSONVar(const char* s) : - JSONVar() +JSONVar::JSONVar(const char *s) : JSONVar() { *this = s; } -JSONVar::JSONVar(const String& s) : - JSONVar() +JSONVar::JSONVar(const String &s) : JSONVar() { *this = s; } -JSONVar::JSONVar(const JSONVar& v) +JSONVar::JSONVar(const JSONVar &v) { _json = cJSON_Duplicate(v._json, true); _parent = NULL; } #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) -JSONVar::JSONVar(JSONVar&& v) +JSONVar::JSONVar(JSONVar &&v) { - cJSON* tmp; + cJSON *tmp; // swap _json tmp = _json; @@ -92,33 +84,33 @@ JSONVar::JSONVar(JSONVar&& v) } #endif -JSONVar::JSONVar(nullptr_t) : - JSONVar() +JSONVar::JSONVar(nullptr_t) : JSONVar() { *this = nullptr; } -JSONVar::JSONVar() : - JSONVar(NULL, NULL) +JSONVar::JSONVar() : JSONVar(NULL, NULL) { } JSONVar::~JSONVar() { - if (_json != NULL && _parent == NULL) { + if (_json != NULL && _parent == NULL) + { cJSON_Delete(_json); _json = NULL; } } -size_t JSONVar::printTo(Print& p) const +size_t JSONVar::printTo(Print &p) const { - if (_json == NULL) { + if (_json == NULL) + { return 0; } - char* s = cJSON_PrintUnformatted(_json); + char *s = cJSON_PrintUnformatted(_json); size_t writen = p.print(s); @@ -152,35 +144,42 @@ JSONVar::operator double() const return cJSON_IsNumber(_json) ? _json->valuedouble : NAN; } -JSONVar::operator const char*() const +JSONVar::operator const char *() const { - if (cJSON_IsString(_json)) { + if (cJSON_IsString(_json)) + { return _json->valuestring; } return NULL; } -void JSONVar::operator=(const JSONVar& v) +void JSONVar::operator=(const JSONVar &v) { - if (&v == &undefined) { - if (cJSON_IsObject(_parent)) { + if (&v == &undefined) + { + if (cJSON_IsObject(_parent)) + { cJSON_DeleteItemFromObjectCaseSensitive(_parent, _json->string); _json = NULL; _parent = NULL; - } else { + } + else + { replaceJson(cJSON_CreateNull()); } - } else { + } + else + { replaceJson(cJSON_Duplicate(v._json, true)); } } #if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__) -JSONVar& JSONVar::operator=(JSONVar&& v) +JSONVar &JSONVar::operator=(JSONVar &&v) { - cJSON* tmp; + cJSON *tmp; // swap _json tmp = _json; @@ -221,12 +220,12 @@ void JSONVar::operator=(double d) replaceJson(cJSON_CreateNumber(d)); } -void JSONVar::operator=(const char* s) +void JSONVar::operator=(const char *s) { replaceJson(cJSON_CreateString(s)); } -void JSONVar::operator=(const String& s) +void JSONVar::operator=(const String &s) { *this = s.c_str(); } @@ -236,16 +235,16 @@ void JSONVar::operator=(nullptr_t) replaceJson(cJSON_CreateNull()); } -bool JSONVar::operator==(const JSONVar& v) const +bool JSONVar::operator==(const JSONVar &v) const { return cJSON_Compare(_json, v._json, 1) || - (_json == NULL && v._json == NULL); + (_json == NULL && v._json == NULL); } -bool JSONVar::operator==(const char* v) const +bool JSONVar::operator==(const char *v) const { return cJSON_Compare(_json, JSONVar(v)._json, 1) || - (_json == NULL && JSONVar(v)._json == NULL); + (_json == NULL && JSONVar(v)._json == NULL); } bool JSONVar::operator==(nullptr_t) const @@ -253,36 +252,41 @@ bool JSONVar::operator==(nullptr_t) const return (cJSON_IsNull(_json)); } -JSONVar JSONVar::operator[](const char* key) +JSONVar JSONVar::operator[](const char *key) { - if (!cJSON_IsObject(_json)) { + if (!cJSON_IsObject(_json)) + { replaceJson(cJSON_CreateObject()); } - cJSON* json = cJSON_GetObjectItemCaseSensitive(_json, key); + cJSON *json = cJSON_GetObjectItemCaseSensitive(_json, key); - if (json == NULL) { + if (json == NULL) + { json = cJSON_AddNullToObject(_json, key); } - - return JSONVar(json, _json); + + return JSONVar(json, _json); } -JSONVar JSONVar::operator[](const String& key) +JSONVar JSONVar::operator[](const String &key) { return (*this)[key.c_str()]; } JSONVar JSONVar::operator[](int index) { - if (!cJSON_IsArray(_json)) { + if (!cJSON_IsArray(_json)) + { replaceJson(cJSON_CreateArray()); } - cJSON* json = cJSON_GetArrayItem(_json, index); + cJSON *json = cJSON_GetArrayItem(_json, index); - if (json == NULL) { - while (index >= cJSON_GetArraySize(_json)) { + if (json == NULL) + { + while (index >= cJSON_GetArraySize(_json)) + { json = cJSON_CreateNull(); cJSON_AddItemToArray(_json, json); @@ -292,16 +296,18 @@ JSONVar JSONVar::operator[](int index) return JSONVar(json, _json); } -JSONVar JSONVar::operator[](const JSONVar& key) +JSONVar JSONVar::operator[](const JSONVar &key) { - if (cJSON_IsArray(_json) && cJSON_IsNumber(key._json)) { + if (cJSON_IsArray(_json) && cJSON_IsNumber(key._json)) + { int index = (int)key; return (*this)[index]; } - if (cJSON_IsObject(_json) && cJSON_IsString(key._json)) { - const char* str = (const char*) key; + if (cJSON_IsObject(_json) && cJSON_IsString(key._json)) + { + const char *str = (const char *)key; return (*this)[str]; } @@ -311,68 +317,77 @@ JSONVar JSONVar::operator[](const JSONVar& key) int JSONVar::length() const { - if (cJSON_IsString(_json)) { + if (cJSON_IsString(_json)) + { return strlen(_json->string); - } else if (cJSON_IsArray(_json)) { + } + else if (cJSON_IsArray(_json)) + { return cJSON_GetArraySize(_json); - } else { + } + else + { return -1; } } JSONVar JSONVar::keys() const { - if (!cJSON_IsObject(_json)) { + if (!cJSON_IsObject(_json)) + { return JSONVar(NULL, NULL); } int length = cJSON_GetArraySize(_json); - const char* keys[length]; - cJSON* child = _json->child; + const char *keys[length]; + cJSON *child = _json->child; - for (int i = 0; i < length; i++, child = child->next) { + for (int i = 0; i < length; i++, child = child->next) + { keys[i] = child->string; } return JSONVar(cJSON_CreateStringArray(keys, length), NULL); } -bool JSONVar::hasOwnProperty(const char* key) const +bool JSONVar::hasOwnProperty(const char *key) const { - if (!cJSON_IsObject(_json)) { + if (!cJSON_IsObject(_json)) + { return false; } - cJSON* json = cJSON_GetObjectItemCaseSensitive(_json, key); + cJSON *json = cJSON_GetObjectItemCaseSensitive(_json, key); return (json != NULL); } -bool JSONVar::hasOwnProperty(const String& key) const +bool JSONVar::hasOwnProperty(const String &key) const { return hasOwnProperty(key.c_str()); } -JSONVar JSONVar::parse(const char* s) +JSONVar JSONVar::parse(const char *s) { - cJSON* json = cJSON_Parse(s); + cJSON *json = cJSON_Parse(s); return JSONVar(json, NULL); } -JSONVar JSONVar::parse(const String& s) +JSONVar JSONVar::parse(const String &s) { return parse(s.c_str()); } -String JSONVar::stringify(const JSONVar& value) +String JSONVar::stringify(const JSONVar &value) { - if (value._json == NULL) { + if (value._json == NULL) + { return String((const char *)NULL); } - char* s = cJSON_PrintUnformatted(value._json); + char *s = cJSON_PrintUnformatted(value._json); String str = s; @@ -381,43 +396,65 @@ String JSONVar::stringify(const JSONVar& value) return str; } -String JSONVar::typeof_(const JSONVar& value) +String JSONVar::typeof_(const JSONVar &value) { - struct cJSON* json = value._json; + struct cJSON *json = value._json; - if (json == NULL || cJSON_IsInvalid(json)) { + if (json == NULL || cJSON_IsInvalid(json)) + { return "undefined"; - } else if (cJSON_IsBool(json)) { + } + else if (cJSON_IsBool(json)) + { return "boolean"; - } else if (cJSON_IsNull(json)) { + } + else if (cJSON_IsNull(json)) + { return "null"; // TODO: should this return "object" to be more JS like? - } else if (cJSON_IsNumber(json)) { + } + else if (cJSON_IsNumber(json)) + { return "number"; - } else if (cJSON_IsString(json)) { + } + else if (cJSON_IsString(json)) + { return "string"; - } else if (cJSON_IsArray(json)) { + } + else if (cJSON_IsArray(json)) + { return "array"; // TODO: should this return "object" to be more JS like? - } else if (cJSON_IsObject(json)) { + } + else if (cJSON_IsObject(json)) + { return "object"; - } else { + } + else + { return "unknown"; } } -void JSONVar::replaceJson(struct cJSON* json) +void JSONVar::replaceJson(struct cJSON *json) { - cJSON* old = _json; + cJSON *old = _json; _json = json; - if (old) { - if (_parent) { - if (cJSON_IsObject(_parent)) { + if (old) + { + if (_parent) + { + if (cJSON_IsObject(_parent)) + { cJSON_ReplaceItemInObjectCaseSensitive(_parent, old->string, _json); - } else if (cJSON_IsArray(_parent)) { + } + else if (cJSON_IsArray(_parent)) + { cJSON_ReplaceItemViaPointer(_parent, old, _json); } - } else { + } + else + { cJSON_Delete(old); } } diff --git a/src/Callback.cpp b/src/Callback.cpp index 356ab8b..17522c1 100644 --- a/src/Callback.cpp +++ b/src/Callback.cpp @@ -7,19 +7,28 @@ #define DOUBLE 4 #define STRING 5 -const char* Callback::mapType(int type) { +const char *Callback::mapType(int type) +{ // Returns function type as string - switch(type) { - case NONE: return "none"; - case VAR: return "var"; - case BOOLEAN: return "boolean"; - case INTEGER: return "int"; - case DOUBLE: return "double"; - case STRING: return "string"; + switch (type) + { + case NONE: + return "none"; + case VAR: + return "var"; + case BOOLEAN: + return "boolean"; + case INTEGER: + return "int"; + case DOUBLE: + return "double"; + case STRING: + return "string"; } } -void Callback::printError(String type) { +void Callback::printError(String type) +{ // Prints error to Debug Port. DEBUG_GRANDEUR("[TYPE-ERROR] Was expecting %s and received %s\n", mapType(_type), type.c_str()); } @@ -28,106 +37,119 @@ Callback::Callback() : _functionPtr(NULL), _nArgs(0), _type(NONE) {} Callback::Callback(int ptr) : _functionPtr(NULL), _nArgs(0), _type(NONE) {} -Callback::Callback(void c(const char*)) : _nArgs(1), _type(NONE) { +Callback::Callback(void c(const char *)) : _nArgs(1), _type(NONE) +{ // Storing function pointer as void pointer for the sake of inclusiveness. - _functionPtr = (void*) c; + _functionPtr = (void *)c; } -Callback::Callback(void c(const char*, Var)) : _nArgs(2), _type(VAR) { +Callback::Callback(void c(const char *, Var)) : _nArgs(2), _type(VAR) +{ // Storing function pointer as void pointer for the sake of inclusiveness. - _functionPtr = (void*) c; + _functionPtr = (void *)c; } -Callback::Callback(void (c)(const char*, bool)) : _nArgs(2), _type(BOOLEAN) { +Callback::Callback(void(c)(const char *, bool)) : _nArgs(2), _type(BOOLEAN) +{ // Storing function pointer as void pointer for the sake of inclusiveness. - _functionPtr = (void*) c; + _functionPtr = (void *)c; } -Callback::Callback(void (c)(const char*, int)) : _nArgs(2), _type(INTEGER) { +Callback::Callback(void(c)(const char *, int)) : _nArgs(2), _type(INTEGER) +{ // Storing function pointer as void pointer for the sake of inclusiveness. - _functionPtr = (void*) c; + _functionPtr = (void *)c; } -Callback::Callback(void (c)(const char*, double)) : _nArgs(2), _type(DOUBLE) { +Callback::Callback(void(c)(const char *, double)) : _nArgs(2), _type(DOUBLE) +{ // Storing function pointer as void pointer for the sake of inclusiveness. - _functionPtr = (void*) c; + _functionPtr = (void *)c; } -Callback::Callback(void (c)(const char*, const char*)) : _nArgs(2), _type(STRING) { +Callback::Callback(void(c)(const char *, const char *)) : _nArgs(2), _type(STRING) +{ // Storing function pointer as void pointer for the sake of inclusiveness. - _functionPtr = (void*) c; + _functionPtr = (void *)c; } -void Callback::operator()(const char* str, Var var) { +void Callback::operator()(const char *str, Var var) +{ // Single argument function has type NONE. // Types are for functions of two arguments. // Checking number of arguments: - if (_nArgs == 1) { + if (_nArgs == 1) + { // Just pass the str argument to function. - return ((void (*)(const char*)) _functionPtr)(str); + return ((void (*)(const char *))_functionPtr)(str); } - if (_nArgs == 2) { + if (_nArgs == 2) + { // Getting type of the var. String varType = Var::typeof(var); // If var is a number - if (varType == "number") { + if (varType == "number") + { // If var as double is bigger than var as int, we use double, otherwise int. - varType = ((double) var - (int) var != 0) ? "double" : "int"; + varType = ((double)var - (int)var != 0) ? "double" : "int"; } // If var is an array - else if (varType == "array") { + else if (varType == "array") + { // Use it as var. varType = "var"; } // Switch cases on function type. We cast "var" to type functionPtr accepts. - switch(_type) { - case VAR: - // If functionPtr accepts Var, pass var argument as it is. - return ((void (*)(const char*, Var)) _functionPtr)(str, var); - case BOOLEAN: - // If functionPtr accepts Bool, pass var argument as bool. - if (varType != "boolean") - // If var argument isn't boolean. - return printError(varType); - else - // Call the function. - return ((void (*)(const char*, bool)) _functionPtr)(str, (bool) var); - - case INTEGER: - // If functionPtr accepts Int, pass var argument as int. - if (varType != "int") - // If var argument isn't int. - return printError(varType); - else - // Call the function. - return ((void (*)(const char*, int)) _functionPtr)(str, (int) var); - - case DOUBLE: - // If functionPtr accepts Double, pass var argument as double. - if (varType != "double") - // If var argument isn't double. - return printError(varType); - else - // Call the function. - return ((void (*)(const char*, double)) _functionPtr)(str, (double) var); - - case STRING: - // If functionPtr accepts String, pass var argument as string. - if (varType != "string") - // If var argument isn't string. - return printError(varType); - else - // Call the function. - return ((void (*)(const char*, const char*)) _functionPtr)(str, (const char*) var); + switch (_type) + { + case VAR: + // If functionPtr accepts Var, pass var argument as it is. + return ((void (*)(const char *, Var))_functionPtr)(str, var); + case BOOLEAN: + // If functionPtr accepts Bool, pass var argument as bool. + if (varType != "boolean") + // If var argument isn't boolean. + return printError(varType); + else + // Call the function. + return ((void (*)(const char *, bool))_functionPtr)(str, (bool)var); + + case INTEGER: + // If functionPtr accepts Int, pass var argument as int. + if (varType != "int") + // If var argument isn't int. + return printError(varType); + else + // Call the function. + return ((void (*)(const char *, int))_functionPtr)(str, (int)var); + + case DOUBLE: + // If functionPtr accepts Double, pass var argument as double. + if (varType != "double") + // If var argument isn't double. + return printError(varType); + else + // Call the function. + return ((void (*)(const char *, double))_functionPtr)(str, (double)var); + + case STRING: + // If functionPtr accepts String, pass var argument as string. + if (varType != "string") + // If var argument isn't string. + return printError(varType); + else + // Call the function. + return ((void (*)(const char *, const char *))_functionPtr)(str, (const char *)var); } return; } } -bool Callback::operator!() { +bool Callback::operator!() +{ // Returns true if the function pointer _functionPtr is not set. return (!_functionPtr && _type == NONE); } \ No newline at end of file diff --git a/src/DuplexHandler.cpp b/src/DuplexHandler.cpp index 89c3ac9..dfff9c4 100644 --- a/src/DuplexHandler.cpp +++ b/src/DuplexHandler.cpp @@ -8,7 +8,6 @@ * */ - #include #include "DuplexHandler.h" @@ -16,44 +15,48 @@ unsigned long timeSinceLastMessage = 0; DuplexHandler::DuplexHandler() : _query("/?type=device"), _token(""), _status(DISCONNECTED), - _connectionHandler([](bool status) {}) {} + _connectionHandler([](bool status) {}) {} -void DuplexHandler::init(Config config) { +void DuplexHandler::init(Config config) +{ _query = _query + "&apiKey=" + config.apiKey; _token = config.token; // Setting up event handler - _client.onEvent([=](WStype_t eventType, uint8_t* message, size_t length) { - duplexEventHandler(eventType, message, length); - }); + _client.onEvent([=](WStype_t eventType, uint8_t *message, size_t length) + { duplexEventHandler(eventType, message, length); }); // Scheduling reconnect every 5 seconds if it disconnects _client.setReconnectInterval(5000); DEBUG_GRANDEUR("Initializing duplex channel."); // Opening up the connection. - _client.beginSSL(GRANDEUR_URL, GRANDEUR_PORT, _query, GRANDEUR_FINGERPRINT, "node"); + _client.beginSSL(GRANDEUR_URL, GRANDEUR_PORT, _query.c_str(), GRANDEUR_FINGERPRINT, "node"); // Setting auth header. char tokenArray[_token.length() + 1]; _token.toCharArray(tokenArray, _token.length() + 1); _client.setAuthorization(tokenArray); } -void DuplexHandler::loop(bool valve) { - if(valve) { +void DuplexHandler::loop(bool valve) +{ + if (valve) + { // If valve is true => valve is open - if(millis() - timeSinceLastMessage >= PING_INTERVAL) { - // Ping Grandeur if PING_INTERVAL milliseconds have passed. - timeSinceLastMessage = millis(); + if (millis() - timeSinceLastMessage >= PING_INTERVAL) + { + // Ping Grandeur if PING_INTERVAL milliseconds have passed. + timeSinceLastMessage = millis(); - DEBUG_GRANDEUR("Pinging Grandeur."); - send("ping"); + DEBUG_GRANDEUR("Pinging Grandeur."); + send("ping"); } // Running duplex loop _client.loop(); } } -Message DuplexHandler::prepareMessage(const char* task) { +Message DuplexHandler::prepareMessage(const char *task) +{ // Generate a new message id. gId messageId = gid(); // Creating new message. @@ -64,7 +67,8 @@ Message DuplexHandler::prepareMessage(const char* task) { return {messageId, JSON.stringify(oMessage)}; } -Message DuplexHandler::prepareMessage(const char* task, Var payload) { +Message DuplexHandler::prepareMessage(const char *task, Var payload) +{ // Generate a new message id. gId messageId = gid(); // Creating new message. @@ -80,9 +84,11 @@ Message DuplexHandler::prepareMessage(const char* task, Var payload) { return {messageId, message}; } -void DuplexHandler::sendMessage(const char* message) { +void DuplexHandler::sendMessage(const char *message) +{ // Returning if channel isn't alive. - if(_status != CONNECTED) return; + if (_status != CONNECTED) + return; // Resetting timeSinceLastMessage. //timeSinceLastMessage = millis(); @@ -92,7 +98,8 @@ void DuplexHandler::sendMessage(const char* message) { _client.sendTXT(message); } -Message DuplexHandler::send(const char* task, Callback cb) { +Message DuplexHandler::send(const char *task, Callback cb) +{ // Preparing a new message. Message message = prepareMessage(task); @@ -100,7 +107,8 @@ Message DuplexHandler::send(const char* task, Callback cb) { _tasks.once(message.id, cb); // If channel isn't connected yet, buffer the message and return. - if(_status != CONNECTED) { + if (_status != CONNECTED) + { _buffer.push(message.id, message.str); return {message.id, message.str}; } @@ -111,12 +119,14 @@ Message DuplexHandler::send(const char* task, Callback cb) { return {message.id, message.str}; } -Message DuplexHandler::send(const char* task) { +Message DuplexHandler::send(const char *task) +{ // Preparing a new message. Message message = prepareMessage(task); // If channel isn't connected yet, buffer the message and return. - if(_status != CONNECTED) { + if (_status != CONNECTED) + { _buffer.push(message.id, message.str); return {message.id, message.str}; } @@ -127,15 +137,17 @@ Message DuplexHandler::send(const char* task) { return {message.id, message.str}; } -Message DuplexHandler::send(const char* task, Var payload, Callback cb) { +Message DuplexHandler::send(const char *task, Var payload, Callback cb) +{ // Preparing a new message. Message message = prepareMessage(task, payload); // Adding task to receive the response message. _tasks.once(message.id, cb); - + // If channel isn't connected yet, buffer the message and return. - if(_status != CONNECTED) { + if (_status != CONNECTED) + { _buffer.push(message.id, message.str); return {message.id, message.str}; } @@ -146,12 +158,14 @@ Message DuplexHandler::send(const char* task, Var payload, Callback cb) { return {message.id, message.str}; } -Message DuplexHandler::send(const char* task, Var payload) { +Message DuplexHandler::send(const char *task, Var payload) +{ // Preparing a new message. Message message = prepareMessage(task, payload); - + // If channel isn't connected yet, buffer the message and return. - if(_status != CONNECTED) { + if (_status != CONNECTED) + { _buffer.push(message.id, message.str); return {message.id, message.str}; } @@ -162,46 +176,52 @@ Message DuplexHandler::send(const char* task, Var payload) { return {message.id, message.str}; } -void DuplexHandler::receive(Var header, Var payload) { +void DuplexHandler::receive(Var header, Var payload) +{ // Extracting task and id from header and code. - const char* task = header["task"]; + const char *task = header["task"]; gId id = header["id"]; - const char* code = payload["code"]; - + const char *code = payload["code"]; + // Extracting data. Var data = null; // Response to Get has data in payload["data"]. - if(strcmp(task, "/device/data/get") == 0) data = payload["data"]; + if (strcmp(task, "/device/data/get") == 0) + data = payload["data"]; // Response to Set has data in payload["update"]. - else if(strcmp(task, "/device/data/set") == 0) data = payload["update"]; + else if (strcmp(task, "/device/data/set") == 0) + data = payload["update"]; // For datastore, we delete code and message from the payload and send the rest. - else if(strcmp(task, "/datastore/insert") == 0 || strcmp(task, "/datastore/delete") == 0 || - strcmp(task, "/datastore/update") == 0 || strcmp(task, "/datastore/pipeline") == 0) { + else if (strcmp(task, "/datastore/insert") == 0 || strcmp(task, "/datastore/delete") == 0 || + strcmp(task, "/datastore/update") == 0 || strcmp(task, "/datastore/pipeline") == 0) + { data = payload; data["code"] = undefined; data["message"] = undefined; } - DEBUG_GRANDEUR( "Response message:: code: %s, data: %s.", code, JSON.stringify(data).c_str() ); + DEBUG_GRANDEUR("Response message:: code: %s, data: %s.", code, JSON.stringify(data).c_str()); // Emit on the Id from the tasks. - if(Var::typeof_(data) != "null" && Var::typeof_(data) != "undefined") - _tasks.emit( id, code, data ); + if (Var::typeof_(data) != "null" && Var::typeof_(data) != "undefined") + _tasks.emit(id, code, data); else - _tasks.emit( id, code, undefined ); + _tasks.emit(id, code, undefined); } -void DuplexHandler::publish(const char* event, const char* path, Var data) { - DEBUG_GRANDEUR( "Data update:: path: %s, data: %s.", path, JSON.stringify(data) ); +void DuplexHandler::publish(const char *event, const char *path, Var data) +{ + DEBUG_GRANDEUR("Data update:: path: %s, data: %s.", path, JSON.stringify(data)); // Handling the backward compatibility for summary/parms. if (strcmp(event, "deviceParms") == 0 || strcmp(event, "deviceSummary") == 0) - strcpy((char*) event, "data"); + strcpy((char *)event, "data"); // If it's update for device data, emit on the pattern "event/path". So that the listeners // subscribing to "event/"" get the update for "event/path" as well. - if(strcmp(event, "data") == 0) { - _subscriptions.pEmit( String(event) + "/" + String(path), path, data ); + if (strcmp(event, "data") == 0) + { + _subscriptions.pEmit(String(event) + "/" + String(path), path, data); return; } @@ -210,7 +230,8 @@ void DuplexHandler::publish(const char* event, const char* path, Var data) { return; } -gId DuplexHandler::subscribe(const char* topic, Var payload, Callback updateHandler) { +gId DuplexHandler::subscribe(const char *topic, Var payload, Callback updateHandler) +{ DEBUG_GRANDEUR("Subscribing to topic:: %s.", topic); // Sending subscription request. @@ -225,7 +246,8 @@ gId DuplexHandler::subscribe(const char* topic, Var payload, Callback updateHand return message.id; } -void DuplexHandler::unsubscribe(const char* topic, gId eventId, Var payload) { +void DuplexHandler::unsubscribe(const char *topic, gId eventId, Var payload) +{ DEBUG_GRANDEUR("Unsubscribing from topic:: %s.", JSON.stringify(payload).c_str()); // Sending unsubscription request to Grandeur. and remove subscription request message from buffer for future reconnection. @@ -236,100 +258,115 @@ void DuplexHandler::unsubscribe(const char* topic, gId eventId, Var payload) { _buffer.remove(eventId); } -void DuplexHandler::duplexEventHandler(WStype_t eventType, uint8_t* message, size_t length) { +void DuplexHandler::duplexEventHandler(WStype_t eventType, uint8_t *message, size_t length) +{ // Resetting timeSinceLastMessage. // timeSinceLastMessage = millis(); // Switch over event type - switch(eventType) { - case WStype_CONNECTED: - DEBUG_GRANDEUR("Duplex channel established."); - // When duplex connection opens - _status = CONNECTED; - // Running connection handler. - _connectionHandler(_status); - - // Flushing all buffered messages to the channel. - _buffer.forEach([=](const char* message) { sendMessage(message); }); - - break; - - case WStype_DISCONNECTED: - DEBUG_GRANDEUR("Duplex channel broke."); - // When duplex connection closes - _status = DISCONNECTED; - // Running connection handler. - _connectionHandler(_status); - - // Clear all tasks. - _tasks.offAll(); - - break; - - case WStype_TEXT: - // When a duplex message is received. - DEBUG_GRANDEUR("Message is received:: %s.", message); - // Parsing the JSON message. - Var oMessage = JSON.parse((char*) message); - // Handling any parsing errors - if (JSON.typeof(oMessage) == "undefined") { - // Just for internal errors of Arduino_JSON - // if the parsing fails. - DEBUG_GRANDEUR("Parsing message failed!"); - return; - } - - Var header = oMessage["header"]; - Var payload = oMessage["payload"]; - const char* task = header["task"]; - - // ROUTES: - // We do not need to handle the unpair event in Device SDKs. - if(strcmp(task, "unpair") == 0); - // Ping has no data so we simply emit. - else if(strcmp(task, "ping") == 0); - // If it is an update event rather than a task (response message). - else if(strcmp(task, "update") == 0) - publish(payload["event"], payload["path"], payload["update"]); - // Otherwise: It's a response message for a task. So we receive it. - else { - receive(header, payload); - - // Debuffer the message except if it's a subscription request. This is to solve losing - // subscriptions due to reconnection. - if (strcmp(task, "/topic/subscribe") == 0); - else - _buffer.remove((gId) header["id"]); - } + switch (eventType) + { + case WStype_CONNECTED: + DEBUG_GRANDEUR("Duplex channel established."); + // When duplex connection opens + _status = CONNECTED; + // Running connection handler. + _connectionHandler(_status); + + // Flushing all buffered messages to the channel. + _buffer.forEach([=](const char *message) + { sendMessage(message); }); + + break; + + case WStype_DISCONNECTED: + DEBUG_GRANDEUR("Duplex channel broke."); + // When duplex connection closes + _status = DISCONNECTED; + // Running connection handler. + _connectionHandler(_status); + + // Clear all tasks. + _tasks.offAll(); + + break; + + case WStype_TEXT: + // When a duplex message is received. + DEBUG_GRANDEUR("Message is received:: %s.", message); + // Parsing the JSON message. + Var oMessage = JSON.parse((char *)message); + // Handling any parsing errors + if (JSON.typeof(oMessage) == "undefined") + { + // Just for internal errors of Arduino_JSON + // if the parsing fails. + DEBUG_GRANDEUR("Parsing message failed!"); + return; + } + + Var header = oMessage["header"]; + Var payload = oMessage["payload"]; + const char *task = header["task"]; + + // ROUTES: + // We do not need to handle the unpair event in Device SDKs. + if (strcmp(task, "unpair") == 0) + ; + // Ping has no data so we simply emit. + else if (strcmp(task, "ping") == 0) + ; + // If it is an update event rather than a task (response message). + else if (strcmp(task, "update") == 0) + publish(payload["event"], payload["path"], payload["update"]); + // Otherwise: It's a response message for a task. So we receive it. + else + { + receive(header, payload); + + // Debuffer the message except if it's a subscription request. This is to solve losing + // subscriptions due to reconnection. + if (strcmp(task, "/topic/subscribe") == 0) + ; + else + _buffer.remove((gId)header["id"]); + } } } -void Buffer::push(gId id, String message) { +void Buffer::push(gId id, String message) +{ _buffer[id] = message; } -void Buffer::remove(gId id) { +void Buffer::remove(gId id) +{ _buffer.erase(id); } -void Buffer::forEach(std::function callback) { +void Buffer::forEach(std::function callback) +{ // Iterating through the _buffer running callback on each message. - for(std::map::iterator it = _buffer.begin(); it != _buffer.end(); it++) { + for (std::map::iterator it = _buffer.begin(); it != _buffer.end(); it++) + { DEBUG_GRANDEUR("Flushing:: Id: %lu, Message: %s.", it->first, it->second.c_str()); callback(it->second.c_str()); } } -void DuplexHandler::onConnectionEvent(void connectionCallback(bool)) { +void DuplexHandler::onConnectionEvent(void connectionCallback(bool)) +{ DEBUG_GRANDEUR("Setting up connection handler."); _connectionHandler = connectionCallback; } -void DuplexHandler::clearConnectionCallback(void) { +void DuplexHandler::clearConnectionCallback(void) +{ DEBUG_GRANDEUR("Clearing connection handler."); // Setting connection handler to empty function. _connectionHandler = [](bool status) {}; } -bool DuplexHandler::getStatus() { +bool DuplexHandler::getStatus() +{ return _status; } diff --git a/src/EventEmitter/EventEmitter.h b/src/EventEmitter/EventEmitter.h index dc4393c..b1d32f1 100644 --- a/src/EventEmitter/EventEmitter.h +++ b/src/EventEmitter/EventEmitter.h @@ -4,8 +4,9 @@ #ifndef _EVENT_EMITTER_H_ #define _EVENT_EMITTER_H_ -template -class EventEmitter { +template +class EventEmitter +{ private: // We use multimap to implement our event emitter. using ListenersMap = std::multimap>; @@ -18,65 +19,77 @@ class EventEmitter { EventEmitter() {} virtual ~EventEmitter() {} - - EventName* eventNames() { + + EventName *eventNames() + { // Returning the array pointer from the vector. return events.data(); } - size_t getNListeners() { + size_t getNListeners() + { // Getting the size of the listeners map. return listeners.size(); } - void on(EventName eventName, Emitter emitter) { + void on(EventName eventName, Emitter emitter) + { // Adding a new reusable listener to listeners map with event name. listeners.insert(std::pair>(eventName, Listener(emitter, false))); events.push_back(eventName); } - bool once(EventName eventName, Emitter emitter) { + void once(EventName eventName, Emitter emitter) + { // Adding a new nonreusable listener to listeners map with event name. listeners.insert(std::pair>(eventName, Listener(emitter, true))); events.push_back(eventName); } - void off(EventName eventName) { + void off(EventName eventName) + { // Erasing listeners with event name from the listeners map and returning the number of them erased. listeners.erase(eventName); events.erase(std::find(events.begin(), events.end(), eventName)); } - void offAll() { + void offAll() + { // Clearing the listeners map. listeners.clear(); events.clear(); } - template - void emit(EventName eventName, T... args) { + template + void emit(EventName eventName, T... args) + { // Getting all listeners from listeners map with event name and emit them. auto lower_itr = listeners.lower_bound(eventName); auto upper_itr = listeners.upper_bound(eventName); - while (lower_itr != upper_itr) { - if (lower_itr->first == eventName) { + while (lower_itr != upper_itr) + { + if (lower_itr->first == eventName) + { lower_itr->second.emit(args...); // If the listener is for once, remove it. - if(lower_itr->second.isOnce()) + if (lower_itr->second.isOnce()) off(eventName); } lower_itr++; } } - template - void pEmit(EventName eventName, T... args) { + template + void pEmit(EventName eventName, T... args) + { // Searching through all listeners and emitting on those that match. - for(auto itr = listeners.begin(); itr != listeners.end(); itr++) { - if(String(eventName).startsWith(itr->first)) { + for (auto itr = listeners.begin(); itr != listeners.end(); itr++) + { + if (String(eventName).startsWith(itr->first)) + { itr->second.emit(args...); // If the listener is for once, remove it. - if(itr->second.isOnce()) + if (itr->second.isOnce()) off(itr->first); } } diff --git a/src/debug.h b/src/debug.h index fe97286..23e7aa7 100644 --- a/src/debug.h +++ b/src/debug.h @@ -2,16 +2,16 @@ #define DEBUG 0 #define DEBUG_WS 0 #if DEBUG || DEBUG_WS - #define DEBUG_PORT Serial +#define DEBUG_PORT Serial #endif /* DEBUG || DEBUG_WS */ #if DEBUG - #define DEBUG_GRANDEUR(format, args...) \ - DEBUG_PORT.printf(("[GRANDEUR-DEBUG] " + String(format) + "\n").c_str(), ##args) - #else - //#define DEBUG_GRANDEUR(format, args...) \ +#define DEBUG_GRANDEUR(format, args...) \ + DEBUG_PORT.printf(("[GRANDEUR-DEBUG] " + String(format) + "\n").c_str(), ##args) +#else +//#define DEBUG_GRANDEUR(format, args...) \ os_printf(("[GRANDEUR-DEBUG] " + String(format)).c_str(), ##args) - #ifndef DEBUG_GRANDEUR - #define DEBUG_GRANDEUR(format, args...) - #endif +#ifndef DEBUG_GRANDEUR +#define DEBUG_GRANDEUR(format, args...) +#endif #endif /* DEBUG */ \ No newline at end of file diff --git a/src/macros.h b/src/macros.h index 014ac15..e02c47b 100644 --- a/src/macros.h +++ b/src/macros.h @@ -13,7 +13,7 @@ // Connection macros #define GRANDEUR_URL "api.grandeur.tech" #define GRANDEUR_PORT 443 -#define GRANDEUR_FINGERPRINT "" +#define GRANDEUR_FINGERPRINT NULL // Strings sizes #define FINGERPRINT_SIZE 256