From 8885d5e36457d90545661a73c12dd82d4d87fed4 Mon Sep 17 00:00:00 2001 From: aziotclb Date: Thu, 9 Nov 2017 17:02:55 -0800 Subject: [PATCH] Sync Arduino libraries with latest Azure IoT SDK 1.0.41 --- README.md | 68 ++--- examples/README.md | 3 - examples/esp8266/simplesample_http/README.md | 4 + .../esp8266/simplesample_http/iot_configs.h | 20 ++ .../simplesample_http/simplesample_http.c | 18 +- .../simplesample_http/simplesample_http.h | 0 .../simplesample_http/simplesample_http.ino | 86 ++++++ examples/samd/simplesample_http/NTPClient.cpp | 92 +++++++ examples/samd/simplesample_http/NTPClient.h | 33 +++ examples/samd/simplesample_http/README.md | 4 + examples/samd/simplesample_http/iot_configs.h | 26 ++ .../simplesample_http/simplesample_http.c | 249 ++++++++++++++++++ .../simplesample_http/simplesample_http.h | 17 ++ .../simplesample_http/simplesample_http.ino | 123 +++++++++ .../simplesample_http/simplesample_http.ino | 133 ---------- library.properties | 2 +- src/AzureIoTUtility.h | 2 +- src/adapters/xlogging_dump_bytes.c | 71 +++++ .../aziotsharedutil.def | 1 - src/azure_c_shared_utility/crt_abstractions.h | 1 - src/azure_c_shared_utility/httpapiexsas.c | 9 +- src/azure_c_shared_utility/sastoken.c | 18 +- src/azure_c_shared_utility/singlylinkedlist.h | 1 - src/azure_c_shared_utility/strings.c | 12 +- src/azure_c_shared_utility/utf8_checker.c | 1 - src/azure_c_shared_utility/utf8_checker.h | 1 - src/azure_c_shared_utility/uws_client.h | 1 - .../uws_frame_encoder.h | 1 - src/azure_c_shared_utility/vector.h | 1 - src/azure_c_shared_utility/vector_types.h | 1 - src/azure_c_shared_utility/xlogging.c | 65 ----- src/azure_c_shared_utility/xlogging.h | 58 ++-- 32 files changed, 800 insertions(+), 322 deletions(-) delete mode 100644 examples/README.md create mode 100644 examples/esp8266/simplesample_http/README.md create mode 100644 examples/esp8266/simplesample_http/iot_configs.h rename examples/{ => esp8266}/simplesample_http/simplesample_http.c (95%) rename examples/{ => esp8266}/simplesample_http/simplesample_http.h (100%) create mode 100644 examples/esp8266/simplesample_http/simplesample_http.ino create mode 100644 examples/samd/simplesample_http/NTPClient.cpp create mode 100644 examples/samd/simplesample_http/NTPClient.h create mode 100644 examples/samd/simplesample_http/README.md create mode 100644 examples/samd/simplesample_http/iot_configs.h create mode 100644 examples/samd/simplesample_http/simplesample_http.c create mode 100644 examples/samd/simplesample_http/simplesample_http.h create mode 100644 examples/samd/simplesample_http/simplesample_http.ino delete mode 100644 examples/simplesample_http/simplesample_http.ino create mode 100644 src/adapters/xlogging_dump_bytes.c diff --git a/README.md b/README.md index 0b73373..cff6493 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,32 @@ -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact +[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. -# AzureIoTHub - Azure IoT Hub library for Arduino +# AzureIoTUtility - Azure IoT Utility library for Arduino -This library is a port of the [Microsoft Azure C Shared Utility](https://github.com/Azure/azure-c-shared-utility/blob/master/c/readme.md) to Arduino. It allows you to use several Arduino compatible boards with Azure IoT Hub. Please submit any contribution directly to [azure-c-shared-utility](https://github.com/Azure/azure-c-shared-utility). +This library is a port of the +[Microsoft Azure C Shared Utility](https://github.com/Azure/azure-c-shared-utility/blob/master/c/readme.md) +to Arduino. It allows you to use several Arduino compatible boards with Azure IoT Hub. -Currently supported hardware: +## Contributors + +### **Pull request caution!** +All of the files in these Arduino library directories are auto-generated +by the Azure IoT C SDK release process, so pull requests cannot be +accepted in this repo. +Your Arduino-specific contributions will be welcomed with open arms in these locations: +* [AzureIoTHub Arduino-specific sources](https://github.com/Azure/azure-iot-pal-arduino/tree/master/build_all/base-libraries/AzureIoTHub) +* [AzureIoTProtocol_HTTP sources](https://github.com/Azure/azure-iot-pal-arduino/tree/master/build_all/base-libraries/AzureIoTProtocol_HTTP) +* [AzureIoTProtocol_MQTT Arduino-specific sources](https://github.com/Azure/azure-iot-pal-arduino/tree/master/build_all/base-libraries/AzureIoTProtocol_MQTT) +* [AzureIoTUtility Arduino-specific sources](https://github.com/Azure/azure-iot-pal-arduino/tree/master/build_all/base-libraries/AzureIoTUtility) + +Contributions for code that is not Arduino-specific can be made to the +[Azuure IoT C SDK](https://github.com/azure/azure-iot-sdk-c) + +## Currently supported hardware - Atmel SAMD Based boards - - Arduino/Genuino [MKR1000](https://www.arduino.cc/en/Main/ArduinoMKR1000) - - Arduino/Genuino [Zero](https://www.arduino.cc/en/Main/ArduinoBoardZero) and [WiFi Shield 101](https://www.arduino.cc/en/Main/ArduinoWiFiShield101) - Adafruit [Feather M0](https://www.adafruit.com/products/3010) - ESP8266 based boards with [esp8266/arduino](https://github.com/esp8266/arduino) - SparkFun [Thing](https://www.sparkfun.com/products/13711) @@ -16,25 +35,17 @@ Currently supported hardware: ## Prerequisites You should have the following ready before beginning with any board: -- [Setup your IoT hub](https://github.com/Azure/azure-iot-sdks/blob/master/doc/setup_iothub.md) -- [Provision your device and get its credentials](https://github.com/Azure/azure-iot-sdks/blob/master/doc/manage_iot_hub.md) +- [Setup your IoT hub](https://github.com/Azure/azure-iot-device-ecosystem/blob/master/setup_iothub.md) +- [Provision your device and get its credentials](https://github.com/Azure/azure-iot-device-ecosystem/blob/master/setup_iothub.md#create-new-device-in-the-iot-hub-device-identity-registry) - [Arduino IDE 1.6.12](https://www.arduino.cc/en/Main/Software) -- Install the `AzureIoTHub` library via the Arduino IDE Library Manager -- Install the `AzureIoTUtility` library via the Arduino IDE Library Manager -- Install the `AzureIoTProtocol_HTTP` library via the Arduino IDE Library Manager +- Install the [`AzureIoTHub`](https://github.com/Azure/azure-iot-arduino) library via the Arduino IDE Library Manager +- Install the [`AzureIoTUtility`](https://github.com/Azure/azure-iot-arduino-utility) library via the Arduino IDE Library Manager +- Install the [`AzureIoTProtocol_HTTP`](https://github.com/Azure/azure-iot-arduino-protocol-http) library via the Arduino IDE Library Manager -# Simple Sample Instructions -## MKR1000 or Zero + Wifi101 -1. Open the `simplesample_http` example from the Arduino IDE File->Examples->AzureIoTHub menu. -2. Install the `WiFi101` library from the Arduino IDE Library Manager. -3. Install the `NTPClient` library from the Arduino IDE Library Manager. -4. Install the `RTCZero` library from the Arduino IDE Library Manager. -5. Update Wifi SSID/Password in simplesample_http.ino - * Ensure you are using a wifi network that does not require additional manual steps after connection, such as opening a web browser. -6. Update IoT Hub Connection string in simplesample_http.c +## Simple Sample Instructions -## ESP8266 +### ESP8266 ##### Sparkfun Thing, Adafruit Feather Huzzah, or generic ESP8266 board 1. Install esp8266 board support into your Arduino IDE. @@ -43,16 +54,14 @@ You should have the following ready before beginning with any board: * Open Boards Manager from Tools > Board menu and install esp8266 platform 2.2.0 or later * Select your ESP8266 board from Tools > Board menu after installation -2. Open the `simplesample_http` example from the Arduino IDE File->Examples->AzureIoTHub menu. -3. Update the sketch as directed by comments in the sample to support the ESP8266 board. -4. Update Wifi SSID/Password in simplesample_http.ino +2. Open the `simplesample_http` example from the Arduino IDE File->AzureIoTHub->ESP8266->Examples menu. +4. Update Wifi SSID/Password and IoT Hub Connection string in iot_configs.h * Ensure you are using a wifi network that does not require additional manual steps after connection, such as opening a web browser. -5. Update IoT Hub Connection string in simplesample_http.c 6. Access the [SparkFun Get Started](https://azure.microsoft.com/en-us/documentation/samples/iot-hub-c-thingdev-getstartedkit/) tutorial to learn more about Microsoft Sparkfun Dev Kit. 7. Access the [Huzzah Get Started](https://azure.microsoft.com/en-us/documentation/samples/iot-hub-c-huzzah-getstartedkit/) tutorial to learn more about Microsoft Huzzah Dev Kit. -## Adafruit Feather M0 +### Adafruit Feather M0 1. Install Feather M0 board support into your Arduino IDE. * Start Arduino and open Preferences window. * Enter `https://adafruit.github.io/arduino-board-index/package_adafruit_index.json` into Additional Board Manager URLs field. You can add multiple URLs, separating them with commas. @@ -60,12 +69,9 @@ You should have the following ready before beginning with any board: * Select your `Adafruit Feather M0` from Tools > Board menu after installation 2. Install the `WiFi101` library from the Arduino IDE Library Manager. 3. Install the `RTCZero` library from the Arduino IDE Library Manager. -4. Install the `NTPClient` library from the Arduino IDE Library Manager. -5. Open the `simplesample_http` example from the Arduino IDE File->Examples->AzureIoTHub menu. -6. Update the sketch as directed by comments in the sample to support the ESP8266 board. -7. Update Wifi SSID/Password in simplesample_http.ino +5. Open the `simplesample_http` example from the Arduino IDE File->AzureIoTHub->M0->Examples menu. +4. Update Wifi SSID/Password and IoT Hub Connection string in iot_configs.h * Ensure you are using a wifi network that does not require additional manual steps after connection, such as opening a web browser. -8. Update IoT Hub Connection string in simplesample_http.c 9. Access the [Feather M0 WiFi Get Started](https://azure.microsoft.com/en-us/documentation/samples/iot-hub-c-m0wifi-getstartedkit/) tutorial to learn more about Microsoft Feather M0 WiFi Dev Kit. ## License diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index a9e591d..0000000 --- a/examples/README.md +++ /dev/null @@ -1,3 +0,0 @@ -These examples are ports from the [Microsoft Azure IoT device SDK for C](https://github.com/Azure/azure-iot-sdks/blob/master/c/readme.md). - - * [simplesample_http](simplesample_http) is from: https://github.com/Azure/azure-iot-sdks/tree/master/c/serializer/samples/simplesample_http diff --git a/examples/esp8266/simplesample_http/README.md b/examples/esp8266/simplesample_http/README.md new file mode 100644 index 0000000..314de52 --- /dev/null +++ b/examples/esp8266/simplesample_http/README.md @@ -0,0 +1,4 @@ +### simplesample_http + +Instructions for this sample are +[here in the Azure IoT HTTP protocol library for Arduino.](https://github.com/Azure/azure-iot-arduino-protocol-http) \ No newline at end of file diff --git a/examples/esp8266/simplesample_http/iot_configs.h b/examples/esp8266/simplesample_http/iot_configs.h new file mode 100644 index 0000000..798e18b --- /dev/null +++ b/examples/esp8266/simplesample_http/iot_configs.h @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#ifndef IOT_CONFIGS_H +#define IOT_CONFIGS_H + +/** + * WiFi setup + */ +#define IOT_CONFIG_WIFI_SSID "" +#define IOT_CONFIG_WIFI_PASSWORD "" + +/** + * Find under Microsoft Azure IoT Suite -> DEVICES -> -> Device Details and Authentication Keys + * String containing Hostname, Device Id & Device Key in the format: + * "HostName=;DeviceId=;SharedAccessKey=" + */ +#define IOT_CONFIG_CONNECTION_STRING "HostName=.azure-devices.net;DeviceId=;SharedAccessKey=" + +#endif /* IOT_CONFIGS_H */ diff --git a/examples/simplesample_http/simplesample_http.c b/examples/esp8266/simplesample_http/simplesample_http.c similarity index 95% rename from examples/simplesample_http/simplesample_http.c rename to examples/esp8266/simplesample_http/simplesample_http.c index deb5555..a199ba6 100644 --- a/examples/simplesample_http/simplesample_http.c +++ b/examples/esp8266/simplesample_http/simplesample_http.c @@ -5,33 +5,19 @@ #include #include +#include "iot_configs.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. */ -#ifdef ARDUINO #include "AzureIoTHub.h" -#else -#include "azure_c_shared_utility/threadapi.h" -#include "azure_c_shared_utility/platform.h" -#include "serializer.h" -#include "iothub_client_ll.h" -#include "iothubtransporthttp.h" -#endif -#ifdef MBED_BUILD_TIMESTAMP -#define SET_TRUSTED_CERT_IN_SAMPLES -#endif // MBED_BUILD_TIMESTAMP - -#ifdef SET_TRUSTED_CERT_IN_SAMPLES -#include "certs.h" -#endif // SET_TRUSTED_CERT_IN_SAMPLES /*String containing Hostname, Device Id & Device Key in the format: */ /* "HostName=;DeviceId=;SharedAccessKey=" */ -static const char* connectionString = "[device connection string]"; +static const char* connectionString = IOT_CONFIG_CONNECTION_STRING; // Define the Model BEGIN_NAMESPACE(WeatherStation); diff --git a/examples/simplesample_http/simplesample_http.h b/examples/esp8266/simplesample_http/simplesample_http.h similarity index 100% rename from examples/simplesample_http/simplesample_http.h rename to examples/esp8266/simplesample_http/simplesample_http.h diff --git a/examples/esp8266/simplesample_http/simplesample_http.ino b/examples/esp8266/simplesample_http/simplesample_http.ino new file mode 100644 index 0000000..661568b --- /dev/null +++ b/examples/esp8266/simplesample_http/simplesample_http.ino @@ -0,0 +1,86 @@ +// 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 + +// for ESP8266 +#include +#include +#include + +#include +#include +#include + +#include "simplesample_http.h" +#include "iot_configs.h" + +static char ssid[] = IOT_CONFIG_WIFI_SSID; +static char pass[] = IOT_CONFIG_WIFI_PASSWORD; + +void setup() { + initSerial(); + initWifi(); + initTime(); +} + +void loop() { + simplesample_http_run(); +} + +void initSerial() { + // Start serial and initialize stdout + Serial.begin(115200); + Serial.setDebugOutput(true); +} + +void initWifi() { + + // 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: + WiFi.begin(ssid, pass); + + Serial.print("Waiting for Wifi connection."); + while (WiFi.status() != WL_CONNECTED) { + Serial.print("."); + delay(500); + } + + 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/samd/simplesample_http/NTPClient.cpp b/examples/samd/simplesample_http/NTPClient.cpp new file mode 100644 index 0000000..90dd08e --- /dev/null +++ b/examples/samd/simplesample_http/NTPClient.cpp @@ -0,0 +1,92 @@ +// 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/simplesample_http/NTPClient.h b/examples/samd/simplesample_http/NTPClient.h new file mode 100644 index 0000000..bed5b21 --- /dev/null +++ b/examples/samd/simplesample_http/NTPClient.h @@ -0,0 +1,33 @@ +// Copyright (c) Arduino. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#include +#include + +#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]; + WiFiUDP _udp; +}; + +#endif // NTPCLIENT_H diff --git a/examples/samd/simplesample_http/README.md b/examples/samd/simplesample_http/README.md new file mode 100644 index 0000000..314de52 --- /dev/null +++ b/examples/samd/simplesample_http/README.md @@ -0,0 +1,4 @@ +### simplesample_http + +Instructions for this sample are +[here in the Azure IoT HTTP protocol library for Arduino.](https://github.com/Azure/azure-iot-arduino-protocol-http) \ No newline at end of file diff --git a/examples/samd/simplesample_http/iot_configs.h b/examples/samd/simplesample_http/iot_configs.h new file mode 100644 index 0000000..0b6168f --- /dev/null +++ b/examples/samd/simplesample_http/iot_configs.h @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#ifndef IOT_CONFIGS_H +#define IOT_CONFIGS_H + +/** + * WiFi setup + */ +#define IOT_CONFIG_WIFI_SSID "" +#define IOT_CONFIG_WIFI_PASSWORD "" + +/** + * Find under Microsoft Azure IoT Suite -> DEVICES -> -> Device Details and Authentication Keys + * String containing Hostname, Device Id & Device Key in the format: + * "HostName=;DeviceId=;SharedAccessKey=" + */ +#define IOT_CONFIG_CONNECTION_STRING "HostName=.azure-devices.net;DeviceId=;SharedAccessKey=" + +/** + * Choose the transport protocol + */ +// #define IOT_CONFIG_MQTT // uncomment this line for MQTT +#define IOT_CONFIG_HTTP // uncomment this line for HTTP + +#endif /* IOT_CONFIGS_H */ diff --git a/examples/samd/simplesample_http/simplesample_http.c b/examples/samd/simplesample_http/simplesample_http.c new file mode 100644 index 0000000..a199ba6 --- /dev/null +++ b/examples/samd/simplesample_http/simplesample_http.c @@ -0,0 +1,249 @@ +// 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 "iot_configs.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" + + +/*String containing Hostname, Device Id & Device Key in the format: */ +/* "HostName=;DeviceId=;SharedAccessKey=" */ +static const char* connectionString = IOT_CONFIG_CONNECTION_STRING; + +// Define the Model +BEGIN_NAMESPACE(WeatherStation); + +DECLARE_MODEL(ContosoAnemometer, +WITH_DATA(ascii_char_ptr, DeviceId), +WITH_DATA(int, WindSpeed), +WITH_DATA(float, Temperature), +WITH_DATA(float, Humidity), +WITH_ACTION(TurnFanOn), +WITH_ACTION(TurnFanOff), +WITH_ACTION(SetAirResistance, int, Position) +); + +END_NAMESPACE(WeatherStation); + +static char propText[1024]; + +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) +{ + unsigned int messageTrackingId = (unsigned int)(uintptr_t)userContextCallback; + + (void)printf("Message Id: %u 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 = IOTHUBMESSAGE_ABANDONED; + } + else + { + /*buffer is not zero terminated*/ + char* temp = malloc(size + 1); + if (temp == NULL) + { + printf("failed to malloc\r\n"); + result = IOTHUBMESSAGE_ABANDONED; + } + else + { + EXECUTE_COMMAND_RESULT executeCommandResult; + + (void)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 simplesample_http_run(void) +{ + if (platform_init() != 0) + { + printf("Failed to initialize the platform.\r\n"); + } + else + { + 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); + int avgWindSpeed = 10; + float minTemperature = 20.0; + float minHumidity = 60.0; + + srand((unsigned int)time(NULL)); + + if (iotHubClientHandle == NULL) + { + (void)printf("Failed on IoTHubClient_LL_Create\r\n"); + } + else + { + // Because it can poll "after 9 seconds" polls will happen + // effectively at ~10 seconds. + // Note that for scalabilty, the default value of minimumPollingTime + // is 25 minutes. For more information, see: + // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging + unsigned int minimumPollingTime = 9; + ContosoAnemometer* myWeather; + + if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) + { + printf("failure to set option \"MinimumPollingTime\"\r\n"); + } + +#ifdef SET_TRUSTED_CERT_IN_SAMPLES + // 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 // SET_TRUSTED_CERT_IN_SAMPLES + + 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); + myWeather->Temperature = minTemperature + (rand() % 10); + myWeather->Humidity = minHumidity + (rand() % 20); + { + unsigned char* destination; + size_t destinationSize; + if (SERIALIZE(&destination, &destinationSize, myWeather->DeviceId, myWeather->WindSpeed, myWeather->Temperature, myWeather->Humidity) != CODEFIRST_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 + { + MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle); + (void)sprintf_s(propText, sizeof(propText), myWeather->Temperature > 28 ? "true" : "false"); + if (Map_AddOrUpdate(propMap, "temperatureAlert", propText) != MAP_OK) + { + printf("ERROR: Map_AddOrUpdate Failed!\r\n"); + } + + 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(); + } + platform_deinit(); + } +} diff --git a/examples/samd/simplesample_http/simplesample_http.h b/examples/samd/simplesample_http/simplesample_http.h new file mode 100644 index 0000000..baf6975 --- /dev/null +++ b/examples/samd/simplesample_http/simplesample_http.h @@ -0,0 +1,17 @@ +// 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 new file mode 100644 index 0000000..7313c31 --- /dev/null +++ b/examples/samd/simplesample_http/simplesample_http.ino @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// Please Use Arduino IDE 1.6.8 or later. + +#include "iot_configs.h" + +#include +#include +#include +#include +#include +#include +#include + + +#include "simplesample_http.h" +#include "NTPClient.h" + +#include +#include + +#ifdef ARDUINO_SAMD_FEATHER_M0 + +// Optional LIPO battery monitoring +#define VBAT_ENABLED 1 +#define VBAT_PIN A7 + +#define WINC_CS 8 +#define WINC_IRQ 7 +#define WINC_RST 4 +#define WINC_EN 2 + +#endif + + +static char ssid[] = IOT_CONFIG_WIFI_SSID; +static char pass[] = IOT_CONFIG_WIFI_PASSWORD; + +int status = WL_IDLE_STATUS; +WiFiSSLClient sslClient; + +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 ARDUINO_SAMD_FEATHER_M0 + //Configure pins for Adafruit ATWINC1500 Feather + Serial.println(F("WINC1500 on FeatherM0 detected.")); + Serial.println(F("Setting pins for WiFi101 library (WINC1500 on FeatherM0)")); + WiFi.setPins(WINC_CS, WINC_IRQ, WINC_RST, WINC_EN); + // for the Adafruit WINC1500 we need to enable the chip + pinMode(WINC_EN, OUTPUT); + digitalWrite(WINC_EN, HIGH); + Serial.println(F("Enabled WINC1500 interface for FeatherM0")); + #endif + initWifi(); + + initTime(); +} + +void loop() { + 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("\r\n\r\nAttempting 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("\r\nConnected to wifi"); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +void initTime() { + WiFiUDP _udp; + + 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/simplesample_http/simplesample_http.ino b/examples/simplesample_http/simplesample_http.ino deleted file mode 100644 index bc3e9c9..0000000 --- a/examples/simplesample_http/simplesample_http.ino +++ /dev/null @@ -1,133 +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_ARCH_ESP8266 -// for ESP8266 -#include -#include -#include -#else -#include -#include -#include -#include -#endif - -#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 // or, tie EN to VCC -#endif - -#include -#include -#include - -#include "simplesample_http.h" - -static char ssid[] = "yourNetwork"; // your network SSID (name) -static char pass[] = "yourPassword"; // your network password (use for WPA, or use as key for WEP) - -void setup() { - initSerial(); - initWifi(); - initTime(); -} - -void loop() { - simplesample_http_run(); -} - -void initSerial() { - // Start serial and initialize stdout - Serial.begin(115200); -#ifdef ARDUINO_ARCH_ESP8266 - Serial.setDebugOutput(true); -#endif -} - -void initWifi() { -#ifdef ARDUINO_SAMD_FEATHER_M0 - //Configure pins for Adafruit ATWINC1500 Feather - Serial.println(F("WINC1500 on FeatherM0 detected.")); - Serial.println(F("Setting pins for WiFi101 library (WINC1500 on FeatherM0)")); - WiFi.setPins(WINC_CS, WINC_IRQ, WINC_RST, WINC_EN); - // for the Adafruit WINC1500 we need to enable the chip - pinMode(WINC_EN, OUTPUT); - digitalWrite(WINC_EN, HIGH); - Serial.println(F("Enabled WINC1500 interface for FeatherM0")); -#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: - 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() { -#if defined(ARDUINO_SAMD_ZERO) || defined(ARDUINO_SAMD_MKR1000) || defined(ARDUINO_SAMD_FEATHER_M0) - WiFiUDP ntpUdp; - - 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); - -#elif ARDUINO_ARCH_ESP8266 - 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; - } - } -#endif -} diff --git a/library.properties b/library.properties index 1cf7a05..9be6be9 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=AzureIoTUtility -version=1.0.40 +version=1.0.41 author=Microsoft maintainer=Microsoft sentence=Azure C shared utility library for Arduino. For the Arduino MKR1000 or Zero and WiFi Shield 101, Adafruit Huzzah and Feather M0, or SparkFun Thing. diff --git a/src/AzureIoTUtility.h b/src/AzureIoTUtility.h index 3a50f7c..d9ebc16 100644 --- a/src/AzureIoTUtility.h +++ b/src/AzureIoTUtility.h @@ -7,6 +7,6 @@ #include "azure_c_shared_utility/lock.h" #include "azure_c_shared_utility/threadapi.h" -#define AzureIoTUtilityVersion "1.0.40" +#define AzureIoTUtilityVersion "1.0.41" #endif //AZUREIOTUTILITY_H diff --git a/src/adapters/xlogging_dump_bytes.c b/src/adapters/xlogging_dump_bytes.c new file mode 100644 index 0000000..1e32d08 --- /dev/null +++ b/src/adapters/xlogging_dump_bytes.c @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +#include "azure_c_shared_utility/xlogging.h" +#include "azure_c_shared_utility/consolelogger.h" + + +/* Print up to 16 bytes per line. */ +#define LINE_SIZE 16 + +/* Return the printable char for the provided value. */ +#define PRINTABLE(c) ((c >= ' ') && (c <= '~')) ? (char)c : '.' + +/* Convert the lower nibble of the provided byte to a hexadecimal printable char. */ +#define HEX_STR(c) (((c) & 0xF) < 0xA) ? (char)(((c) & 0xF) + '0') : (char)(((c) & 0xF) - 0xA + 'A') + +void xlogging_dump_bytes(const void* buf, size_t size) +{ + char charBuf[LINE_SIZE + 1]; + char hexBuf[LINE_SIZE * 3 + 1]; + size_t countbuf = 0; + const unsigned char* bufAsChar = (const unsigned char*)buf; + const unsigned char* startPos = bufAsChar; + + /* Print the whole buffer. */ + size_t i = 0; + for (i = 0; i < size; i++) + { + /* Store the printable value of the char in the charBuf to print. */ + charBuf[countbuf] = PRINTABLE(*bufAsChar); + + /* Convert the high nibble to a printable hexadecimal value. */ + hexBuf[countbuf * 3] = HEX_STR(*bufAsChar >> 4); + + /* Convert the low nibble to a printable hexadecimal value. */ + hexBuf[countbuf * 3 + 1] = HEX_STR(*bufAsChar); + + hexBuf[countbuf * 3 + 2] = ' '; + + countbuf++; + bufAsChar++; + /* If the line is full, print it to start another one. */ + if (countbuf == LINE_SIZE) + { + charBuf[countbuf] = '\0'; + hexBuf[countbuf * 3] = '\0'; + LOG(AZ_LOG_TRACE, 0, "%p: %s %s", startPos, hexBuf, charBuf); + countbuf = 0; + startPos = bufAsChar; + } + } + + /* If the last line does not fit the line size. */ + if (countbuf > 0) + { + /* Close the charBuf string. */ + charBuf[countbuf] = '\0'; + + /* Fill the hexBuf with spaces to keep the charBuf alignment. */ + while ((countbuf++) < LINE_SIZE - 1) + { + hexBuf[countbuf * 3] = ' '; + hexBuf[countbuf * 3 + 1] = ' '; + hexBuf[countbuf * 3 + 2] = ' '; + } + hexBuf[countbuf * 3] = '\0'; + + /* Print the last line. */ + LOG(AZ_LOG_TRACE, 0, "%p: %s %s", startPos, hexBuf, charBuf); + } +} diff --git a/src/azure_c_shared_utility/aziotsharedutil.def b/src/azure_c_shared_utility/aziotsharedutil.def index 1043009..0111fc4 100644 --- a/src/azure_c_shared_utility/aziotsharedutil.def +++ b/src/azure_c_shared_utility/aziotsharedutil.def @@ -283,7 +283,6 @@ EXPORTS xio_retrieveoptions xio_send xio_setoption - xlogging_dump_buffer xlogging_get_log_function xlogging_get_log_function_GetLastError xlogging_set_log_function diff --git a/src/azure_c_shared_utility/crt_abstractions.h b/src/azure_c_shared_utility/crt_abstractions.h index cc86919..5063609 100644 --- a/src/azure_c_shared_utility/crt_abstractions.h +++ b/src/azure_c_shared_utility/crt_abstractions.h @@ -32,7 +32,6 @@ typedef bool _Bool; #ifndef _WIN32_WCE #define HAS_STDBOOL #ifdef __cplusplus -#include /*because C++ doesn't do anything about _Bool... */ #define _Bool bool #else // __cplusplus diff --git a/src/azure_c_shared_utility/httpapiexsas.c b/src/azure_c_shared_utility/httpapiexsas.c index 8ca5a9d..093e6e0 100644 --- a/src/azure_c_shared_utility/httpapiexsas.c +++ b/src/azure_c_shared_utility/httpapiexsas.c @@ -35,16 +35,11 @@ HTTPAPIEX_SAS_HANDLE HTTPAPIEX_SAS_Create(STRING_HANDLE key, STRING_HANDLE uriRe /*Codes_SRS_HTTPAPIEXSAS_06_002: [If the parameter uriResource is NULL then HTTPAPIEX_SAS_Create shall return NULL.]*/ LogError("No uri resource passed to HTTPAPIEX_SAS_Create."); } - else if (keyName == NULL) - { - /*Codes_SRS_HTTPAPIEXSAS_06_003: [If the parameter keyName is NULL then HTTPAPIEX_SAS_Create shall return NULL.]*/ - LogError("No key name passed to HTTPAPIEX_SAS_Create."); - } else { /*Codes_SRS_HTTPAPIEXSAS_01_001: [ HTTPAPIEX_SAS_Create shall create a new instance of HTTPAPIEX_SAS and return a non-NULL handle to it. ]*/ HTTPAPIEX_SAS_STATE* state = (HTTPAPIEX_SAS_STATE*)malloc(sizeof(HTTPAPIEX_SAS_STATE)); - /*Codes_SRS_HTTPAPIEXSAS_06_004: [If there are any other errors in the instantiation of this handle then HTTPAPIEX_SAS_Create shall return NULL.]*/ + /*Codes_SRS_HTTPAPIEXSAS_06_003: [The parameter keyName for HTTPAPIEX_SAS_Create is optional and can be NULL.]*/ if (state != NULL) { state->key = NULL; @@ -52,7 +47,7 @@ HTTPAPIEX_SAS_HANDLE HTTPAPIEX_SAS_Create(STRING_HANDLE key, STRING_HANDLE uriRe state->keyName = NULL; if (((state->key = STRING_clone(key)) == NULL) || ((state->uriResource = STRING_clone(uriResource)) == NULL) || - ((state->keyName = STRING_clone(keyName)) == NULL)) + ((keyName != NULL) && ((state->keyName = STRING_clone(keyName)) == NULL))) { /*Codes_SRS_HTTPAPIEXSAS_06_004: [If there are any other errors in the instantiation of this handle then HTTPAPIEX_SAS_Create shall return NULL.]*/ LogError("Unable to clone the arguments."); diff --git a/src/azure_c_shared_utility/sastoken.c b/src/azure_c_shared_utility/sastoken.c index a40e000..389cc63 100644 --- a/src/azure_c_shared_utility/sastoken.c +++ b/src/azure_c_shared_utility/sastoken.c @@ -268,8 +268,8 @@ static STRING_HANDLE construct_sas_token(const char* key, const char* scope, con /*Codes_SRS_SASTOKEN_06_019: [The string urlEncodedSignature shall be appended to result.]*/ /*Codes_SRS_SASTOKEN_06_020: [The string "&se=" shall be appended to result.]*/ /*Codes_SRS_SASTOKEN_06_021: [tokenExpirationTime is appended to result.]*/ - /*Codes_SRS_SASTOKEN_06_022: [The string "&skn=" is appended to result.]*/ - /*Codes_SRS_SASTOKEN_06_023: [The argument keyName is appended to result.]*/ + /*Codes_SRS_SASTOKEN_06_022: [If keyName is non-NULL, the string "&skn=" is appended to result.]*/ + /*Codes_SRS_SASTOKEN_06_023: [If keyName is non-NULL, the argument keyName is appended to result.]*/ if ((HMACSHA256_ComputeHash(outBuf, outLen, inBuf, inLen, hash) != HMACSHA256_OK) || ((base64Signature = Base64_Encoder(hash)) == NULL) || ((urlEncodedSignature = URL_Encode(base64Signature)) == NULL) || @@ -279,8 +279,8 @@ static STRING_HANDLE construct_sas_token(const char* key, const char* scope, con (STRING_concat_with_STRING(result, urlEncodedSignature) != 0) || (STRING_concat(result, "&se=") != 0) || (STRING_concat(result, tokenExpirationTime) != 0) || - (STRING_concat(result, "&skn=") != 0) || - (STRING_concat(result, keyname) != 0)) + ((keyname != NULL) && (STRING_concat(result, "&skn=") != 0)) || + ((keyname != NULL) && (STRING_concat(result, keyname) != 0))) { LogError("Unable to build the SAS token."); STRING_delete(result); @@ -308,10 +308,9 @@ STRING_HANDLE SASToken_Create(STRING_HANDLE key, STRING_HANDLE scope, STRING_HAN /*Codes_SRS_SASTOKEN_06_001: [If key is NULL then SASToken_Create shall return NULL.]*/ /*Codes_SRS_SASTOKEN_06_003: [If scope is NULL then SASToken_Create shall return NULL.]*/ - /*Codes_SRS_SASTOKEN_06_007: [If keyName is NULL then SASToken_Create shall return NULL.]*/ + /*Codes_SRS_SASTOKEN_06_007: [keyName is optional and can be set to NULL.]*/ if ((key == NULL) || - (scope == NULL) || - (keyName == NULL)) + (scope == NULL)) { LogError("Invalid Parameter to SASToken_Create. handle key: %p, handle scope: %p, handle keyName: %p", key, scope, keyName); result = NULL; @@ -332,10 +331,9 @@ STRING_HANDLE SASToken_CreateString(const char* key, const char* scope, const ch /*Codes_SRS_SASTOKEN_06_001: [If key is NULL then SASToken_Create shall return NULL.]*/ /*Codes_SRS_SASTOKEN_06_003: [If scope is NULL then SASToken_Create shall return NULL.]*/ - /*Codes_SRS_SASTOKEN_06_007: [If keyName is NULL then SASToken_Create shall return NULL.]*/ + /*Codes_SRS_SASTOKEN_06_007: [keyName is optional and can be set to NULL.]*/ if ((key == NULL) || - (scope == NULL) || - (keyName == NULL)) + (scope == NULL)) { LogError("Invalid Parameter to SASToken_Create. handle key: %p, handle scope: %p, handle keyName: %p", key, scope, keyName); result = NULL; diff --git a/src/azure_c_shared_utility/singlylinkedlist.h b/src/azure_c_shared_utility/singlylinkedlist.h index 9cb2ccd..bd09ee4 100644 --- a/src/azure_c_shared_utility/singlylinkedlist.h +++ b/src/azure_c_shared_utility/singlylinkedlist.h @@ -6,7 +6,6 @@ #ifdef __cplusplus extern "C" { -#include #else #include "stdbool.h" #endif /* __cplusplus */ diff --git a/src/azure_c_shared_utility/strings.c b/src/azure_c_shared_utility/strings.c index 2fac434..eaf4c9f 100644 --- a/src/azure_c_shared_utility/strings.c +++ b/src/azure_c_shared_utility/strings.c @@ -126,9 +126,9 @@ STRING_HANDLE STRING_construct_sprintf(const char* format, ...) { STRING* result; -#ifdef ARDUINO_ARCH_ESP8266 - size_t maxBufSize = 512; - char buf[512]; +#ifdef STRINGS_C_SPRINTF_BUFFER_SIZE + size_t maxBufSize = STRINGS_C_SPRINTF_BUFFER_SIZE; + char buf[STRINGS_C_SPRINTF_BUFFER_SIZE]; #else size_t maxBufSize = 0; char* buf = NULL; @@ -517,9 +517,9 @@ int STRING_sprintf(STRING_HANDLE handle, const char* format, ...) { int result; -#ifdef ARDUINO_ARCH_ESP8266 - size_t maxBufSize = 512; - char buf[512]; +#ifdef STRINGS_C_SPRINTF_BUFFER_SIZE + size_t maxBufSize = STRINGS_C_SPRINTF_BUFFER_SIZE; + char buf[STRINGS_C_SPRINTF_BUFFER_SIZE]; #else size_t maxBufSize = 0; char* buf = NULL; diff --git a/src/azure_c_shared_utility/utf8_checker.c b/src/azure_c_shared_utility/utf8_checker.c index 4e93add..fd3bffa 100644 --- a/src/azure_c_shared_utility/utf8_checker.c +++ b/src/azure_c_shared_utility/utf8_checker.c @@ -3,7 +3,6 @@ #ifdef __cplusplus #include -#include #include #include #else diff --git a/src/azure_c_shared_utility/utf8_checker.h b/src/azure_c_shared_utility/utf8_checker.h index f6e06a9..f4758de 100644 --- a/src/azure_c_shared_utility/utf8_checker.h +++ b/src/azure_c_shared_utility/utf8_checker.h @@ -5,7 +5,6 @@ #define UTF8_CHECKER_H #ifdef __cplusplus -#include #include extern "C" { #else diff --git a/src/azure_c_shared_utility/uws_client.h b/src/azure_c_shared_utility/uws_client.h index b67b938..b2c6aaf 100644 --- a/src/azure_c_shared_utility/uws_client.h +++ b/src/azure_c_shared_utility/uws_client.h @@ -9,7 +9,6 @@ #include "azure_c_shared_utility/optionhandler.h" #ifdef __cplusplus -#include #include #include extern "C" { diff --git a/src/azure_c_shared_utility/uws_frame_encoder.h b/src/azure_c_shared_utility/uws_frame_encoder.h index b58316b..1da29bd 100644 --- a/src/azure_c_shared_utility/uws_frame_encoder.h +++ b/src/azure_c_shared_utility/uws_frame_encoder.h @@ -9,7 +9,6 @@ #include "azure_c_shared_utility/macro_utils.h" #ifdef __cplusplus -#include #include extern "C" { #else diff --git a/src/azure_c_shared_utility/vector.h b/src/azure_c_shared_utility/vector.h index 47e8a56..4256938 100644 --- a/src/azure_c_shared_utility/vector.h +++ b/src/azure_c_shared_utility/vector.h @@ -10,7 +10,6 @@ #ifdef __cplusplus #include -#include extern "C" { #else diff --git a/src/azure_c_shared_utility/vector_types.h b/src/azure_c_shared_utility/vector_types.h index e3c0303..b3f0759 100644 --- a/src/azure_c_shared_utility/vector_types.h +++ b/src/azure_c_shared_utility/vector_types.h @@ -5,7 +5,6 @@ #define VECTOR_TYPES_H #ifdef __cplusplus -#include extern "C" { #else diff --git a/src/azure_c_shared_utility/xlogging.c b/src/azure_c_shared_utility/xlogging.c index 4783450..b59b089 100644 --- a/src/azure_c_shared_utility/xlogging.c +++ b/src/azure_c_shared_utility/xlogging.c @@ -67,69 +67,4 @@ LOGGER_LOG_GETLASTERROR xlogging_get_log_function_GetLastError(void) } #endif -/* Print up to 16 bytes per line. */ -#define LINE_SIZE 16 - -/* Return the printable char for the provided value. */ -#define PRINTABLE(c) ((c >= ' ') && (c <= '~')) ? (char)c : '.' - -/* Convert the lower nibble of the provided byte to a hexadecimal printable char. */ -#define HEX_STR(c) (((c) & 0xF) < 0xA) ? (char)(((c) & 0xF) + '0') : (char)(((c) & 0xF) - 0xA + 'A') - -void xlogging_dump_buffer(const void* buf, size_t size) -{ - char charBuf[LINE_SIZE + 1]; - char hexBuf[LINE_SIZE * 3 + 1]; - size_t countbuf = 0; - const unsigned char* bufAsChar = (const unsigned char*)buf; - const unsigned char* startPos = bufAsChar; - - /* Print the whole buffer. */ - size_t i = 0; - for (i = 0; i < size; i++) - { - /* Store the printable value of the char in the charBuf to print. */ - charBuf[countbuf] = PRINTABLE(*bufAsChar); - - /* Convert the high nibble to a printable hexadecimal value. */ - hexBuf[countbuf * 3] = HEX_STR(*bufAsChar >> 4); - - /* Convert the low nibble to a printable hexadecimal value. */ - hexBuf[countbuf * 3 + 1] = HEX_STR(*bufAsChar); - - hexBuf[countbuf * 3 + 2] = ' '; - - countbuf++; - bufAsChar++; - /* If the line is full, print it to start another one. */ - if (countbuf == LINE_SIZE) - { - charBuf[countbuf] = '\0'; - hexBuf[countbuf * 3] = '\0'; - LOG(AZ_LOG_TRACE, 0, "%p: %s %s", startPos, hexBuf, charBuf); - countbuf = 0; - startPos = bufAsChar; - } - } - - /* If the last line does not fit the line size. */ - if (countbuf > 0) - { - /* Close the charBuf string. */ - charBuf[countbuf] = '\0'; - - /* Fill the hexBuf with spaces to keep the charBuf alignment. */ - while ((countbuf++) < LINE_SIZE - 1) - { - hexBuf[countbuf * 3] = ' '; - hexBuf[countbuf * 3 + 1] = ' '; - hexBuf[countbuf * 3 + 2] = ' '; - } - hexBuf[countbuf * 3] = '\0'; - - /* Print the last line. */ - LOG(AZ_LOG_TRACE, 0, "%p: %s %s", startPos, hexBuf, charBuf); - } -} - #endif diff --git a/src/azure_c_shared_utility/xlogging.h b/src/azure_c_shared_utility/xlogging.h index ffdaa8f..848e1ee 100644 --- a/src/azure_c_shared_utility/xlogging.h +++ b/src/azure_c_shared_utility/xlogging.h @@ -1,18 +1,17 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +// This is the Arduino-specific version of xlogging.h + #ifndef XLOGGING_H #define XLOGGING_H #include "azure_c_shared_utility/agenttime.h" #include "azure_c_shared_utility/optimize_size.h" -#if defined(ESP8266_RTOS) -#include "c_types.h" -#endif - #if defined(ARDUINO_ARCH_ESP8266) #include "esp8266/azcpgmspace.h" +#define STRINGS_C_SPRINTF_BUFFER_SIZE 512 #endif #ifdef __cplusplus @@ -22,10 +21,6 @@ extern "C" { #include #endif /* __cplusplus */ -#ifdef TIZENRT -#undef LOG_INFO -#endif - typedef enum LOG_CATEGORY_TAG { AZ_LOG_ERROR, @@ -63,21 +58,6 @@ typedef void(*LOGGER_LOG_GETLASTERROR)(const char* file, const char* func, int l #define LogErrorWinHTTPWithGetLastErrorAsString(...) #define UNUSED(x) (void)(x) -#elif defined(ESP8266_RTOS) -#define LogInfo(FORMAT, ...) do { \ - static const char flash_str[] ICACHE_RODATA_ATTR STORE_ATTR = FORMAT; \ - printf(flash_str, ##__VA_ARGS__); \ - printf("\n");\ - } while((void)0,0) - -#define LogError LogInfo -#define LOG(log_category, log_options, FORMAT, ...) { \ - static const char flash_str[] ICACHE_RODATA_ATTR STORE_ATTR = (FORMAT); \ - printf(flash_str, ##__VA_ARGS__); \ - printf("\r\n"); \ -} - - #elif defined(ARDUINO_ARCH_ESP8266) /* The ESP8266 compiler doesn't do a good job compiling this code; it doesn't understand that the 'format' is @@ -120,11 +100,9 @@ so we compacted the log in the macro LogInfo. #if defined _MSC_VER -#if !defined(WINCE) extern void xlogging_set_log_function_GetLastError(LOGGER_LOG_GETLASTERROR log_function); extern LOGGER_LOG_GETLASTERROR xlogging_get_log_function_GetLastError(void); #define LogLastError(FORMAT, ...) do{ LOGGER_LOG_GETLASTERROR l = xlogging_get_log_function_GetLastError(); if(l!=NULL) l(__FILE__, FUNC_NAME, __LINE__, FORMAT, __VA_ARGS__); }while((void)0,0) -#endif #define LogError(FORMAT, ...) do{ LOG(AZ_LOG_ERROR, LOG_LINE, FORMAT, __VA_ARGS__); }while((void)0,0) #define TEMP_BUFFER_SIZE 1024 @@ -159,9 +137,9 @@ extern LOGGER_LOG_GETLASTERROR xlogging_get_log_function_GetLastError(void); }\ }\ } while((void)0,0) -#else +#else // _MSC_VER #define LogError(FORMAT, ...) do{ LOG(AZ_LOG_ERROR, LOG_LINE, FORMAT, ##__VA_ARGS__); }while((void)0,0) -#endif +#endif // _MSC_VER extern void xlogging_set_log_function(LOGGER_LOG log_function); extern LOGGER_LOG xlogging_get_log_function(void); @@ -169,19 +147,19 @@ extern LOGGER_LOG xlogging_get_log_function(void); #endif /* ARDUINO_ARCH_ESP8266 */ - /** - * @brief Print the memory content byte pre byte in hexadecimal and as a char it the byte correspond to any printable ASCII chars. - * - * This function prints the 'size' bytes in the 'buf' to the log. It will print in portions of 16 bytes, - * and will print the byte as a hexadecimal value, and, it is a printable, this function will print - * the correspondent ASCII character. - * Non printable characters will shows as a single '.'. - * For this function, printable characters are all characters between ' ' (0x20) and '~' (0x7E). - * - * @param buf Pointer to the memory address with the buffer to print. - * @param size Number of bytes to print. - */ - extern void xlogging_dump_buffer(const void* buf, size_t size); +/** + * @brief Print the memory content byte pre byte in hexadecimal and as a char it the byte correspond to any printable ASCII chars. + * + * This function prints the 'size' bytes in the 'buf' to the log. It will print in portions of 16 bytes, + * and will print the byte as a hexadecimal value, and, it is a printable, this function will print + * the correspondent ASCII character. + * Non printable characters will shows as a single '.'. + * For this function, printable characters are all characters between ' ' (0x20) and '~' (0x7E). + * + * @param buf Pointer to the memory address with the buffer to print. + * @param size Number of bytes to print. + */ +extern void xlogging_dump_bytes(const void* buf, size_t size); #ifdef __cplusplus } // extern "C"