diff --git a/examples/samd/README.md b/examples/README.md similarity index 100% rename from examples/samd/README.md rename to examples/README.md diff --git a/examples/samd/command_center/command_center.ino b/examples/command_center/command_center.ino similarity index 55% rename from examples/samd/command_center/command_center.ino rename to examples/command_center/command_center.ino index 7f055e4..2c18d56 100644 --- a/examples/samd/command_center/command_center.ino +++ b/examples/command_center/command_center.ino @@ -4,101 +4,63 @@ // This example code shows how to use an Adafruit Feather M0 module and Microsoft Azure for IoT // applications. -#include -#include -#include -#include -#include -#include -#ifdef ARDUINO_SAMD_FEATHER_M0 +// change the next three lines to use on non-Adafruit WINC1500 based boards/shields #include -#include -#include -#include #include #include -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -#include -#endif -#include + +// for WiFi101 +//#include +//#include +//#include + +// for ESP8266 +//#include +//#include +//#include + #include -#include "rem_ctrl_http.h" -#include "NTPClient.h" +#include +#include +#include "rem_ctrl_http.h" -#ifdef ARDUINO_SAMD_FEATHER_M0 +// for the Adafruit WINC1500 we need to create our own WiFi instance +// Define the WINC1500 board connections below. #define WINC_CS 8 #define WINC_IRQ 7 #define WINC_RST 4 -#define WINC_EN 2 - +#define WINC_EN 2 // or, tie EN to VCC // Setup the WINC1500 connection with the pins above and the default hardware SPI. Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST); -#endif - static const char ssid[] = "[Your WiFi network SSID or name]"; static const char pass[] = "[Your WiFi network WPA password or WEP key]"; -static const char* connectionString = "[Device Connection String]"; // The connection string is the one which begins with HostName=... and contains the DeviceId // and SharedAccessKey for this particular Thing on the Internet. +static const char* connectionString = "[Device Connection String]"; -int status = WL_IDLE_STATUS; +// change the next line to use on non-Adafruit WINC1500 based boards/shields +Adafruit_WINC1500SSLClient sslClient; // for Adafruit WINC150 +//WiFiSSLClient sslClient; // for WiFi101 +//WiFiClientSecure sslClient; // for ESP8266 +AzureIoTHubClient iotHubClient(sslClient); #define SEALEVELPRESSURE_HPA (1013.25) const int Bme280_cs_pin__i = 5; bool Bme_init_result = false; Adafruit_BME280 bme(Bme280_cs_pin__i); -void initTime(); - void setup() { - // The Feather M0 loses it's COMn connection with every reset. - // This 10 s delay allows you to reselect the COM port and open the serial monitor window. - delay(10000); - - Serial.begin(9600); - Serial.println("Azure_remote_monitoring Sketch."); -#ifdef WINC_EN - pinMode(WINC_EN, OUTPUT); - digitalWrite(WINC_EN, HIGH); -#endif + initSerial(); - Serial.println("Checking for the presence of the BME280 temp/humid/press module."); - Bme_init_result = bme.begin(); - if (Bme_init_result) - { - Serial.println("Found and initialized BME280 module."); - } - else - { - Serial.println("Warning! BME280 module not found."); - } - - Serial.println("Checking for the presence of the WiFi module."); - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("Warning! WiFi shield not found."); - } - else - { - Serial.println("WiFi module found."); - } + Serial.println("Azure_remote_monitoring Sketch."); - Serial.println("Attempting to connect to Wifi network."); - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - if (status != WL_CONNECTED) { - // wait 10 seconds for connection: - delay(10000); - } - } - Serial.println("Connected to wifi"); + initWifi(); + initTime(); + initBME(); if (rem_ctrl_set_connection_string(connectionString)) { Serial.print("Connection string successfully set to \""); @@ -115,7 +77,7 @@ void setup() { Serial.println("Unable to initialize the Azure connection. Halting."); } - initTime(); + iotHubClient.begin(); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -141,7 +103,7 @@ void loop() { Sensor_read_next_ms__u32 = Curr_time_ms__u32 + Sensor_read_period_ms__u32; } - + if (IS_TASK_TIME(Curr_time_ms__u32, Azure_io_update_next_ms__u32)) { rem_ctrl_http_run(); @@ -150,38 +112,101 @@ void loop() { } /////////////////////////////////////////////////////////////////////////////////////////////////// +void initSerial() { + //Initialize serial and wait for port to open: + // For SAMD boards (e.g. MKR1000, Adafruit WINC1500 based) + Serial.begin(9600); + + // Uncomment the next two lines For ESP8266 boards (and comment out the line above) + // Serial.begin(115200); + // Serial.setDebugOutput(true); + + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } +} + +void initWifi() { + // for the Adafruit WINC1500 we need to enable the chip + pinMode(WINC_EN, OUTPUT); + digitalWrite(WINC_EN, HIGH); + + // check for the presence of the shield : + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to Wifi network: + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + while (WiFi.begin(ssid, pass) != WL_CONNECTED) { + // unsuccessful, retry in 4 seconds + Serial.print("failed ... "); + delay(4000); + Serial.print("retrying ... "); + } + + Serial.println("Connected to wifi"); +} + void initTime() { -#ifdef ARDUINO_SAMD_FEATHER_M0 - Adafruit_WINC1500UDP _udp; -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) - WiFiUDP _udp; -#endif - - time_t epochTime = (time_t)-1; - - NTPClient ntpClient; - ntpClient.begin(); - - while (true) { - epochTime = ntpClient.getEpochTime("0.pool.ntp.org"); - - if (epochTime == (time_t)-1) { - Serial.println("Fetching NTP epoch time failed! Waiting 5 seconds to retry."); - delay(5000); - } else { - Serial.print("Fetched NTP epoch time is: "); - Serial.println(epochTime); - break; - } - } - - ntpClient.end(); - - struct timeval tv; - tv.tv_sec = epochTime; - tv.tv_usec = 0; - - settimeofday(&tv, NULL); + // change the next line to use on non-WINC1500 based boards/shields + Adafruit_WINC1500UDP ntpUdp; // for Adafruit WINC1500 + // WiFiUDP ntpUdp; // for WiFi101 + // for ESP8266 boards see comment below + NTPClient ntpClient(ntpUdp); + + ntpClient.begin(); + + while (!ntpClient.update()) { + Serial.println("Fetching NTP epoch time failed! Waiting 5 seconds to retry."); + delay(5000); + } + + ntpClient.end(); + + unsigned long epochTime = ntpClient.getEpochTime(); + + Serial.print("Fetched NTP epoch time is: "); + Serial.println(epochTime); + + iotHubClient.setEpochTime(epochTime); + + // For ESP8266 boards comment out the above portion of the function and un-comment + // the remainder below. + + // time_t epochTime; + + // configTime(0, 0, "pool.ntp.org", "time.nist.gov"); + + // while (true) { + // epochTime = time(NULL); + + // if (epochTime == 0) { + // Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); + // delay(2000); + // } else { + // Serial.print("Fetched NTP epoch time is: "); + // Serial.println(epochTime); + // break; + // } + // } } +void initBME() { + Serial.println("Checking for the presence of the BME280 temp/humid/press module."); + Bme_init_result = bme.begin(); + if (Bme_init_result) + { + Serial.println("Found and initialized BME280 module."); + } + else + { + Serial.println("Warning! BME280 module not found."); + } +} diff --git a/examples/samd/command_center/rem_ctrl_http.c b/examples/command_center/rem_ctrl_http.c similarity index 85% rename from examples/samd/command_center/rem_ctrl_http.c rename to examples/command_center/rem_ctrl_http.c index ba04d90..6f2052b 100644 --- a/examples/samd/command_center/rem_ctrl_http.c +++ b/examples/command_center/rem_ctrl_http.c @@ -9,6 +9,7 @@ #ifdef ARDUINO #include "AzureIoTHub.h" +#include "iot_logging.h" #else #include "serializer.h" #include "iothub_client_ll.h" @@ -48,7 +49,7 @@ DEFINE_ENUM_STRINGS(IOTHUB_CLIENT_CONFIRMATION_RESULT, IOTHUB_CLIENT_CONFIRMATIO EXECUTE_COMMAND_RESULT TurnFanOn(BME280_data* device) { (void)device; - (void)printf("Turning Green LED on.\r\n"); + LogInfo("Turning Green LED on.\r\n"); digitalWrite(greenLedPin, HIGH); digitalWrite(redLedPin, LOW); return EXECUTE_COMMAND_SUCCESS; @@ -57,7 +58,7 @@ EXECUTE_COMMAND_RESULT TurnFanOn(BME280_data* device) EXECUTE_COMMAND_RESULT TurnFanOff(BME280_data* device) { (void)device; - (void)printf("Turning red LED on.\r\n"); + LogInfo("Turning red LED on.\r\n"); digitalWrite(greenLedPin, LOW); digitalWrite(redLedPin, HIGH); return EXECUTE_COMMAND_SUCCESS; @@ -79,9 +80,9 @@ void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCal { int messageTrackingId = (intptr_t)userContextCallback; - (void)printf("Message Id: %d Received.\r\n", messageTrackingId); + LogInfo("Message Id: %d Received.\r\n", messageTrackingId); - (void)printf("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); + LogInfo("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -91,17 +92,17 @@ static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsign IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size); if (messageHandle == NULL) { - printf("unable to create a new IoTHubMessage\r\n"); + LogInfo("unable to create a new IoTHubMessage\r\n"); } else { if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK) { - printf("failed to hand over the message to IoTHubClient"); + LogInfo("failed to hand over the message to IoTHubClient"); } else { - printf("IoTHubClient accepted the message for delivery\r\n"); + LogInfo("IoTHubClient accepted the message for delivery\r\n"); } IoTHubMessage_Destroy(messageHandle); } @@ -118,7 +119,7 @@ static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE mess size_t size; if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK) { - printf("unable to IoTHubMessage_GetByteArray\r\n"); + LogInfo("unable to IoTHubMessage_GetByteArray\r\n"); result = EXECUTE_COMMAND_ERROR; } else @@ -127,7 +128,7 @@ static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE mess char* temp = malloc(size + 1); if (temp == NULL) { - printf("failed to malloc\r\n"); + LogInfo("failed to malloc\r\n"); result = EXECUTE_COMMAND_ERROR; } else @@ -157,7 +158,7 @@ int rem_ctrl_http_init(void) if (serializer_init(NULL) != SERIALIZER_OK) { - (void)printf("Failed on serializer_init\r\n"); + LogInfo("Failed on serializer_init\r\n"); } else { @@ -166,7 +167,7 @@ int rem_ctrl_http_init(void) iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol); if (iotHubClientHandle == NULL) { - (void)printf("Failed on IoTHubClient_LL_Create\r\n"); + LogInfo("Failed on IoTHubClient_LL_Create\r\n"); } else { @@ -175,13 +176,13 @@ int rem_ctrl_http_init(void) unsigned int minimumPollingTime = 9; // Because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds. if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) { - printf("failure to set option \"MinimumPollingTime\"\r\n"); + LogInfo("failure to set option \"MinimumPollingTime\"\r\n"); } myWeather = CREATE_MODEL_INSTANCE(RemoteMonitorExample, BME280_data); if (myWeather == NULL) { - (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n"); + LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n"); } else { @@ -189,7 +190,7 @@ int rem_ctrl_http_init(void) if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK) { - printf("unable to IoTHubClient_SetMessageCallback\r\n"); + LogInfo("unable to IoTHubClient_SetMessageCallback\r\n"); } else { @@ -230,7 +231,7 @@ void rem_ctrl_http_send_data(float Temp_c__f, float Pres_hPa__f, float Humi_pct_ if (Init_level__i < 4) return; timeNow = (int)time(NULL); - sprintf(buff, "%d", timeNow); + sLogInfo(buff, "%d", timeNow); myWeather->DeviceId = "FeatherM0_w_BME280"; myWeather->MTemperature = Temp_c__f; @@ -242,24 +243,24 @@ void rem_ctrl_http_send_data(float Temp_c__f, float Pres_hPa__f, float Humi_pct_ size_t destinationSize; if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->EventTime, myWeather->MTemperature, myWeather->Pressure, myWeather->Humidity) != IOT_AGENT_OK) { - (void)printf("Failed to serialize\r\n"); + LogInfo("Failed to serialize\r\n"); } else { IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize); if (messageHandle == NULL) { - printf("unable to create a new IoTHubMessage\r\n"); + LogInfo("unable to create a new IoTHubMessage\r\n"); } else { if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) { - printf("failed to hand over the message to IoTHubClient"); + LogInfo("failed to hand over the message to IoTHubClient"); } else { - printf("IoTHubClient accepted the message for delivery\r\n"); + LogInfo("IoTHubClient accepted the message for delivery\r\n"); } IoTHubMessage_Destroy(messageHandle); diff --git a/examples/samd/command_center/rem_ctrl_http.h b/examples/command_center/rem_ctrl_http.h similarity index 100% rename from examples/samd/command_center/rem_ctrl_http.h rename to examples/command_center/rem_ctrl_http.h diff --git a/examples/esp8266/command_center/command_center.ino b/examples/esp8266/command_center/command_center.ino deleted file mode 100644 index 87db917..0000000 --- a/examples/esp8266/command_center/command_center.ino +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -// This example only works with Arduino IDE 1.6.8 or later. - -#include -#include -#include "command_center_http.h" - - -const char ssid[] = "[SSID]"; // your WiFi SSID (name) -const char pass[] = "[PASSWORD]"; // your WiFi password (use for WPA, or use as key for WEP) -const char connectionString[] = "HostName=[HubName].azure-devices.net;DeviceId=[DeviceName];SharedAccessKey=[KEY]"; - -int status = WL_IDLE_STATUS; - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void setup() { - initSerial(); - initWifi(); - initTime(); - - // This function doesn't exit. - simplesample_http_run(); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void loop() { - // Not used. -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void initSerial() { - // Start serial and initialize stdout - Serial.begin(115200); - Serial.setDebugOutput(true); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void initWifi() { - // Attempt to connect to Wifi network: - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - - Serial.println("Connected to wifi"); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void initTime() { - time_t epochTime; - - configTime(0, 0, "pool.ntp.org", "time.nist.gov"); - - while (true) { - epochTime = time(NULL); - - if (epochTime == 0) { - Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); - delay(2000); - } else { - Serial.print("Fetched NTP epoch time is: "); - Serial.println(epochTime); - break; - } - } -} - diff --git a/examples/esp8266/command_center/command_center_http.c b/examples/esp8266/command_center/command_center_http.c deleted file mode 100644 index 278287b..0000000 --- a/examples/esp8266/command_center/command_center_http.c +++ /dev/null @@ -1,314 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////////////////////////// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#include - -#include -#include -#include -#include -#include - -#include "dht22.h" -#include "command_center_http.h" - -/* This sample uses the _LL APIs of iothub_client for example purposes. -That does not mean that HTTP only works with the _LL APIs. -Simply changing the using the convenience layer (functions not having _LL) -and removing calls to _DoWork will yield the same results. */ - -#include "AzureIoTHub.h" - - -//static const char* connectionString = "HostName=[host].azure-devices.net;DeviceId=[device];SharedAccessKey=[key]"; -static const char connectionString[] = "HostName=[host].azure-devices.net;DeviceId=[device];SharedAccessKey=[key]"; - -static int redLedPin = 12; -static int redLedState = LOW; -static int greenLedPin = 13; -static int greenLedState = LOW; - -// Define the Model -BEGIN_NAMESPACE(WeatherStation); - -DECLARE_MODEL(ContosoAnemometer, -WITH_DATA(ascii_char_ptr, DeviceId), -WITH_DATA(ascii_char_ptr, EventTime), -WITH_DATA(int, WindSpeed), -WITH_DATA(int, MTemperature), -WITH_DATA(int, Humidity), -WITH_ACTION(TurnFanOn), -WITH_ACTION(TurnFanOff), -WITH_ACTION(SetAirResistance, int, Position) -); - -END_NAMESPACE(WeatherStation); - -DEFINE_ENUM_STRINGS(IOTHUB_CLIENT_CONFIRMATION_RESULT, IOTHUB_CLIENT_CONFIRMATION_RESULT_VALUES) - -EXECUTE_COMMAND_RESULT TurnFanOn(ContosoAnemometer* device) -{ - (void)device; - - LogInfo("Toggling red LED.\r\n"); - if (redLedState != LOW) - { - redLedState = LOW; - } - else - { - redLedState = HIGH; - } - digitalWrite(redLedPin, redLedState); - - return EXECUTE_COMMAND_SUCCESS; -} - -EXECUTE_COMMAND_RESULT TurnFanOff(ContosoAnemometer* device) -{ - (void)device; - - LogInfo("Toggling green LED.\r\n"); - if (greenLedState != LOW) - { - greenLedState = LOW; - } - else - { - greenLedState = HIGH; - } - digitalWrite(greenLedPin, greenLedState); - - return EXECUTE_COMMAND_SUCCESS; -} - -EXECUTE_COMMAND_RESULT SetAirResistance(ContosoAnemometer* device, int Position) -{ - (void)device; - LogInfo("Setting Air Resistance Position to %d.\r\n", Position); - return EXECUTE_COMMAND_SUCCESS; -} - -void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback) -{ - int messageTrackingId = (intptr_t)userContextCallback; - - LogInfo("Message Id: %d Received.\r\n", messageTrackingId); - - LogInfo("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); -} - -static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size) -{ - static unsigned int messageTrackingId; - IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size); - if (messageHandle == NULL) - { - LogInfo("unable to create a new IoTHubMessage\r\n"); - } - else - { - if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK) - { - LogInfo("failed to hand over the message to IoTHubClient"); - } - else - { - LogInfo("IoTHubClient accepted the message for delivery\r\n"); - } - IoTHubMessage_Destroy(messageHandle); - } - free((void*)buffer); - messageTrackingId++; -} - -/*this function "links" IoTHub to the serialization library*/ -static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback) -{ - IOTHUBMESSAGE_DISPOSITION_RESULT result; - const unsigned char* buffer; - size_t size; - if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK) - { - LogInfo("unable to IoTHubMessage_GetByteArray\r\n"); - result = EXECUTE_COMMAND_ERROR; - } - else - { - /*buffer is not zero terminated*/ - char* temp = malloc(size + 1); - if (temp == NULL) - { - LogInfo("failed to malloc\r\n"); - result = EXECUTE_COMMAND_ERROR; - } - else - { - memcpy(temp, buffer, size); - temp[size] = '\0'; - EXECUTE_COMMAND_RESULT executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp); - result = - (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED : - (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED : - IOTHUBMESSAGE_REJECTED; - free(temp); - } - } - return result; -} - -void simplesample_http_run(void) -{ - initDht(); - - digitalWrite(redLedPin, redLedState); - pinMode(redLedPin, OUTPUT); - - digitalWrite(greenLedPin, greenLedState); - pinMode(greenLedPin, OUTPUT); - - if (serializer_init(NULL) != SERIALIZER_OK) - { - LogInfo("Failed on serializer_init\r\n"); - } - else - { - IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol); - srand((unsigned int)time(NULL)); - int avgWindSpeed = 10.0; - - if (iotHubClientHandle == NULL) - { - LogInfo("Failed on IoTHubClient_LL_Create\r\n"); - } - else - { - unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/ - if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) - { - LogInfo("failure to set option \"MinimumPollingTime\"\r\n"); - } - -#ifdef MBED_BUILD_TIMESTAMP - // For mbed add the certificate information - if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) - { - LogInfo("failure to set option \"TrustedCerts\"\r\n"); - } -#endif // MBED_BUILD_TIMESTAMP - - ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer); - if (myWeather == NULL) - { - LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n"); - } - else - { - if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK) - { - LogInfo("unable to IoTHubClient_SetMessageCallback\r\n"); - } - else - { - myWeather->DeviceId = "myFirstDevice"; - myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2); - { - unsigned char* destination; - size_t destinationSize; - if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != IOT_AGENT_OK) - { - LogInfo("Failed to serialize\r\n"); - } - else - { - IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize); - if (messageHandle == NULL) - { - LogInfo("unable to create a new IoTHubMessage\r\n"); - } - else - { - if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) - { - LogInfo("failed to hand over the message to IoTHubClient\r\n"); - } - else - { - LogInfo("IoTHubClient accepted the message for delivery\r\n"); - } - - IoTHubMessage_Destroy(messageHandle); - } - free(destination); - } - } - - /* wait for commands */ - long Prev_time_ms = millis(); - char buff[11]; - int timeNow = 0; - - while (1) - { - long Curr_time_ms = millis(); - if (Curr_time_ms >= Prev_time_ms + 5000) - { - Prev_time_ms = Curr_time_ms; - - timeNow = (int)time(NULL); - sprintf(buff, "%d", timeNow); - - float Temp_c__f, Humi_pct__f; - getNextSample(&Temp_c__f, &Humi_pct__f); - myWeather->DeviceId = "myFirstDevice"; - myWeather->EventTime = timeNow; - myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2); - myWeather->MTemperature = (int)Temp_c__f; - myWeather->Humidity = (int)Humi_pct__f; - { - unsigned char* destination; - size_t destinationSize; - if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->EventTime, myWeather->WindSpeed, myWeather->MTemperature, myWeather->Humidity) != IOT_AGENT_OK) - { - LogInfo("Failed to serialize\r\n"); - } - else - { - IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize); - if (messageHandle == NULL) - { - LogInfo("unable to create a new IoTHubMessage\r\n"); - } - else - { - if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) - { - LogInfo("failed to hand over the message to IoTHubClient\r\n"); - } - else - { - LogInfo("IoTHubClient accepted the message for delivery\r\n"); - } - - IoTHubMessage_Destroy(messageHandle); - } - free(destination); - } - } - } - - IoTHubClient_LL_DoWork(iotHubClientHandle); - ThreadAPI_Sleep(100); - } - } - - DESTROY_MODEL_INSTANCE(myWeather); - } - IoTHubClient_LL_Destroy(iotHubClientHandle); - } - serializer_deinit(); - } -} - - diff --git a/examples/esp8266/command_center/command_center_http.h b/examples/esp8266/command_center/command_center_http.h deleted file mode 100644 index 943ddf9..0000000 --- a/examples/esp8266/command_center/command_center_http.h +++ /dev/null @@ -1,22 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////////////////////////// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifndef _cmd_ctr_HTTP_H -#define _cmd_ctr_HTTP_H - -#define MAX_CONNECTION_STRING_LEN (255) - -#ifdef __cplusplus -extern "C" { -#endif - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void simplesample_http_run(void); - -#ifdef __cplusplus -} -#endif - -#endif//_cmd_ctr_HTTP_H - diff --git a/examples/esp8266/command_center/dht22.cpp b/examples/esp8266/command_center/dht22.cpp deleted file mode 100644 index 58977b3..0000000 --- a/examples/esp8266/command_center/dht22.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#include -#include -#include -#include -#include "dht22.h" - - -#define DHTPIN 2 // Pin which is connected to the DHT sensor. -#define DHTTYPE DHT22 // DHT 22 (AM2302) -// See guide for details on sensor wiring and usage: -// https://learn.adafruit.com/dht/overview -DHT_Unified dht(DHTPIN, DHTTYPE); -uint32_t delayMS; -uint32_t nextSampleAllowedMS = 0; - -void initDht(void) { - // Initialize device. - dht.begin(); - Serial.println("DHTxx Unified Sensor Example"); - // Print temperature sensor details. - sensor_t sensor; - dht.temperature().getSensor(&sensor); - Serial.println("------------------------------------"); - Serial.println("Temperature"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" *C"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" *C"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" *C"); - Serial.println("------------------------------------"); - // Print humidity sensor details. - dht.humidity().getSensor(&sensor); - Serial.println("------------------------------------"); - Serial.println("Humidity"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println("%"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println("%"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println("%"); - Serial.println("------------------------------------"); - // Set delay between sensor readings based on sensor details. - delayMS = sensor.min_delay / 1000; -} - -void getNextSample(float* Temperature, float* Humidity) -{ - // Enforce a delay between measurements. - uint32_t currTimeMS = millis(); - if (currTimeMS < nextSampleAllowedMS) return; - nextSampleAllowedMS = currTimeMS + delayMS; - - // Get temperature event and print its value. - sensors_event_t event; - dht.temperature().getEvent(&event); - if (isnan(event.temperature)) { - Serial.println("Error reading temperature!"); - } - else { - Serial.print("Temperature: "); - Serial.print(event.temperature); - Serial.println(" *C"); - *Temperature = event.temperature; - } - // Get humidity event and print its value. - dht.humidity().getEvent(&event); - if (isnan(event.relative_humidity)) { - Serial.println("Error reading humidity!"); - } - else { - Serial.print("Humidity: "); - Serial.print(event.relative_humidity); - Serial.println("%"); - *Humidity = event.relative_humidity; - } -} - - diff --git a/examples/esp8266/command_center/dht22.h b/examples/esp8266/command_center/dht22.h deleted file mode 100644 index 3e38817..0000000 --- a/examples/esp8266/command_center/dht22.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifndef __DHT22_H -#define __DHT22_H - - -#ifdef __cplusplus -extern "C" { -#endif - -void initDht(void); -void getNextSample(float* Temperature, float* Humidity); - -#ifdef __cplusplus -} -#endif - - -#endif//__DHT22_H - diff --git a/examples/esp8266/remote_monitoring/dht22.cpp b/examples/esp8266/remote_monitoring/dht22.cpp deleted file mode 100644 index 58977b3..0000000 --- a/examples/esp8266/remote_monitoring/dht22.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#include -#include -#include -#include -#include "dht22.h" - - -#define DHTPIN 2 // Pin which is connected to the DHT sensor. -#define DHTTYPE DHT22 // DHT 22 (AM2302) -// See guide for details on sensor wiring and usage: -// https://learn.adafruit.com/dht/overview -DHT_Unified dht(DHTPIN, DHTTYPE); -uint32_t delayMS; -uint32_t nextSampleAllowedMS = 0; - -void initDht(void) { - // Initialize device. - dht.begin(); - Serial.println("DHTxx Unified Sensor Example"); - // Print temperature sensor details. - sensor_t sensor; - dht.temperature().getSensor(&sensor); - Serial.println("------------------------------------"); - Serial.println("Temperature"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" *C"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" *C"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" *C"); - Serial.println("------------------------------------"); - // Print humidity sensor details. - dht.humidity().getSensor(&sensor); - Serial.println("------------------------------------"); - Serial.println("Humidity"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println("%"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println("%"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println("%"); - Serial.println("------------------------------------"); - // Set delay between sensor readings based on sensor details. - delayMS = sensor.min_delay / 1000; -} - -void getNextSample(float* Temperature, float* Humidity) -{ - // Enforce a delay between measurements. - uint32_t currTimeMS = millis(); - if (currTimeMS < nextSampleAllowedMS) return; - nextSampleAllowedMS = currTimeMS + delayMS; - - // Get temperature event and print its value. - sensors_event_t event; - dht.temperature().getEvent(&event); - if (isnan(event.temperature)) { - Serial.println("Error reading temperature!"); - } - else { - Serial.print("Temperature: "); - Serial.print(event.temperature); - Serial.println(" *C"); - *Temperature = event.temperature; - } - // Get humidity event and print its value. - dht.humidity().getEvent(&event); - if (isnan(event.relative_humidity)) { - Serial.println("Error reading humidity!"); - } - else { - Serial.print("Humidity: "); - Serial.print(event.relative_humidity); - Serial.println("%"); - *Humidity = event.relative_humidity; - } -} - - diff --git a/examples/esp8266/remote_monitoring/dht22.h b/examples/esp8266/remote_monitoring/dht22.h deleted file mode 100644 index 3e38817..0000000 --- a/examples/esp8266/remote_monitoring/dht22.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifndef __DHT22_H -#define __DHT22_H - - -#ifdef __cplusplus -extern "C" { -#endif - -void initDht(void); -void getNextSample(float* Temperature, float* Humidity); - -#ifdef __cplusplus -} -#endif - - -#endif//__DHT22_H - diff --git a/examples/esp8266/remote_monitoring/remote_monitoring.c b/examples/esp8266/remote_monitoring/remote_monitoring.c deleted file mode 100644 index 28c5c64..0000000 --- a/examples/esp8266/remote_monitoring/remote_monitoring.c +++ /dev/null @@ -1,264 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#include "AzureIoTHub.h" -#include "sdk/schemaserializer.h" -#include "dht22.h" - - -// Find under Microsoft Azure IoT Suite -> DEVICES -> -> Device Details and Authentication Keys -//static const char* deviceId = "[DEVICEID]"; -//static const char* deviceKey = "[KEY 1 or 2]"; -//static const char* hubName = "[HOSTNAME]"; -//static const char* hubSuffix = "azure-devices.net"; -static const char* deviceId = "[device-id]"; -static const char* deviceKey = "[device-key]"; -static const char* hubName = "[hub-name]"; -static const char* hubSuffix = "azure-devices.net"; - - -// Define the Model -BEGIN_NAMESPACE(Contoso); - -DECLARE_STRUCT(SystemProperties, - ascii_char_ptr, DeviceID, - _Bool, Enabled -); - -DECLARE_STRUCT(DeviceProperties, -ascii_char_ptr, DeviceID, -_Bool, HubEnabledState -); - -DECLARE_MODEL(Thermostat, - - /* Event data (temperature, external temperature and humidity) */ - WITH_DATA(int, Temperature), - WITH_DATA(int, ExternalTemperature), - WITH_DATA(int, Humidity), - WITH_DATA(ascii_char_ptr, DeviceId), - - /* Device Info - This is command metadata + some extra fields */ - WITH_DATA(ascii_char_ptr, ObjectType), - WITH_DATA(_Bool, IsSimulatedDevice), - WITH_DATA(ascii_char_ptr, Version), - WITH_DATA(DeviceProperties, DeviceProperties), - WITH_DATA(ascii_char_ptr_no_quotes, Commands), - - /* Commands implemented by the device */ - WITH_ACTION(SetTemperature, int, temperature), - WITH_ACTION(SetHumidity, int, humidity) -); - -END_NAMESPACE(Contoso); - -EXECUTE_COMMAND_RESULT SetTemperature(Thermostat* thermostat, int temperature) -{ - LogInfo("Received temperature %d\r\n", temperature); - thermostat->Temperature = temperature; - return EXECUTE_COMMAND_SUCCESS; -} - -EXECUTE_COMMAND_RESULT SetHumidity(Thermostat* thermostat, int humidity) -{ - LogInfo("Received humidity %d\r\n", humidity); - thermostat->Humidity = humidity; - return EXECUTE_COMMAND_SUCCESS; -} - -static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size) -{ - IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size); - if (messageHandle == NULL) - { - LogInfo("unable to create a new IoTHubMessage\r\n"); - } - else - { - if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK) - { - LogInfo("failed to hand over the message to IoTHubClient"); - } - else - { - LogInfo("IoTHubClient accepted the message for delivery\r\n"); - } - - IoTHubMessage_Destroy(messageHandle); - } - free((void*)buffer); -} - -/*this function "links" IoTHub to the serialization library*/ -static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback) -{ - IOTHUBMESSAGE_DISPOSITION_RESULT result; - const unsigned char* buffer; - size_t size; - if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK) - { - LogInfo("unable to IoTHubMessage_GetByteArray\r\n"); - result = EXECUTE_COMMAND_ERROR; - } - else - { - /*buffer is not zero terminated*/ - char* temp = malloc(size + 1); - if (temp == NULL) - { - LogInfo("failed to malloc\r\n"); - result = EXECUTE_COMMAND_ERROR; - } - else - { - EXECUTE_COMMAND_RESULT executeCommandResult; - - memcpy(temp, buffer, size); - temp[size] = '\0'; - executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp); - result = - (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED : - (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED : - IOTHUBMESSAGE_REJECTED; - free(temp); - } - } - return result; -} - -void remote_monitoring_run(void) -{ - initDht(); - - srand((unsigned int)time(NULL)); - if (serializer_init(NULL) != SERIALIZER_OK) - { - LogInfo("Failed on serializer_init\r\n"); - } - else - { - IOTHUB_CLIENT_CONFIG config; - IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle; - - config.deviceId = deviceId; - config.deviceKey = deviceKey; - config.iotHubName = hubName; - config.iotHubSuffix = hubSuffix; - config.protocol = HTTP_Protocol; - - iotHubClientHandle = IoTHubClient_LL_Create(&config); - if (iotHubClientHandle == NULL) - { - LogInfo("Failed on IoTHubClient_CreateFromConnectionString\r\n"); - } - else - { -#ifdef MBED_BUILD_TIMESTAMP - // For mbed add the certificate information - if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) - { - LogInfo("failure to set option \"TrustedCerts\"\r\n"); - } -#endif // MBED_BUILD_TIMESTAMP - - Thermostat* thermostat = CREATE_MODEL_INSTANCE(Contoso, Thermostat); - if (thermostat == NULL) - { - LogInfo("Failed on CREATE_MODEL_INSTANCE\r\n"); - } - else - { - STRING_HANDLE commandsMetadata; - - if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, thermostat) != IOTHUB_CLIENT_OK) - { - LogInfo("unable to IoTHubClient_SetMessageCallback\r\n"); - } - else - { - - /* send the device info upon startup so that the cloud app knows - what commands are available and the fact that the device is up */ - thermostat->ObjectType = "DeviceInfo"; - thermostat->IsSimulatedDevice = false; - thermostat->Version = "1.0"; - thermostat->DeviceProperties.HubEnabledState = true; - thermostat->DeviceProperties.DeviceID = (char*)deviceId; - - commandsMetadata = STRING_new(); - if (commandsMetadata == NULL) - { - LogInfo("Failed on creating string for commands metadata\r\n"); - } - else - { - /* Serialize the commands metadata as a JSON string before sending */ - if (SchemaSerializer_SerializeCommandMetadata(GET_MODEL_HANDLE(Contoso, Thermostat), commandsMetadata) != SCHEMA_SERIALIZER_OK) - { - LogInfo("Failed serializing commands metadata\r\n"); - } - else - { - unsigned char* buffer; - size_t bufferSize; - thermostat->Commands = (char*)STRING_c_str(commandsMetadata); - - /* Here is the actual send of the Device Info */ - if (SERIALIZE(&buffer, &bufferSize, thermostat->ObjectType, thermostat->Version, thermostat->IsSimulatedDevice, thermostat->DeviceProperties, thermostat->Commands) != IOT_AGENT_OK) - { - LogInfo("Failed serializing\r\n"); - } - else - { - sendMessage(iotHubClientHandle, buffer, bufferSize); - } - - } - - STRING_delete(commandsMetadata); - } - - thermostat->DeviceId = (char*)deviceId; - int sendCycle = 10; - int currentCycle = 0; - while (1) - { - if(currentCycle >= sendCycle) { - float Temp; - float Humi; - getNextSample(&Temp, &Humi); - //thermostat->Temperature = 50 + (rand() % 10 + 2); - thermostat->Temperature = (int)round(Temp); - thermostat->ExternalTemperature = 55 + (rand() % 5 + 2); - //thermostat->Humidity = 50 + (rand() % 8 + 2); - thermostat->Humidity = (int)round(Humi); - currentCycle = 0; - unsigned char*buffer; - size_t bufferSize; - - LogInfo("Sending sensor value Temperature = %d, Humidity = %d\r\n", thermostat->Temperature, thermostat->Humidity); - - if (SERIALIZE(&buffer, &bufferSize, thermostat->DeviceId, thermostat->Temperature, thermostat->Humidity, thermostat->ExternalTemperature) != IOT_AGENT_OK) - { - LogInfo("Failed sending sensor value\r\n"); - } - else - { - sendMessage(iotHubClientHandle, buffer, bufferSize); - } - } - - IoTHubClient_LL_DoWork(iotHubClientHandle); - ThreadAPI_Sleep(100); - currentCycle++; - } - } - - DESTROY_MODEL_INSTANCE(thermostat); - } - IoTHubClient_LL_Destroy(iotHubClientHandle); - } - serializer_deinit(); - - } -} diff --git a/examples/esp8266/remote_monitoring/remote_monitoring.h b/examples/esp8266/remote_monitoring/remote_monitoring.h deleted file mode 100644 index 1a2fde3..0000000 --- a/examples/esp8266/remote_monitoring/remote_monitoring.h +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifndef REMOTE_MONITORING_H -#define REMOTE_MONITORING_H - -#ifdef __cplusplus -extern "C" { -#endif - - void remote_monitoring_run(void); - -#ifdef __cplusplus -} -#endif - -#endif /* REMOTE_MONITORING_H */ diff --git a/examples/esp8266/remote_monitoring/remote_monitoring.ino b/examples/esp8266/remote_monitoring/remote_monitoring.ino deleted file mode 100644 index 26fd0a5..0000000 --- a/examples/esp8266/remote_monitoring/remote_monitoring.ino +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -// Please use an Arduino IDE 1.6.8 or greater - -#include -#include -#include "remote_monitoring.h" - -//char ssid[] = "[SSID]"; // your WiFi SSID (name) -//char pass[] = "[PASSWORD]"; // your WiFi password (use for WPA, or use as key for WEP) -char ssid[] = "[SSID]"; // your WiFi SSID (name) -char pass[] = "[PASSWORD]"; // your WiFi password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; - -void setup() { - initSerial(); - initWifi(); - initTime(); -} - -void loop() { - // Run the Remote Monitoring from the Azure IoT Hub C SDK - // You must set the device id, device key, IoT Hub name and IotHub suffix in - // remote_monitoring.c - remote_monitoring_run(); -} - -void initSerial() { - // Start serial and initialize stdout - Serial.begin(115200); - Serial.setDebugOutput(true); -} - -void initWifi() { - // Attempt to connect to Wifi network: - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - - Serial.println("Connected to wifi"); -} - -void initTime() { - time_t epochTime; - - configTime(0, 0, "pool.ntp.org", "time.nist.gov"); - - while (true) { - epochTime = time(NULL); - - if (epochTime == 0) { - Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); - delay(2000); - } else { - Serial.print("Fetched NTP epoch time is: "); - Serial.println(epochTime); - break; - } - } -} - diff --git a/examples/esp8266/simplesample_http/simplesample_http.ino b/examples/esp8266/simplesample_http/simplesample_http.ino deleted file mode 100644 index f095e07..0000000 --- a/examples/esp8266/simplesample_http/simplesample_http.ino +++ /dev/null @@ -1,62 +0,0 @@ -// Please use an Arduino IDE 1.6.8 or greater - -#include -#include -#include "simplesample_http.h" - -char ssid[] = "ssid"; // your network SSID (name) -char pass[] = "password"; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; - -void setup() { - initSerial(); - initWifi(); - initTime(); -} - -void loop() { - // Run the SimpleSample from the Azure IoT Hub SDK - // You must set the connection string in simplesample_http.c - simplesample_http_run(); -} - -void initSerial() { - // Start serial and initialize stdout - Serial.begin(115200); - Serial.setDebugOutput(true); -} - -void initWifi() { - // Attempt to connect to Wifi network: - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - - Serial.println("Connected to wifi"); -} - -void initTime() { - time_t epochTime; - - configTime(0, 0, "pool.ntp.org", "time.nist.gov"); - - while (true) { - epochTime = time(NULL); - - if (epochTime == 0) { - Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); - delay(2000); - } else { - Serial.print("Fetched NTP epoch time is: "); - Serial.println(epochTime); - break; - } - } -} \ No newline at end of file diff --git a/examples/samd/remote_monitoring/bme280.cpp b/examples/remote_monitoring/bme280.cpp similarity index 92% rename from examples/samd/remote_monitoring/bme280.cpp rename to examples/remote_monitoring/bme280.cpp index 4bd5a41..749e47f 100644 --- a/examples/samd/remote_monitoring/bme280.cpp +++ b/examples/remote_monitoring/bme280.cpp @@ -5,6 +5,7 @@ #include #include #include "bme280.h" +#include "iot_logging.h" const int Bme280_cs_pin__i = 5; bool Bme_init_result = false; @@ -33,6 +34,6 @@ void getNextSample(float* Temperature, float* Humidity) //float Pres_hPa__f = bme.readPressure() / 100; *Humidity = bme.readHumidity(); //printf("Temp=%.2f, Pres=%.2f, Humi=%.2f\n", Temp_c__f, Pres_hPa__f, Humi_pct__f); - printf("Temp=%.2f, Humi=%.2f\n", *Temperature, *Humidity); + LogInfo("Temp=%.2f, Humi=%.2f\n", *Temperature, *Humidity); } diff --git a/examples/samd/remote_monitoring/bme280.h b/examples/remote_monitoring/bme280.h similarity index 100% rename from examples/samd/remote_monitoring/bme280.h rename to examples/remote_monitoring/bme280.h diff --git a/examples/samd/remote_monitoring/remote_monitoring.c b/examples/remote_monitoring/remote_monitoring.c similarity index 99% rename from examples/samd/remote_monitoring/remote_monitoring.c rename to examples/remote_monitoring/remote_monitoring.c index 6c9b55c..3878714 100644 --- a/examples/samd/remote_monitoring/remote_monitoring.c +++ b/examples/remote_monitoring/remote_monitoring.c @@ -4,6 +4,7 @@ #include "AzureIoTHub.h" #include "sdk/schemaserializer.h" #include "bme280.h" +#include "iot_logging.h" static const char* deviceId = "[device-id]"; diff --git a/examples/samd/remote_monitoring/remote_monitoring.h b/examples/remote_monitoring/remote_monitoring.h similarity index 100% rename from examples/samd/remote_monitoring/remote_monitoring.h rename to examples/remote_monitoring/remote_monitoring.h diff --git a/examples/remote_monitoring/remote_monitoring.ino b/examples/remote_monitoring/remote_monitoring.ino new file mode 100644 index 0000000..faa7b66 --- /dev/null +++ b/examples/remote_monitoring/remote_monitoring.ino @@ -0,0 +1,141 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// change the next three lines to use on non-WiFi101 based boards/shields +#include +#include +#include + +// for ESP8266 +//#include +//#include +//#include + +// for Adafruit WINC1500 +//#include +//#include +//#include + +// for the Adafruit WINC1500 we need to create our own WiFi instance +// // Define the WINC1500 board connections below. +// #define WINC_CS 8 +// #define WINC_IRQ 7 +// #define WINC_RST 4 +// #define WINC_EN 2 // or, tie EN to VCC +// // Setup the WINC1500 connection with the pins above and the default hardware SPI. +// Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST); + +#include +#include + +#include "remote_monitoring.h" + +char ssid[] = "[Your WiFi network SSID or name]"; +char pass[] = "[Your WiFi network WPA password or WEP key]"; + +// change the next line to use on non-WiFi101 based boards/shields +WiFiSSLClient sslClient; +//WiFiClientSecure sslClient; // for ESP8266 +//Adafruit_WINC1500SSLClient sslClient; // for Adafruit WINC1500 + +AzureIoTHubClient iotHubClient(sslClient); + +void setup() { + initSerial(); + initWifi(); + initTime(); + + iotHubClient.begin(); +} + +void loop() { + // Run the Remote Monitoring from the Azure IoT Hub C SDK + // You must set the device id, device key, IoT Hub name and IotHub suffix in + // remote_monitoring.c + remote_monitoring_run(); +} + +void initSerial() { + //Initialize serial and wait for port to open: + // For SAMD boards (e.g. MKR1000, Adafruit WINC1500 based) + Serial.begin(9600); + + // Uncomment the next two lines For ESP8266 boards (and comment out the line above) + // Serial.begin(115200); + // Serial.setDebugOutput(true); + + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } +} + +void initWifi() { + // for the Adafruit WINC1500 we need to enable the chip + //pinMode(WINC_EN, OUTPUT); + //digitalWrite(WINC_EN, HIGH); + + // check for the presence of the shield : + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to Wifi network: + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + while (WiFi.begin(ssid, pass) != WL_CONNECTED) { + // unsuccessful, retry in 4 seconds + Serial.print("failed ... "); + delay(4000); + Serial.print("retrying ... "); + } + + Serial.println("Connected to wifi"); +} + +void initTime() { + // change the next line to use on non-WiFi101, for ESP8266 boards see comment below + WiFiUDP ntpUdp; + //Adafruit_WINC1500UDP ntpUdp; // for Adafruit WINC1500 + NTPClient ntpClient(ntpUdp); + + ntpClient.begin(); + + while (!ntpClient.update()) { + Serial.println("Fetching NTP epoch time failed! Waiting 5 seconds to retry."); + delay(5000); + } + + ntpClient.end(); + + unsigned long epochTime = ntpClient.getEpochTime(); + + Serial.print("Fetched NTP epoch time is: "); + Serial.println(epochTime); + + iotHubClient.setEpochTime(epochTime); + + // For ESP8266 boards comment out the above portion of the function and un-comment + // the remainder below. + + // time_t epochTime; + + // configTime(0, 0, "pool.ntp.org", "time.nist.gov"); + + // while (true) { + // epochTime = time(NULL); + + // if (epochTime == 0) { + // Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); + // delay(2000); + // } else { + // Serial.print("Fetched NTP epoch time is: "); + // Serial.println(epochTime); + // break; + // } + // } +} + diff --git a/examples/samd/command_center/NTPClient.cpp b/examples/samd/command_center/NTPClient.cpp deleted file mode 100644 index 90dd08e..0000000 --- a/examples/samd/command_center/NTPClient.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Arduino. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if defined(ARDUINO_ARCH_SAMD) -#include "NTPClient.h" - -#define LOCAL_UDP_PORT 2390 - -NTPClient::NTPClient() : - _udp() -{ -} - -int NTPClient::begin() -{ - return _udp.begin(LOCAL_UDP_PORT); -} - -uint32_t NTPClient::getEpochTime(const char* host, int port, unsigned long timeout) -{ - if (host == NULL || port < 1) { - return (uint32_t)-1; - } - - prepareRequest(); - sendRequest(host, port); - - if (!receiveResponse(timeout)) { - return (uint32_t)-1; - } - - return parseResponse(); -} - -void NTPClient::end() -{ - _udp.stop(); -} - -void NTPClient::prepareRequest() -{ - memset(_buffer, 0, NTP_PACKET_SIZE); - - // Initialize values needed to form NTP request - _buffer[0] = 0b11100011; // LI, Version, Mode - _buffer[1] = 0; // Stratum, or type of clock - _buffer[2] = 6; // Polling Interval - _buffer[3] = 0xEC; // Peer Clock Precision - - // 8 bytes of zero for Root Delay & Root Dispersion - - _buffer[12] = 49; - _buffer[13] = 0x4E; - _buffer[14] = 49; - _buffer[15] = 52; -} - -void NTPClient::sendRequest(const char* host, int port) -{ - _udp.beginPacket(host, port); - _udp.write(_buffer, NTP_PACKET_SIZE); - _udp.endPacket(); -} - -int NTPClient::receiveResponse(unsigned long timeout) -{ - long start = millis(); - int size = 0; - - while(size == 0 && (millis() - start) < timeout) { - size = _udp.parsePacket(); - } - - if (size != NTP_PACKET_SIZE) { - return 0; - } - - _udp.read(_buffer, NTP_PACKET_SIZE); - - return 1; -} - -uint32_t NTPClient::parseResponse() -{ - uint16_t high = word(_buffer[40], _buffer[41]); - uint16_t low = word(_buffer[42], _buffer[43]); - uint32_t ntpTime = high << 16 | low; // since 1900 - uint32_t epoch = ntpTime - 2208988800UL; // since 1970 - - return epoch; -} -#endif diff --git a/examples/samd/command_center/NTPClient.h b/examples/samd/command_center/NTPClient.h deleted file mode 100644 index 3990350..0000000 --- a/examples/samd/command_center/NTPClient.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Arduino. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifdef ARDUINO_SAMD_FEATHER_M0 -#include -#include -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -#include -#include -#endif - -#ifndef NTPCLIENT_H -#define NTPCLIENT_H - -#define NTP_PACKET_SIZE 48 -#define NTP_PORT 123 - -#define DEFAULT_NTP_TIMEOUT 10000 - -class NTPClient -{ - public: - NTPClient(); - int begin(); - uint32_t getEpochTime(const char* host, int port = NTP_PORT, unsigned long timeout = DEFAULT_NTP_TIMEOUT); - void end(); - - private: - void prepareRequest(); - void sendRequest(const char* host, int port); - int receiveResponse(unsigned long timeout); - uint32_t parseResponse(); - - char _buffer[NTP_PACKET_SIZE]; -#ifdef ARDUINO_SAMD_FEATHER_M0 - Adafruit_WINC1500UDP _udp; -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) - WiFiUDP _udp; -#endif - -}; - -#endif diff --git a/examples/samd/remote_monitoring/NTPClient.cpp b/examples/samd/remote_monitoring/NTPClient.cpp deleted file mode 100644 index 90dd08e..0000000 --- a/examples/samd/remote_monitoring/NTPClient.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Arduino. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if defined(ARDUINO_ARCH_SAMD) -#include "NTPClient.h" - -#define LOCAL_UDP_PORT 2390 - -NTPClient::NTPClient() : - _udp() -{ -} - -int NTPClient::begin() -{ - return _udp.begin(LOCAL_UDP_PORT); -} - -uint32_t NTPClient::getEpochTime(const char* host, int port, unsigned long timeout) -{ - if (host == NULL || port < 1) { - return (uint32_t)-1; - } - - prepareRequest(); - sendRequest(host, port); - - if (!receiveResponse(timeout)) { - return (uint32_t)-1; - } - - return parseResponse(); -} - -void NTPClient::end() -{ - _udp.stop(); -} - -void NTPClient::prepareRequest() -{ - memset(_buffer, 0, NTP_PACKET_SIZE); - - // Initialize values needed to form NTP request - _buffer[0] = 0b11100011; // LI, Version, Mode - _buffer[1] = 0; // Stratum, or type of clock - _buffer[2] = 6; // Polling Interval - _buffer[3] = 0xEC; // Peer Clock Precision - - // 8 bytes of zero for Root Delay & Root Dispersion - - _buffer[12] = 49; - _buffer[13] = 0x4E; - _buffer[14] = 49; - _buffer[15] = 52; -} - -void NTPClient::sendRequest(const char* host, int port) -{ - _udp.beginPacket(host, port); - _udp.write(_buffer, NTP_PACKET_SIZE); - _udp.endPacket(); -} - -int NTPClient::receiveResponse(unsigned long timeout) -{ - long start = millis(); - int size = 0; - - while(size == 0 && (millis() - start) < timeout) { - size = _udp.parsePacket(); - } - - if (size != NTP_PACKET_SIZE) { - return 0; - } - - _udp.read(_buffer, NTP_PACKET_SIZE); - - return 1; -} - -uint32_t NTPClient::parseResponse() -{ - uint16_t high = word(_buffer[40], _buffer[41]); - uint16_t low = word(_buffer[42], _buffer[43]); - uint32_t ntpTime = high << 16 | low; // since 1900 - uint32_t epoch = ntpTime - 2208988800UL; // since 1970 - - return epoch; -} -#endif diff --git a/examples/samd/remote_monitoring/NTPClient.h b/examples/samd/remote_monitoring/NTPClient.h deleted file mode 100644 index 3990350..0000000 --- a/examples/samd/remote_monitoring/NTPClient.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Arduino. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifdef ARDUINO_SAMD_FEATHER_M0 -#include -#include -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -#include -#include -#endif - -#ifndef NTPCLIENT_H -#define NTPCLIENT_H - -#define NTP_PACKET_SIZE 48 -#define NTP_PORT 123 - -#define DEFAULT_NTP_TIMEOUT 10000 - -class NTPClient -{ - public: - NTPClient(); - int begin(); - uint32_t getEpochTime(const char* host, int port = NTP_PORT, unsigned long timeout = DEFAULT_NTP_TIMEOUT); - void end(); - - private: - void prepareRequest(); - void sendRequest(const char* host, int port); - int receiveResponse(unsigned long timeout); - uint32_t parseResponse(); - - char _buffer[NTP_PACKET_SIZE]; -#ifdef ARDUINO_SAMD_FEATHER_M0 - Adafruit_WINC1500UDP _udp; -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) - WiFiUDP _udp; -#endif - -}; - -#endif diff --git a/examples/samd/remote_monitoring/remote_monitoring.ino b/examples/samd/remote_monitoring/remote_monitoring.ino deleted file mode 100644 index bf957b8..0000000 --- a/examples/samd/remote_monitoring/remote_monitoring.ino +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -// Use Arduino IDE 1.6.8 or later. - -#include -#include -#include -#include -#include -#include -#ifdef ARDUINO_SAMD_FEATHER_M0 -#include -#include -#include -#include -#include -#include -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -#include -#endif -#include "remote_monitoring.h" -#include "NTPClient.h" - - -#ifdef ARDUINO_SAMD_FEATHER_M0 -#define WINC_CS 8 -#define WINC_IRQ 7 -#define WINC_RST 4 -#define WINC_EN 2 - -// Setup the WINC1500 connection with the pins above and the default hardware SPI. -Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST); -#endif - - -static const char ssid[] = "[Your WiFi network SSID or name]"; -static const char pass[] = "[Your WiFi network WPA password or WEP key]"; - -int status = WL_IDLE_STATUS; - -void setup() { - // The Feather M0 loses it's COMn connection with every reset. - // This 10 s delay allows you to reselect the COM port and open the serial monitor window. - delay(10000); - - initSerial(); - - #ifdef WINC_EN - pinMode(WINC_EN, OUTPUT); - digitalWrite(WINC_EN, HIGH); - #endif - initWifi(); - - initTime(); -} - -void loop() { - // Run the Remote Monitoring from the Azure IoT Hub C SDK - // You must set the device id, device key, IoT Hub name and IotHub suffix in - // remote_monitoring.c - remote_monitoring_run(); -} - -void initSerial() { - // Start serial and initialize stdout - Serial.begin(115200); - //Serial.setDebugOutput(true); -} - -void initWifi() { - // Attempt to connect to Wifi network: - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - - Serial.println("Connected to wifi"); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void initTime() { -#ifdef ARDUINO_SAMD_FEATHER_M0 - Adafruit_WINC1500UDP _udp; -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) - WiFiUDP _udp; -#endif - - time_t epochTime = (time_t)-1; - - NTPClient ntpClient; - ntpClient.begin(); - - while (true) { - epochTime = ntpClient.getEpochTime("0.pool.ntp.org"); - - if (epochTime == (time_t)-1) { - Serial.println("Fetching NTP epoch time failed! Waiting 5 seconds to retry."); - delay(5000); - } else { - Serial.print("Fetched NTP epoch time is: "); - Serial.println(epochTime); - break; - } - } - - ntpClient.end(); - - struct timeval tv; - tv.tv_sec = epochTime; - tv.tv_usec = 0; - - settimeofday(&tv, NULL); -} - - diff --git a/examples/samd/simplesample_http/NTPClient.cpp b/examples/samd/simplesample_http/NTPClient.cpp deleted file mode 100644 index 3901a22..0000000 --- a/examples/samd/simplesample_http/NTPClient.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Arduino. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if defined(ARDUINO_ARCH_SAMD) -#include "NTPClient.h" - -#define LOCAL_UDP_PORT 2390 - -NTPClient::NTPClient() : - _udp() -{ -} - -int NTPClient::begin() -{ - return _udp.begin(LOCAL_UDP_PORT); -} - -uint32_t NTPClient::getEpochTime(const char* host, int port, unsigned long timeout) -{ - if (host == NULL || port < 1) { - return (uint32_t)-1; - } - - prepareRequest(); - sendRequest(host, port); - - if (!receiveResponse(timeout)) { - return (uint32_t)-1; - } - - return parseResponse(); -} - -void NTPClient::end() -{ - _udp.stop(); -} - -void NTPClient::prepareRequest() -{ - memset(_buffer, 0, NTP_PACKET_SIZE); - - // Initialize values needed to form NTP request - _buffer[0] = 0b11100011; // LI, Version, Mode - _buffer[1] = 0; // Stratum, or type of clock - _buffer[2] = 6; // Polling Interval - _buffer[3] = 0xEC; // Peer Clock Precision - - // 8 bytes of zero for Root Delay & Root Dispersion - - _buffer[12] = 49; - _buffer[13] = 0x4E; - _buffer[14] = 49; - _buffer[15] = 52; -} - -void NTPClient::sendRequest(const char* host, int port) -{ - _udp.beginPacket(host, port); - _udp.write(_buffer, NTP_PACKET_SIZE); - _udp.endPacket(); -} - -int NTPClient::receiveResponse(unsigned long timeout) -{ - long start = millis(); - int size = 0; - - while(size == 0 && (millis() - start) < timeout) { - size = _udp.parsePacket(); - } - - if (size != NTP_PACKET_SIZE) { - return 0; - } - - _udp.read(_buffer, NTP_PACKET_SIZE); - - return 1; -} - -uint32_t NTPClient::parseResponse() -{ - uint16_t high = word(_buffer[40], _buffer[41]); - uint16_t low = word(_buffer[42], _buffer[43]); - uint32_t ntpTime = high << 16 | low; // since 1900 - uint32_t epoch = ntpTime - 2208988800UL; // since 1970 - - return epoch; -} -#endif \ No newline at end of file diff --git a/examples/samd/simplesample_http/NTPClient.h b/examples/samd/simplesample_http/NTPClient.h deleted file mode 100644 index b160f3d..0000000 --- a/examples/samd/simplesample_http/NTPClient.h +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Arduino. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifdef ARDUINO_SAMD_FEATHER_M0 -#include -#include -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -#include -#include -#endif - -#ifndef NTPCLIENT_H -#define NTPCLIENT_H - -#define NTP_PACKET_SIZE 48 -#define NTP_PORT 123 - -#define DEFAULT_NTP_TIMEOUT 10000 - -class NTPClient -{ - public: - NTPClient(); - int begin(); - uint32_t getEpochTime(const char* host, int port = NTP_PORT, unsigned long timeout = DEFAULT_NTP_TIMEOUT); - void end(); - - private: - void prepareRequest(); - void sendRequest(const char* host, int port); - int receiveResponse(unsigned long timeout); - uint32_t parseResponse(); - - char _buffer[NTP_PACKET_SIZE]; -#ifdef ARDUINO_SAMD_FEATHER_M0 - Adafruit_WINC1500UDP _udp; -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) - WiFiUDP _udp; -#endif - -}; - -#endif \ No newline at end of file diff --git a/examples/samd/simplesample_http/simplesample_http.c b/examples/samd/simplesample_http/simplesample_http.c deleted file mode 100644 index fb82da3..0000000 --- a/examples/samd/simplesample_http/simplesample_http.c +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#include - -#include -#include - -/* This sample uses the _LL APIs of iothub_client for example purposes. -That does not mean that HTTP only works with the _LL APIs. -Simply changing the using the convenience layer (functions not having _LL) -and removing calls to _DoWork will yield the same results. */ - -#include "AzureIoTHub.h" - -static const char* connectionString = "HostName=[host].azure-devices.net;DeviceId=[device];SharedAccessKey=[key]"; - -// Define the Model -BEGIN_NAMESPACE(WeatherStation); - -DECLARE_MODEL(ContosoAnemometer, -WITH_DATA(ascii_char_ptr, DeviceId), -WITH_DATA(double, WindSpeed), -WITH_ACTION(TurnFanOn), -WITH_ACTION(TurnFanOff), -WITH_ACTION(SetAirResistance, int, Position) -); - -END_NAMESPACE(WeatherStation); - -DEFINE_ENUM_STRINGS(IOTHUB_CLIENT_CONFIRMATION_RESULT, IOTHUB_CLIENT_CONFIRMATION_RESULT_VALUES) - -EXECUTE_COMMAND_RESULT TurnFanOn(ContosoAnemometer* device) -{ - (void)device; - (void)printf("Turning fan on.\r\n"); - return EXECUTE_COMMAND_SUCCESS; -} - -EXECUTE_COMMAND_RESULT TurnFanOff(ContosoAnemometer* device) -{ - (void)device; - (void)printf("Turning fan off.\r\n"); - return EXECUTE_COMMAND_SUCCESS; -} - -EXECUTE_COMMAND_RESULT SetAirResistance(ContosoAnemometer* device, int Position) -{ - (void)device; - (void)printf("Setting Air Resistance Position to %d.\r\n", Position); - return EXECUTE_COMMAND_SUCCESS; -} - -void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback) -{ - int messageTrackingId = (intptr_t)userContextCallback; - - (void)printf("Message Id: %d Received.\r\n", messageTrackingId); - - (void)printf("Result Call Back Called! Result is: %s \r\n", ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); -} - -static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, const unsigned char* buffer, size_t size) -{ - static unsigned int messageTrackingId; - IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(buffer, size); - if (messageHandle == NULL) - { - printf("unable to create a new IoTHubMessage\r\n"); - } - else - { - if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)(uintptr_t)messageTrackingId) != IOTHUB_CLIENT_OK) - { - printf("failed to hand over the message to IoTHubClient"); - } - else - { - printf("IoTHubClient accepted the message for delivery\r\n"); - } - IoTHubMessage_Destroy(messageHandle); - } - free((void*)buffer); - messageTrackingId++; -} - -/*this function "links" IoTHub to the serialization library*/ -static IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubMessage(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback) -{ - IOTHUBMESSAGE_DISPOSITION_RESULT result; - const unsigned char* buffer; - size_t size; - if (IoTHubMessage_GetByteArray(message, &buffer, &size) != IOTHUB_MESSAGE_OK) - { - printf("unable to IoTHubMessage_GetByteArray\r\n"); - result = EXECUTE_COMMAND_ERROR; - } - else - { - /*buffer is not zero terminated*/ - char* temp = malloc(size + 1); - if (temp == NULL) - { - printf("failed to malloc\r\n"); - result = EXECUTE_COMMAND_ERROR; - } - else - { - memcpy(temp, buffer, size); - temp[size] = '\0'; - EXECUTE_COMMAND_RESULT executeCommandResult = EXECUTE_COMMAND(userContextCallback, temp); - result = - (executeCommandResult == EXECUTE_COMMAND_ERROR) ? IOTHUBMESSAGE_ABANDONED : - (executeCommandResult == EXECUTE_COMMAND_SUCCESS) ? IOTHUBMESSAGE_ACCEPTED : - IOTHUBMESSAGE_REJECTED; - free(temp); - } - } - return result; -} - -void simplesample_http_run(void) -{ - if (serializer_init(NULL) != SERIALIZER_OK) - { - (void)printf("Failed on serializer_init\r\n"); - } - else - { - IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol); - srand((unsigned int)time(NULL)); - double avgWindSpeed = 10.0; - - if (iotHubClientHandle == NULL) - { - (void)printf("Failed on IoTHubClient_LL_Create\r\n"); - } - else - { - unsigned int minimumPollingTime = 9; /*because it can poll "after 9 seconds" polls will happen effectively at ~10 seconds*/ - if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) - { - printf("failure to set option \"MinimumPollingTime\"\r\n"); - } - -#ifdef MBED_BUILD_TIMESTAMP - // For mbed add the certificate information - if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) - { - (void)printf("failure to set option \"TrustedCerts\"\r\n"); - } -#endif // MBED_BUILD_TIMESTAMP - - ContosoAnemometer* myWeather = CREATE_MODEL_INSTANCE(WeatherStation, ContosoAnemometer); - if (myWeather == NULL) - { - (void)printf("Failed on CREATE_MODEL_INSTANCE\r\n"); - } - else - { - if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, myWeather) != IOTHUB_CLIENT_OK) - { - printf("unable to IoTHubClient_SetMessageCallback\r\n"); - } - else - { - myWeather->DeviceId = "myFirstDevice"; - myWeather->WindSpeed = avgWindSpeed + (rand() % 4 + 2); - { - unsigned char* destination; - size_t destinationSize; - if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed) != IOT_AGENT_OK) - { - (void)printf("Failed to serialize\r\n"); - } - else - { - IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray(destination, destinationSize); - if (messageHandle == NULL) - { - printf("unable to create a new IoTHubMessage\r\n"); - } - else - { - if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) - { - printf("failed to hand over the message to IoTHubClient"); - } - else - { - printf("IoTHubClient accepted the message for delivery\r\n"); - } - - IoTHubMessage_Destroy(messageHandle); - } - free(destination); - } - } - - /* wait for commands */ - while (1) - { - IoTHubClient_LL_DoWork(iotHubClientHandle); - ThreadAPI_Sleep(100); - } - } - - DESTROY_MODEL_INSTANCE(myWeather); - } - IoTHubClient_LL_Destroy(iotHubClientHandle); - } - serializer_deinit(); - } -} diff --git a/examples/samd/simplesample_http/simplesample_http.h b/examples/samd/simplesample_http/simplesample_http.h deleted file mode 100644 index baf6975..0000000 --- a/examples/samd/simplesample_http/simplesample_http.h +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#ifndef SIMPLESAMPLEHTTP_H -#define SIMPLESAMPLEHTTP_H - -#ifdef __cplusplus -extern "C" { -#endif - - void simplesample_http_run(void); - -#ifdef __cplusplus -} -#endif - -#endif /* SIMPLESAMPLEHTTP_H */ diff --git a/examples/samd/simplesample_http/simplesample_http.ino b/examples/samd/simplesample_http/simplesample_http.ino deleted file mode 100644 index 23f813e..0000000 --- a/examples/samd/simplesample_http/simplesample_http.ino +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) Arduino. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -#include - -#ifdef ARDUINO_SAMD_FEATHER_M0 -#include -#include -#include -#include -#include -#include -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -#include -#endif - -#include "simplesample_http.h" -#include "NTPClient.h" -#include -#include - -#ifdef ARDUINO_SAMD_FEATHER_M0 -// Define the WINC1500 board connections below. -// If you're following the Adafruit WINC1500 board -// guide you don't need to modify these: -#define WINC_CS 8 -#define WINC_IRQ 7 -#define WINC_RST 4 -#define WINC_EN 2 // or, tie EN to VCC -// The SPI pins of the WINC1500 (SCK, MOSI, MISO) should be -// connected to the hardware SPI port of the Arduino. -// On an Uno or compatible these are SCK = #13, MISO = #12, MOSI = #11. -// On an Arduino Zero use the 6-pin ICSP header, see: -// https://www.arduino.cc/en/Reference/SPI - -// Setup the WINC1500 connection with the pins above and the default hardware SPI. -Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST); -#endif - -char ssid[] = ""; // your network SSID (name) -char pass[] = ""; // your network password (use for WPA, or use as key for WEP) -int status = WL_IDLE_STATUS; - -void setup() { - initSerial(); - initWifi(); - initTime(); -} - -void initSerial() { - Serial.begin(9600); - - while(!Serial) { - ; - } -} - -void initWifi() { -#ifdef WINC_EN - pinMode(WINC_EN, OUTPUT); - digitalWrite(WINC_EN, HIGH); -#endif - - // check for the presence of the shield : - if (WiFi.status() == WL_NO_SHIELD) { - Serial.println("WiFi shield not present"); - // don't continue: - while (true); - } - - // attempt to connect to Wifi network: - while (status != WL_CONNECTED) { - Serial.print("Attempting to connect to SSID: "); - Serial.println(ssid); - // Connect to WPA/WPA2 network. Change this line if using open or WEP network: - status = WiFi.begin(ssid, pass); - - if (status != WL_CONNECTED) { - // wait 10 seconds for connection: - delay(10000); - } - } - - Serial.println("Connected to wifi"); -} - -void initTime() { -#ifdef ARDUINO_SAMD_FEATHER_M0 - Adafruit_WINC1500UDP _udp; -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) - WiFiUDP _udp; -#endif - - time_t epochTime = (time_t)-1; - - NTPClient ntpClient; - ntpClient.begin(); - - while (true) { - epochTime = ntpClient.getEpochTime("0.pool.ntp.org"); - - if (epochTime == (time_t)-1) { - Serial.println("Fetching NTP epoch time failed! Waiting 5 seconds to retry."); - delay(5000); - } else { - Serial.print("Fetched NTP epoch time is: "); - Serial.println(epochTime); - break; - } - } - - ntpClient.end(); - - struct timeval tv; - tv.tv_sec = epochTime; - tv.tv_usec = 0; - - settimeofday(&tv, NULL); - -} - -void loop() { - simplesample_http_run(); -} - diff --git a/examples/esp8266/simplesample_http/simplesample_http.c b/examples/simplesample_http/simplesample_http.c similarity index 98% rename from examples/esp8266/simplesample_http/simplesample_http.c rename to examples/simplesample_http/simplesample_http.c index 3681b29..6b70a96 100644 --- a/examples/esp8266/simplesample_http/simplesample_http.c +++ b/examples/simplesample_http/simplesample_http.c @@ -5,7 +5,6 @@ #include #include -#include /* This sample uses the _LL APIs of iothub_client for example purposes. That does not mean that HTTP only works with the _LL APIs. @@ -13,6 +12,7 @@ Simply changing the using the convenience layer (functions not having _LL) and removing calls to _DoWork will yield the same results. */ #include "AzureIoTHub.h" +#include "iot_logging.h" static const char* connectionString = "HostName=[host].azure-devices.net;DeviceId=[device];SharedAccessKey=[key]"; @@ -130,7 +130,7 @@ void simplesample_http_run(void) { IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol); srand((unsigned int)time(NULL)); - int avgWindSpeed = 10.0; + int avgWindSpeed = 10; if (iotHubClientHandle == NULL) { @@ -185,7 +185,7 @@ void simplesample_http_run(void) { if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK) { - LogInfo("failed to hand over the message to IoTHubClient\r\n"); + LogInfo("failed to hand over the message to IoTHubClient"); } else { diff --git a/examples/esp8266/simplesample_http/simplesample_http.h b/examples/simplesample_http/simplesample_http.h similarity index 100% rename from examples/esp8266/simplesample_http/simplesample_http.h rename to examples/simplesample_http/simplesample_http.h diff --git a/examples/simplesample_http/simplesample_http.ino b/examples/simplesample_http/simplesample_http.ino new file mode 100644 index 0000000..e98c4c9 --- /dev/null +++ b/examples/simplesample_http/simplesample_http.ino @@ -0,0 +1,137 @@ +// Copyright (c) Arduino. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// change the next three lines to use on non-WiFi101 based boards/shields +#include +#include +#include + +// for ESP8266 +//#include +//#include +//#include + +// for Adafruit WINC1500 +//#include +//#include +//#include + +// for the Adafruit WINC1500 we need to create our own WiFi instance +// // Define the WINC1500 board connections below. +// #define WINC_CS 8 +// #define WINC_IRQ 7 +// #define WINC_RST 4 +// #define WINC_EN 2 // or, tie EN to VCC +// // Setup the WINC1500 connection with the pins above and the default hardware SPI. +// Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST); + +#include +#include + +#include "simplesample_http.h" + +char ssid[] = "yourNetwork"; // your network SSID (name) +char pass[] = "yourPassword"; // your network password (use for WPA, or use as key for WEP) + +// change the next line to use on non-WiFi101 based boards/shields +WiFiSSLClient sslClient; +//WiFiClientSecure sslClient; // for ESP8266 +//Adafruit_WINC1500SSLClient sslClient; // for Adafruit WINC1500 + +AzureIoTHubClient iotHubClient(sslClient); + +void setup() { + initSerial(); + initWifi(); + initTime(); + + iotHubClient.begin(); +} + +void loop() { + simplesample_http_run(); +} + +void initSerial() { + //Initialize serial and wait for port to open: + // For SAMD boards (e.g. MKR1000, Adafruit WINC1500 based) + Serial.begin(9600); + + // Uncomment the next two lines For ESP8266 boards (and comment out the line above) + // Serial.begin(115200); + // Serial.setDebugOutput(true); + + while (!Serial) { + ; // wait for serial port to connect. Needed for native USB port only + } +} + +void initWifi() { + // for the Adafruit WINC1500 we need to enable the chip + //pinMode(WINC_EN, OUTPUT); + //digitalWrite(WINC_EN, HIGH); + + // check for the presence of the shield : + if (WiFi.status() == WL_NO_SHIELD) { + Serial.println("WiFi shield not present"); + // don't continue: + while (true); + } + + // attempt to connect to Wifi network: + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + + // Connect to WPA/WPA2 network. Change this line if using open or WEP network: + while (WiFi.begin(ssid, pass) != WL_CONNECTED) { + // unsuccessful, retry in 4 seconds + Serial.print("failed ... "); + delay(4000); + Serial.print("retrying ... "); + } + + Serial.println("Connected to wifi"); +} + +void initTime() { + // change the next line to use on non-WiFi101, for ESP8266 boards see comment below + WiFiUDP ntpUdp; + //Adafruit_WINC1500UDP ntpUdp; // for Adafruit WINC1500 + NTPClient ntpClient(ntpUdp); + + ntpClient.begin(); + + while (!ntpClient.update()) { + Serial.println("Fetching NTP epoch time failed! Waiting 5 seconds to retry."); + delay(5000); + } + + ntpClient.end(); + + unsigned long epochTime = ntpClient.getEpochTime(); + + Serial.print("Fetched NTP epoch time is: "); + Serial.println(epochTime); + + iotHubClient.setEpochTime(epochTime); + + // For ESP8266 boards comment out the above portion of the function and un-comment + // the remainder below. + + // time_t epochTime; + + // configTime(0, 0, "pool.ntp.org", "time.nist.gov"); + + // while (true) { + // epochTime = time(NULL); + + // if (epochTime == 0) { + // Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry."); + // delay(2000); + // } else { + // Serial.print("Fetched NTP epoch time is: "); + // Serial.println(epochTime); + // break; + // } + // } +} diff --git a/keywords.txt b/keywords.txt new file mode 100644 index 0000000..64f59fc --- /dev/null +++ b/keywords.txt @@ -0,0 +1,20 @@ +####################################### +# Syntax Coloring Map For WiFi +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +AzureIoTHubClient KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +setEpochTime KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/src/AzureIoTHub.h b/src/AzureIoTHub.h index 950cf65..136fd93 100644 --- a/src/AzureIoTHub.h +++ b/src/AzureIoTHub.h @@ -1,6 +1,9 @@ // Copyright (c) Arduino. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#ifndef AZUREIOTHUB_H +#define AZUREIOTHUB_H + #include "sdk/lock.h" #include "sdk/threadapi.h" #include "sdk/serializer.h" @@ -9,5 +12,6 @@ #include "sdk/iothub_message.h" #include "sdk/iothubtransporthttp.h" +#include "AzureIoTHubClient.h" - +#endif diff --git a/src/AzureIoTHubClient.cpp b/src/AzureIoTHubClient.cpp new file mode 100644 index 0000000..0d6a4ec --- /dev/null +++ b/src/AzureIoTHubClient.cpp @@ -0,0 +1,29 @@ +// Copyright (c) Arduino. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#include +#include + +#include + +Client* AzureIoTHubClient::sslClient = NULL; + +AzureIoTHubClient::AzureIoTHubClient(Client& sslClient) +{ + AzureIoTHubClient::sslClient = &sslClient; +} + +void AzureIoTHubClient::begin() +{ +} + +void AzureIoTHubClient::setEpochTime(unsigned long epochTime) +{ +#ifndef ARDUINO_ARCH_ESP8266 + struct timeval tv; + + tv.tv_sec = epochTime; + tv.tv_usec = 0; + settimeofday(&tv, NULL); +#endif +} diff --git a/src/AzureIoTHubClient.h b/src/AzureIoTHubClient.h new file mode 100644 index 0000000..874d5aa --- /dev/null +++ b/src/AzureIoTHubClient.h @@ -0,0 +1,21 @@ +#ifndef AZUREIOTHUBCLIENT_H +#define AZUREIOTHUBCLIENT_H + +#ifdef __cplusplus + +#include + +class AzureIoTHubClient +{ +public: + AzureIoTHubClient(Client& sslClient); + + void begin(); + void setEpochTime(unsigned long epochTime); + + static Client* sslClient; +}; + +#endif + +#endif diff --git a/src/httpapi.cpp b/src/httpapi.cpp index 608b2a2..35d0552 100644 --- a/src/httpapi.cpp +++ b/src/httpapi.cpp @@ -7,18 +7,17 @@ #include "sdk/httpapi.h" #include "iot_logging.h" +#include "AzureIoTHubClient.h" #include "util/HTTPSClient.h" -#define POOL_SIZE 1 -HTTPSClient httpsClients[POOL_SIZE]; +HTTPSClient* httpsClient = NULL; HTTPAPI_RESULT HTTPAPI_Init(void) { - for (int i = 0; i < POOL_SIZE; i++) { - httpsClients[i] = HTTPSClient(); - httpsClients[i].setTimeout(10000); - } + httpsClient = new HTTPSClient(AzureIoTHubClient::sslClient); + httpsClient->setTimeout(10000); + return HTTPAPI_OK; } @@ -30,23 +29,14 @@ HTTP_HANDLE HTTPAPI_CreateConnection(const char* hostName) { HTTPSClient* client = NULL; - // find an available client to use - for (int i = 0; i < POOL_SIZE; i++) { - if (!httpsClients[i].connected()) { - client = &httpsClients[i]; - break; - } - } - - if (client) { - if (!client->begin(hostName)) { - // connection failed - LogError("HTTPS connection to %s failed\n", hostName); - client = NULL; - } - } else { + if (httpsClient->connected()) { // no clients available LogError("No HTTPS clients available\n"); + } else if (httpsClient->begin(hostName)) { + client = httpsClient; + } else { + // connection failed + LogError("HTTPS connection to %s failed\n", hostName); } return ((HTTP_HANDLE)client); diff --git a/src/util/HTTPSClient.cpp b/src/util/HTTPSClient.cpp index 55a0310..160a4cf 100644 --- a/src/util/HTTPSClient.cpp +++ b/src/util/HTTPSClient.cpp @@ -1,6 +1,8 @@ // Copyright (c) Arduino. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +#include + #include "HTTPSClient.h" // Uncomment the below to see HTTP traffic in @@ -8,14 +10,25 @@ // #define DEBUG_STREAM Serial -HTTPSClient::HTTPSClient() : +HTTPSClient::HTTPSClient(Client* sslClient) : + _sslClient(sslClient), _contentLength(0) { } int HTTPSClient::begin(const char* host, int port) { - return connect(host, port); + return _sslClient->connect(host, port); +} + +uint8_t HTTPSClient::connected() +{ + return _sslClient->connected(); +} + +void HTTPSClient::setTimeout(unsigned long timeout) +{ + _sslClient->setTimeout(timeout); } int HTTPSClient::sendRequest(const char* method, const char* path) @@ -130,24 +143,35 @@ int HTTPSClient::readHeader(String& name, String& value) void HTTPSClient::end() { - stop(); + _sslClient->stop(); +} + +int HTTPSClient::readBody(unsigned char *content, int length) +{ + _sslClient->readBytes(content, length); +#ifdef DEBUG_STREAM + DEBUG_STREAM.write(content, length); + DEBUG_STREAM.println(); +#endif + return 1; +} + +size_t HTTPSClient::write(uint8_t b) +{ + return _sslClient->write(b); +} + +size_t HTTPSClient::write(const uint8_t *buffer, size_t size) +{ + return _sslClient->write(buffer, size); } String HTTPSClient::readLine() { - return readStringUntil('\n'); + return _sslClient->readStringUntil('\n'); } size_t HTTPSClient::contentLength() { return _contentLength; } - -int HTTPSClient::readBody(unsigned char *content, int length) -{ - readBytes(content, length); -#ifdef DEBUG_STREAM - DEBUG_STREAM.write(content, length); -#endif - return 1; -} \ No newline at end of file diff --git a/src/util/HTTPSClient.h b/src/util/HTTPSClient.h index 1366797..d153166 100644 --- a/src/util/HTTPSClient.h +++ b/src/util/HTTPSClient.h @@ -5,27 +5,18 @@ #ifndef HTTPSCLIENT_H #define HTTPSCLIENT_H -#ifdef ARDUINO_SAMD_FEATHER_M0 -#include -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -#include -#elif defined(ESP8266) -#include -#endif +#include +#include #define HTTPS_PORT 443 -#ifdef ARDUINO_SAMD_FEATHER_M0 -class HTTPSClient : public Adafruit_WINC1500SSLClient -#elif defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) -class HTTPSClient : public WiFiSSLClient -#elif defined(ESP8266) -class HTTPSClient : public WiFiClientSecure -#endif +class HTTPSClient : Print { public: - HTTPSClient(); + HTTPSClient(Client* sslClient); int begin(const char* host, int port = HTTPS_PORT); + uint8_t connected(); + void setTimeout(unsigned long timeout); int sendRequest(const char* method, const char* path); int sendHeader(const String& header); int sendBody(const unsigned char *content, int length); @@ -35,9 +26,13 @@ class HTTPSClient : public WiFiClientSecure int readBody(unsigned char *content, int length); void end(); + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buffer, size_t size); + private: String readLine(); + Client* _sslClient; size_t _contentLength; };