From 70c66e2bd344aee8b925c3557051da9b5b2c398d Mon Sep 17 00:00:00 2001 From: erikoleary Date: Thu, 12 Apr 2018 20:15:02 -0500 Subject: [PATCH 1/6] Updated library.json & platform ini to reference dependencies --- .gitignore | 1 + library.json | 8 ++++++-- platformio.ini | 4 +++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 099b9b9..4e8532b 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ CMakeListsPrivate.txt .vscode .vscode/c_cpp_properties.json .vscode/launch.json +.vscode/.browse.c_cpp.db* diff --git a/library.json b/library.json index 721bc19..dae8e6e 100644 --- a/library.json +++ b/library.json @@ -16,11 +16,15 @@ "frameworks": "arduino", "platforms": "espressif8266", "dependencies": [ + { + "name": "PubSubClient", + "authors": "Nick O'Leary", + "frameworks": "arduino" + }, { "name": "ArduinoJson", "authors": "Benoit Blanchon", - "frameworks": "arduino", - "platforms": "espressif8266" + "frameworks": "arduino" }, { "name": "Time", diff --git a/platformio.ini b/platformio.ini index e0301d3..0b43bd4 100644 --- a/platformio.ini +++ b/platformio.ini @@ -11,4 +11,6 @@ platform = espressif8266 board = espectro framework = arduino -lib_deps = 64, 44 \ No newline at end of file +lib_deps = + ArduinoJson@5.13.1 + Time@1.5 \ No newline at end of file From b26ae3a5c9607362110bb09c2c563b89db27146b Mon Sep 17 00:00:00 2001 From: erikoleary Date: Wed, 18 Apr 2018 19:11:20 -0500 Subject: [PATCH 2/6] Removed ntp client dependency --- src/AzureIoTHubMQTTClient.cpp | 63 +++-------------------------------- src/AzureIoTHubMQTTClient.h | 9 ----- 2 files changed, 4 insertions(+), 68 deletions(-) diff --git a/src/AzureIoTHubMQTTClient.cpp b/src/AzureIoTHubMQTTClient.cpp index 4489bb5..cf14e50 100644 --- a/src/AzureIoTHubMQTTClient.cpp +++ b/src/AzureIoTHubMQTTClient.cpp @@ -14,45 +14,12 @@ AzureIoTHubMQTTClient::AzureIoTHubMQTTClient(Client& c, String iotHubHostName, S mqttCommandSubscribeTopic_ = "devices/" + deviceId + "/messages/devicebound/#"; mqttCommandPublishTopic_ = "devices/" + deviceId + "/messages/events/"; - - using namespace std::placeholders; - NTP.onNTPSyncEvent(std::bind(&AzureIoTHubMQTTClient::onNTPSynced, this, _1)); } AzureIoTHubMQTTClient::~AzureIoTHubMQTTClient() { } -void AzureIoTHubMQTTClient::onNTPSynced(NTPSyncEvent_t ntpEvent) { - if (ntpEvent) { - DEBUGLOG("Time Sync error: "); - if (ntpEvent == noResponse) { - DEBUGLOG("NTP server not reachable\n"); - } - else if (ntpEvent == invalidAddress) { - DEBUGLOG("Invalid NTP server address\n"); - } - - NTP.setInterval(5); //try again soon - -// ntpTrialCount_++; -// if (ntpTrialCount_ > 3) { -// } - - } - else { - ntpSyncedFlag_ = true; - DEBUGLOG("Got NTP time: "); - DEBUGLOG("%s\n", NTP.getTimeDateString(NTP.getLastNTPSync()).c_str()); - NTP.setInterval(61); - - changeEventTo(AzureIoTHubMQTTClientEventNTPSynced); - - } - - DEBUGLOG("Current timestamp: %d\n", now()); -} - bool AzureIoTHubMQTTClient::begin() { if (!WiFi.isConnected()) { @@ -60,42 +27,27 @@ bool AzureIoTHubMQTTClient::begin() { return false; } - NTP.begin(NTP_DEFAULT_HOST);//, 1, true); - changeEventTo(AzureIoTHubMQTTClientEventNTPSyncing); - return true; } void AzureIoTHubMQTTClient::run() { - //if (ntpSyncedFlag_ || timeStatus() == timeSet) { - if (ntpSyncedFlag_ && currentEvent_ == AzureIoTHubMQTTClientEventNTPSynced) { - ntpSyncedFlag_ = false; - - if (!connected()) { - doConnect(); - } - } - else { - if (currentEvent_ == AzureIoTHubMQTTClientEventNTPSyncing) { - timeStatus(); - } + if (!connected()) { + doConnect(); } PubSubClient::loop(); } void AzureIoTHubMQTTClient::end() { - //ntpTrialCount_ = 0; disconnect(); - NTP.stop(); } String AzureIoTHubMQTTClient::createIotHubSASToken(char *key, String url, long expire){ url.toLowerCase(); if (expire == 0) { - expire = 1737504000; //hardcoded expire + expire = 2147483647; // hardcode expire to MAX unix timestamp } String stringToSign = url + "\n" + String(expire); @@ -132,11 +84,8 @@ bool AzureIoTHubMQTTClient::doConnect() { String url = iotHubHostName_ + urlEncode(String("/devices/" + deviceId_).c_str()); char *devKey = (char *)deviceKey_.c_str(); - long expire = (timeStatus() == timeSet? now(): 0) + (AZURE_IOTHUB_TOKEN_EXPIRE); - DEBUGLOG("SAS Token expire: %d\n", expire); - //TODO: Store SAS token? So that no expensive operation for each begin - sasToken_ = createIotHubSASToken(devKey, url, expire); + sasToken_ = createIotHubSASToken(devKey, url, 0); } changeEventTo(AzureIoTHubMQTTClientEventConnecting); @@ -242,10 +191,6 @@ void AzureIoTHubMQTTClient::_onActualMqttMessageCallback(const MQTT::Publish &ms } } -bool AzureIoTHubMQTTClient::setTimeZone(int timeZone) { - return NTP.setTimeZone(timeZone); -} - void AzureIoTHubMQTTClient::onCloudCommand(String command, AzureIoTHubMQTTClient::AzureIoTHubMQTTClientCommandCallback callback) { diff --git a/src/AzureIoTHubMQTTClient.h b/src/AzureIoTHubMQTTClient.h index 5ba640e..3fce9ab 100644 --- a/src/AzureIoTHubMQTTClient.h +++ b/src/AzureIoTHubMQTTClient.h @@ -24,10 +24,7 @@ #define DEBUGLOG(...) #endif -#include "NtpClientLib.h" - #define MAX_JSON_OBJECT_SIZE 20 -#define NTP_DEFAULT_HOST DEFAULT_NTP_SERVER //"time.nist.gov"//"pool.ntp.org" #define AZURE_IOTHUB_MQTT_PORT 8883 #define AZURE_IOTHUB_TOKEN_EXPIRE 10*24*3600 //seconds @@ -36,8 +33,6 @@ class AzureIoTHubMQTTClient : public PubSubClient { enum AzureIoTHubMQTTClientEvent { AzureIoTHubMQTTClientEventUnknown, - AzureIoTHubMQTTClientEventNTPSyncing, - AzureIoTHubMQTTClientEventNTPSynced, AzureIoTHubMQTTClientEventConnecting, AzureIoTHubMQTTClientEventConnected, AzureIoTHubMQTTClientEventDisconnected @@ -59,7 +54,6 @@ class AzureIoTHubMQTTClient : public PubSubClient { bool sendEvent(String payload); bool sendEvent(const uint8_t *payload, uint32_t plength, bool retained = false); void sendEventWithKeyVal(KeyValueMap keyValMap); - bool setTimeZone(int timeZone); void onEvent(EventCallback cb) { eventCallback_ = cb; @@ -76,7 +70,6 @@ class AzureIoTHubMQTTClient : public PubSubClient { String sasToken_; String mqttCommandSubscribeTopic_, mqttCommandPublishTopic_; PubSubClient::callback_t onSubscribeCallback_; - volatile bool ntpSyncedFlag_ = false; bool parseMessageAsJson_ = false; @@ -86,8 +79,6 @@ class AzureIoTHubMQTTClient : public PubSubClient { bool doConnect(); String createIotHubSASToken(char *key, String url, long expire = 0); void _onActualMqttMessageCallback(const MQTT::Publish& p); - void onNTPSynced(NTPSyncEvent_t ntpEvent); - //uint8_t ntpTrialCount_ = 0; AzureIoTHubMQTTClientEvent currentEvent_ = AzureIoTHubMQTTClientEventUnknown; void changeEventTo(AzureIoTHubMQTTClientEvent event); From bc9014c65e7f0890948b2183364ff80ba0818021 Mon Sep 17 00:00:00 2001 From: erikoleary Date: Sun, 18 Nov 2018 11:41:49 -0600 Subject: [PATCH 3/6] Connect with provided credentials --- src/AzureIoTHubMQTTClient.cpp | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/src/AzureIoTHubMQTTClient.cpp b/src/AzureIoTHubMQTTClient.cpp index cf14e50..2b5052f 100644 --- a/src/AzureIoTHubMQTTClient.cpp +++ b/src/AzureIoTHubMQTTClient.cpp @@ -78,23 +78,12 @@ String AzureIoTHubMQTTClient::createIotHubSASToken(char *key, String url, long e } bool AzureIoTHubMQTTClient::doConnect() { - - if (sasToken_.equals("")) { - DEBUGLOG("Creating SAS Token!\n"); - - String url = iotHubHostName_ + urlEncode(String("/devices/" + deviceId_).c_str()); - char *devKey = (char *)deviceKey_.c_str(); - - sasToken_ = createIotHubSASToken(devKey, url, 0); - } - changeEventTo(AzureIoTHubMQTTClientEventConnecting); - String mqttUname = iotHubHostName_ + "/" + deviceId_ + "/api-version=2016-11-14"; - String mqttPassword = "SharedAccessSignature " + sasToken_; + String mqttUname = iotHubHostName_ + "/" + deviceId_ + "/api-version=2016-11-14"; //DEBUGLOG(mqttPassword); - MQTT::Connect conn = MQTT::Connect(deviceId_).set_auth(mqttUname, mqttPassword);//.set_clean_session(); + MQTT::Connect conn = MQTT::Connect(deviceId_).set_auth(mqttUname, deviceKey_);//.set_clean_session(); conn.set_keepalive(10); bool ret = PubSubClient::connect(conn); From 09ab5588b91c380fe04337a65549bfe8182d4873 Mon Sep 17 00:00:00 2001 From: erikoleary Date: Sun, 18 Nov 2018 11:43:53 -0600 Subject: [PATCH 4/6] Removed pubsubclient mention --- library.json | 5 ----- 1 file changed, 5 deletions(-) diff --git a/library.json b/library.json index dae8e6e..332d918 100644 --- a/library.json +++ b/library.json @@ -16,11 +16,6 @@ "frameworks": "arduino", "platforms": "espressif8266", "dependencies": [ - { - "name": "PubSubClient", - "authors": "Nick O'Leary", - "frameworks": "arduino" - }, { "name": "ArduinoJson", "authors": "Benoit Blanchon", From 3926e49d63512f6b24023acd565044cefea499b2 Mon Sep 17 00:00:00 2001 From: erikoleary Date: Sun, 18 Nov 2018 11:58:19 -0600 Subject: [PATCH 5/6] Code cleanup --- src/AzureIoTHubMQTTClient.cpp | 110 ++-------- src/AzureIoTHubMQTTClient.h | 23 +- src/Base64.cpp | 130 ----------- src/Base64.h | 79 ------- src/NtpClientLib.h | 401 ---------------------------------- src/NtpClientLib_ESP.cpp | 377 -------------------------------- src/PubSubClient_JSON.h | 65 ------ src/Utils.cpp | 57 ----- src/Utils.h | 20 -- src/sha256.cpp | 167 -------------- src/sha256.h | 42 ---- 11 files changed, 23 insertions(+), 1448 deletions(-) delete mode 100755 src/Base64.cpp delete mode 100755 src/Base64.h delete mode 100755 src/NtpClientLib.h delete mode 100755 src/NtpClientLib_ESP.cpp delete mode 100755 src/PubSubClient_JSON.h delete mode 100644 src/Utils.cpp delete mode 100644 src/Utils.h delete mode 100755 src/sha256.cpp delete mode 100755 src/sha256.h diff --git a/src/AzureIoTHubMQTTClient.cpp b/src/AzureIoTHubMQTTClient.cpp index 2b5052f..d9807cf 100644 --- a/src/AzureIoTHubMQTTClient.cpp +++ b/src/AzureIoTHubMQTTClient.cpp @@ -4,34 +4,15 @@ #include "AzureIoTHubMQTTClient.h" -#include "sha256.h" -#include "Base64.h" -#include "Utils.h" #include AzureIoTHubMQTTClient::AzureIoTHubMQTTClient(Client& c, String iotHubHostName, String deviceId, String deviceKey): iotHubHostName_(iotHubHostName), deviceId_(deviceId), deviceKey_(deviceKey), PubSubClient(c, iotHubHostName, AZURE_IOTHUB_MQTT_PORT) { - mqttCommandSubscribeTopic_ = "devices/" + deviceId + "/messages/devicebound/#"; mqttCommandPublishTopic_ = "devices/" + deviceId + "/messages/events/"; } -AzureIoTHubMQTTClient::~AzureIoTHubMQTTClient() { - -} - -bool AzureIoTHubMQTTClient::begin() { - - if (!WiFi.isConnected()) { - DEBUGLOG("NOT connected to internet!\n"); - return false; - } - - return true; -} - void AzureIoTHubMQTTClient::run() { - if (!connected()) { doConnect(); } @@ -43,83 +24,39 @@ void AzureIoTHubMQTTClient::end() { disconnect(); } -String AzureIoTHubMQTTClient::createIotHubSASToken(char *key, String url, long expire){ - - url.toLowerCase(); - if (expire == 0) { - expire = 2147483647; // hardcode expire to MAX unix timestamp - } - - String stringToSign = url + "\n" + String(expire); - - // START: Create signature - // https://raw.githubusercontent.com/adamvr/arduino-base64/master/examples/base64/base64.ino - - int keyLength = strlen(key); - - int decodedKeyLength = base64_dec_len(key, keyLength); - char decodedKey[decodedKeyLength]; //allocate char array big enough for the base64 decoded key - - base64_decode(decodedKey, key, keyLength); //decode key - - Sha256.initHmac((const uint8_t*)decodedKey, decodedKeyLength); - Sha256.print(stringToSign); - char* sign = (char*) Sha256.resultHmac(); - // END: Create signature - - // START: Get base64 of signature - int encodedSignLen = base64_enc_len(HASH_LENGTH); - char encodedSign[encodedSignLen]; - base64_encode(encodedSign, sign, HASH_LENGTH); - - // SharedAccessSignature - return "sr=" + url + "&sig="+ urlEncode(encodedSign) + "&se=" + String(expire); - // END: create SAS -} - bool AzureIoTHubMQTTClient::doConnect() { changeEventTo(AzureIoTHubMQTTClientEventConnecting); - String mqttUname = iotHubHostName_ + "/" + deviceId_ + "/api-version=2016-11-14"; - //DEBUGLOG(mqttPassword); - - MQTT::Connect conn = MQTT::Connect(deviceId_).set_auth(mqttUname, deviceKey_);//.set_clean_session(); - conn.set_keepalive(10); - bool ret = PubSubClient::connect(conn); + auto mqttUname = iotHubHostName_ + "/" + deviceId_ + "/api-version=2016-11-14"; - if (ret) { + auto conn = MQTT::Connect(deviceId_) + .set_auth(mqttUname, deviceKey_) + .set_keepalive(10); - //DEBUGLOG("Connected to Azure IoT Hub\n"); + if (PubSubClient::connect(conn)) { changeEventTo(AzureIoTHubMQTTClientEventConnected); - PubSubClient::callback_t cb = [=](const MQTT::Publish& p){ + auto cb = [=](const MQTT::Publish& p){ _onActualMqttMessageCallback(p); }; set_callback(cb); //Directly subscribe - PubSubClient::subscribe(mqttCommandSubscribeTopic_); - //MQTT::Subscribe sub = MQTT::Subscribe(mqttCommandSubscribeTopic_, 1); - //PubSubClient::subscribe(sub); - + PubSubClient::subscribe("devices/" + deviceId_ + "/messages/devicebound/#"); return true; - } else { + } + else { DEBUGLOG("Failed to connect to Azure IoT Hub\n"); return false; } } bool AzureIoTHubMQTTClient::sendEvent(String payload) { - //return PubSubClient::publish(mqttCommandPublishTopic_, payload); return PubSubClient::publish(MQTT::Publish(mqttCommandPublishTopic_, payload).set_qos(1).set_retain(false)); } -bool AzureIoTHubMQTTClient::sendEvent(const uint8_t *payload, uint32_t plength, bool retained) { - return PubSubClient::publish(mqttCommandPublishTopic_, payload, plength, retained); -} - void AzureIoTHubMQTTClient::sendEventWithKeyVal(KeyValueMap keyValMap) { if (keyValMap.size() == 0) { return; @@ -127,7 +64,7 @@ void AzureIoTHubMQTTClient::sendEventWithKeyVal(KeyValueMap keyValMap) { const int BUFFER_SIZE = JSON_OBJECT_SIZE(MAX_JSON_OBJECT_SIZE); StaticJsonBuffer jsonBuffer; - JsonObject &root = jsonBuffer.createObject(); + auto& root = jsonBuffer.createObject(); for (const auto &keyVal: keyValMap) { root[keyVal.first] = keyVal.second; @@ -141,60 +78,49 @@ void AzureIoTHubMQTTClient::sendEventWithKeyVal(KeyValueMap keyValMap) { } void AzureIoTHubMQTTClient::_onActualMqttMessageCallback(const MQTT::Publish &msg) { - //Process message if (msg.payload_len() > 0 && parseMessageAsJson_ && commandsHandlerMap_.size() > 0) { - StaticJsonBuffer<200> jsonBuffer; JsonObject& json = jsonBuffer.parseObject((char*)msg.payload(), 3); + if (json.success()) { String key = ""; - if (json.containsKey("Name")) { + + if (json.containsKey("Name")) key = "Name"; - } - else if (json.containsKey("name")) { + else if (json.containsKey("name")) key = "name"; - } if (!key.equals("")) { String cmdName = String(json[key].as()); for (const auto &myPair : commandsHandlerMap_) { - if (!cmdName.equals(myPair.first)) { + if (!cmdName.equals(myPair.first)) continue; - } DEBUGLOG("Found %s command\n", cmdName.c_str()); AzureIoTHubMQTTClientCommandCallback cb = myPair.second; -// auto val = json[myPair.first]; -// cb(myPair.first, val); cb(myPair.first, json); } } } } - //Last resort - if (onSubscribeCallback_) { + // Last resort + if (onSubscribeCallback_) onSubscribeCallback_(msg); - } } void AzureIoTHubMQTTClient::onCloudCommand(String command, AzureIoTHubMQTTClient::AzureIoTHubMQTTClientCommandCallback callback) { - parseMessageAsJson_ = true; - if (commandsHandlerMap_.size() == 0) { - } - commandsHandlerMap_[command] = callback; } void AzureIoTHubMQTTClient::changeEventTo(AzureIoTHubMQTTClient::AzureIoTHubMQTTClientEvent event) { - currentEvent_ = event; if (eventCallback_) { eventCallback_(event); } -} +} \ No newline at end of file diff --git a/src/AzureIoTHubMQTTClient.h b/src/AzureIoTHubMQTTClient.h index 3fce9ab..7c37bbb 100644 --- a/src/AzureIoTHubMQTTClient.h +++ b/src/AzureIoTHubMQTTClient.h @@ -1,9 +1,7 @@ // // Created by Andri Yadi on 10/29/16. // - -#ifndef PIOMQTTAZUREIOTHUB_AZUREIOTHUBMQTT_H -#define PIOMQTTAZUREIOTHUB_AZUREIOTHUBMQTT_H +#pragma once #include #include "PubSubClient.h" @@ -18,7 +16,6 @@ #define DEBUG #ifdef DEBUG -#define DEBUG_NTPCLIENT #define DEBUGLOG(...) DEBUG_PORT.printf(__VA_ARGS__) #else #define DEBUGLOG(...) @@ -26,7 +23,6 @@ #define MAX_JSON_OBJECT_SIZE 20 #define AZURE_IOTHUB_MQTT_PORT 8883 -#define AZURE_IOTHUB_TOKEN_EXPIRE 10*24*3600 //seconds class AzureIoTHubMQTTClient : public PubSubClient { public: @@ -39,20 +35,16 @@ class AzureIoTHubMQTTClient : public PubSubClient { }; typedef std::function EventCallback; - typedef std::function AzureIoTHubMQTTClientCommandCallback; typedef std::map CommandsHandlerMap_t; + typedef std::map KeyValueMap; AzureIoTHubMQTTClient(Client& c, String iotHubHostName, String deviceId, String deviceKey); - ~AzureIoTHubMQTTClient(); + ~AzureIoTHubMQTTClient() { } - typedef std::map KeyValueMap; - - bool begin(); void run(); void end(); bool sendEvent(String payload); - bool sendEvent(const uint8_t *payload, uint32_t plength, bool retained = false); void sendEventWithKeyVal(KeyValueMap keyValMap); void onEvent(EventCallback cb) { @@ -67,8 +59,7 @@ class AzureIoTHubMQTTClient : public PubSubClient { String iotHubHostName_; String deviceId_; String deviceKey_; - String sasToken_; - String mqttCommandSubscribeTopic_, mqttCommandPublishTopic_; + String mqttCommandPublishTopic_; PubSubClient::callback_t onSubscribeCallback_; bool parseMessageAsJson_ = false; @@ -77,12 +68,8 @@ class AzureIoTHubMQTTClient : public PubSubClient { CommandsHandlerMap_t commandsHandlerMap_; bool doConnect(); - String createIotHubSASToken(char *key, String url, long expire = 0); void _onActualMqttMessageCallback(const MQTT::Publish& p); AzureIoTHubMQTTClientEvent currentEvent_ = AzureIoTHubMQTTClientEventUnknown; void changeEventTo(AzureIoTHubMQTTClientEvent event); -}; - - -#endif //PIOMQTTAZUREIOTHUB_AZUREIOTHUBMQTT_H +}; \ No newline at end of file diff --git a/src/Base64.cpp b/src/Base64.cpp deleted file mode 100755 index 73e6c21..0000000 --- a/src/Base64.cpp +++ /dev/null @@ -1,130 +0,0 @@ -#include "Base64.h" -const char b64_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - -/* 'Private' declarations */ -inline void a3_to_a4(unsigned char * a4, unsigned char * a3); -inline void a4_to_a3(unsigned char * a3, unsigned char * a4); -inline unsigned char b64_lookup(char c); - -int base64_encode(char *output, char *input, int inputLen) { - int i = 0, j = 0; - int encLen = 0; - unsigned char a3[3]; - unsigned char a4[4]; - - while(inputLen--) { - a3[i++] = *(input++); - if(i == 3) { - a3_to_a4(a4, a3); - - for(i = 0; i < 4; i++) { - output[encLen++] = b64_alphabet[a4[i]]; - } - - i = 0; - } - } - - if(i) { - for(j = i; j < 3; j++) { - a3[j] = '\0'; - } - - a3_to_a4(a4, a3); - - for(j = 0; j < i + 1; j++) { - output[encLen++] = b64_alphabet[a4[j]]; - } - - while((i++ < 3)) { - output[encLen++] = '='; - } - } - output[encLen] = '\0'; - return encLen; -} - -int base64_decode(char * output, char * input, int inputLen) { - int i = 0, j = 0; - int decLen = 0; - unsigned char a3[3]; - unsigned char a4[4]; - - - while (inputLen--) { - if(*input == '=') { - break; - } - - a4[i++] = *(input++); - if (i == 4) { - for (i = 0; i <4; i++) { - a4[i] = b64_lookup(a4[i]); - } - - a4_to_a3(a3,a4); - - for (i = 0; i < 3; i++) { - output[decLen++] = a3[i]; - } - i = 0; - } - } - - if (i) { - for (j = i; j < 4; j++) { - a4[j] = '\0'; - } - - for (j = 0; j <4; j++) { - a4[j] = b64_lookup(a4[j]); - } - - a4_to_a3(a3,a4); - - for (j = 0; j < i - 1; j++) { - output[decLen++] = a3[j]; - } - } - output[decLen] = '\0'; - return decLen; -} - -int base64_enc_len(int plainLen) { - int n = plainLen; - return (n + 2 - ((n + 2) % 3)) / 3 * 4; -} - -int base64_dec_len(char * input, int inputLen) { - int i = 0; - int numEq = 0; - for(i = inputLen - 1; input[i] == '='; i--) { - numEq++; - } - - return ((6 * inputLen) / 8) - numEq; -} - -inline void a3_to_a4(unsigned char * a4, unsigned char * a3) { - a4[0] = (a3[0] & 0xfc) >> 2; - a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4); - a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6); - a4[3] = (a3[2] & 0x3f); -} - -inline void a4_to_a3(unsigned char * a3, unsigned char * a4) { - a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4); - a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2); - a3[2] = ((a4[2] & 0x3) << 6) + a4[3]; -} - -inline unsigned char b64_lookup(char c) { - if(c >='A' && c <='Z') return c - 'A'; - if(c >='a' && c <='z') return c - 71; - if(c >='0' && c <='9') return c + 4; - if(c == '+') return 62; - if(c == '/') return 63; - return -1; -} diff --git a/src/Base64.h b/src/Base64.h deleted file mode 100755 index 35a537b..0000000 --- a/src/Base64.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2013 Adam Rudd. - * See LICENSE for more information - */ -#ifndef _BASE64_H -#define _BASE64_H - -/* b64_alphabet: - * Description: Base64 alphabet table, a mapping between integers - * and base64 digits - * Notes: This is an extern here but is defined in Base64.c - */ -extern const char b64_alphabet[]; - -/* base64_encode: - * Description: - * Encode a string of characters as base64 - * Parameters: - * output: the output buffer for the encoding, stores the encoded string - * input: the input buffer for the encoding, stores the binary to be encoded - * inputLen: the length of the input buffer, in bytes - * Return value: - * Returns the length of the encoded string - * Requirements: - * 1. output must not be null or empty - * 2. input must not be null - * 3. inputLen must be greater than or equal to 0 - */ -int base64_encode(char *output, char *input, int inputLen); - -/* base64_decode: - * Description: - * Decode a base64 encoded string into bytes - * Parameters: - * output: the output buffer for the decoding, - * stores the decoded binary - * input: the input buffer for the decoding, - * stores the base64 string to be decoded - * inputLen: the length of the input buffer, in bytes - * Return value: - * Returns the length of the decoded string - * Requirements: - * 1. output must not be null or empty - * 2. input must not be null - * 3. inputLen must be greater than or equal to 0 - */ -int base64_decode(char *output, char *input, int inputLen); - -/* base64_enc_len: - * Description: - * Returns the length of a base64 encoded string whose decoded - * form is inputLen bytes long - * Parameters: - * inputLen: the length of the decoded string - * Return value: - * The length of a base64 encoded string whose decoded form - * is inputLen bytes long - * Requirements: - * None - */ -int base64_enc_len(int inputLen); - -/* base64_dec_len: - * Description: - * Returns the length of the decoded form of a - * base64 encoded string - * Parameters: - * input: the base64 encoded string to be measured - * inputLen: the length of the base64 encoded string - * Return value: - * Returns the length of the decoded form of a - * base64 encoded string - * Requirements: - * 1. input must not be null - * 2. input must be greater than or equal to zero - */ -int base64_dec_len(char *input, int inputLen); - -#endif // _BASE64_H diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h deleted file mode 100755 index ea02ca4..0000000 --- a/src/NtpClientLib.h +++ /dev/null @@ -1,401 +0,0 @@ -/* -Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are -permitted provided that the following conditions are met : - -1. Redistributions of source code must retain the above copyright notice, this list of -conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list -of conditions and the following disclaimer in the documentation and / or other materials -provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -The views and conclusions contained in the software and documentation are those of the -authors and should not be interpreted as representing official policies, either expressed -or implied, of German Martin -*/ -/* - Name: NtpClientLib - Created: 17/08/2016 - Author: Germán Martín (gmag11@gmail.com) - Maintainer:Germán Martín (gmag11@gmail.com) - Editor: http://www.visualmicro.com - - Library to get system sync from a NTP server -*/ - -#ifndef _NtpClientLib_h -#define _NtpClientLib_h - -#define DEBUG_NTPCLIENT //Uncomment this to enable debug messages over serial port - -#ifdef ESP8266 -extern "C" { -#include "user_interface.h" -#include "sntp.h" -} -#include -using namespace std; -using namespace placeholders; -#endif - -#include - -#if defined(ARDUINO) && ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -#define NETWORK_W5100 (1) // Arduino Ethernet Shield -#define NETWORK_ENC28J60 (2) // Alternate Ethernet Shield -#define NETWORK_WIFI101 (3) // WiFi Shield 101 or MKR1000 -#define NETWORK_ESP8266 (100) // ESP8266 boards, not for Arduino using AT firmware - -#define DEFAULT_NTP_SERVER "pool.ntp.org" // Default international NTP server. I recommend you to select a closer server to get better accuracy -#define DEFAULT_NTP_PORT 123 // Default local udp port. Select a different one if neccesary (usually not needed) -#define DEFAULT_NTP_INTERVAL 1800 // Default sync interval 30 minutes -#define DEFAULT_NTP_SHORTINTERVAL 5 // Sync interval when sync has not been achieved. 15 seconds -#define DEFAULT_NTP_TIMEZONE 0 // Select your local time offset. 0 if UTC time has to be used - - -#ifdef ARDUINO_ARCH_ESP8266 -#define NETWORK_TYPE NETWORK_ESP8266 - -#elif defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 -#define NETWORK_TYPE NETWORK_WIFI101 // SET YOUR NETWORK INTERFACE -//#define NETWORK_TYPE NETWORK_W5100 - -#if NETWORK_TYPE == NETWORK_W5100 -#include -#include -#include -#include -#include -#elif NETWORK_TYPE == NETWORK_WIFI101 -#include -#include -#include -#include -#include -#include -#endif // NETWORK_TYPE - -const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message - -#else -#error "Incorrect platform. Only ARDUINO and ESP8266 MCUs are valid." -#endif - -typedef enum { - timeSyncd, // Time successfully got from NTP server - noResponse, // No response from server - invalidAddress // Address not reachable -} NTPSyncEvent_t; - -#ifdef ARDUINO_ARCH_ESP8266 -#include -typedef std::function onSyncEvent_t; -#else -typedef void(*onSyncEvent_t)(NTPSyncEvent_t); -#endif - -class NTPClient{ -public: - /** - * Construct NTP client. - */ - NTPClient(); - - /** - * Starts time synchronization. - * @param[in] NTP server name as String. - * @param[in] Time offset from UTC. - * @param[in] true if this time zone has dayligth saving. - * @param[out] true if everything went ok. - */ - bool begin(String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false); - -#ifdef ARDUINO_ARCH_ESP8266 - /** - * Sets NTP server name. - * @param[in] New NTP server name. - * @param[in] Server index (0-2). - * @param[out] True if everything went ok. - */ - bool setNtpServerName(String ntpServerName, int idx = 0); - - /** - * Gets NTP server name - * @param[in] Server index (0-2). - * @param[out] NTP server name. - */ - String getNtpServerName(int idx = 0); - - /** - * Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. - * Kept in public section to allow direct NTP request. - * @param[out] Time in UNIX time format. - */ - time_t getTime(); -#endif -#if defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 - /** - * Sets NTP server name. - * @param[in] New NTP server name. - * @param[out] True if everything went ok. - */ - bool setNtpServerName(String ntpServerName); - - /** - * Gets NTP server name - * @param[out] NTP server name. - */ - String getNtpServerName(); -#endif - - /** - * Sets timezone. - * @param[in] New time offset in hours (-11 <= timeZone <= +13). - * @param[out] True if everything went ok. - */ - bool setTimeZone(int timeZone); - - /** - * Gets timezone. - * @param[out] Time offset in hours (plus or minus). - */ - int getTimeZone(); - - /** - * Stops time synchronization. - * @param[out] True if everything went ok. - */ - bool stop(); - - /** - * Changes sync period. - * @param[in] New interval in seconds. - * @param[out] True if everything went ok. - */ - bool setInterval(int interval); - - /** - * Changes sync period in sync'd and not sync'd status. - * @param[in] New interval while time is not first adjusted yet, in seconds. - * @param[in] New interval for normal operation, in seconds. - * @param[out] True if everything went ok. - */ - bool setInterval(int shortInterval, int longInterval); - - /** - * Gets sync period. - * @param[out] Interval for normal operation, in seconds. - */ - int getInterval(); - - /** - * Changes sync period not sync'd status. - * @param[out] Interval while time is not first adjusted yet, in seconds. - */ - int getShortInterval(); - - /** - * Gets sync period. - * @param[out] Interval for normal operation in seconds. - */ - int getLongInterval() { return getInterval(); } - - /** - * Set daylight time saving option. - * @param[in] true is daylight time savings apply. - */ - void setDayLight(bool daylight); - - /** - * Get daylight time saving option. - * @param[out] true is daylight time savings apply. - */ - bool getDayLight(); - - /** - * Convert current time to a String. - * @param[out] String constructed from current time. - * TODO: Add internationalization support - */ - String getTimeStr(); - - /** - * Convert a time in UNIX format to a String representing time. - * @param[out] String constructed from current time. - * @param[in] time_t object to convert to extract time. - * TODO: Add internationalization support - */ - String getTimeStr(time_t moment); - - /** - * Convert current date to a String. - * @param[out] String constructed from current date. - * TODO: Add internationalization support - */ - String getDateStr(); - - /** - * Convert a time in UNIX format to a String representing its date. - * @param[out] String constructed from current date. - * @param[in] time_t object to convert to extract date. - * TODO: Add internationalization support - */ - String getDateStr(time_t moment); - - /** - * Convert current time and date to a String. - * @param[out] String constructed from current time. - * TODO: Add internationalization support - */ - String getTimeDateString(); - - /** - * Convert current time and date to a String. - * @param[in] time_t object to convert to String. - * @param[out] String constructed from current time. - * TODO: Add internationalization support - */ - String getTimeDateString(time_t moment); - - /** - * Gets last successful sync time in UNIX format. - * @param[out] Last successful sync time. 0 equals never. - */ - time_t getLastNTPSync(); - - /** - * Get uptime in human readable String format. - * @param[out] Uptime. - */ - String getUptimeString(); - - /** - * Get uptime in UNIX format, time since MCU was last rebooted. - * @param[out] Uptime. 0 equals never. - */ - time_t getUptime(); - - /** - * Get first boot time in UNIX format, time when MCU was last rebooted. - * @param[out] Uptime. 0 equals never. - */ - time_t getLastBootTime(); - - /** - * Get first successful synchronization time after boot. - * @param[out] First sync time. - */ - time_t getFirstSync(); - - /** - * Set a callback that triggers after a sync trial. - * @param[in] function with void(NTPSyncEvent_t) or std::function (only for ESP8266) - * NTPSyncEvent_t equals 0 is there is no error - */ - void onNTPSyncEvent(onSyncEvent_t handler); - - /** - * True if current time is inside DST period (aka. summer time). False otherwise of if NTP object has DST - * calculation disabled - * @param[out] True = summertime enabled and time in summertime period - * False = sumertime disabled or time ouside summertime period - */ - boolean isSummerTime() { - if (_daylight) - return isSummerTimePeriod(now()); - else - return false; - } - - /** - * True if given time is inside DST period (aka. summer time). False otherwise. - * @param[in] time to make the calculation with - * @param[out] True = time in summertime period - * False = time ouside summertime period - */ - boolean isSummerTimePeriod(time_t moment); - -protected: - - bool _daylight; //Does this time zone have daylight saving? - int _shortInterval; //Interval to set periodic time sync until first synchronization. - int _longInterval; //Interval to set periodic time sync - time_t _lastSyncd = 0; //Stored time of last successful sync - time_t _firstSync = 0; //Stored time of first successful sync after boot - unsigned long _uptime = 0; // Time since boot - onSyncEvent_t onSyncEvent; // Event handler callback - - /** - * Function that gets time from NTP server and convert it to Unix time format - * @param[out] Time form NTP in Unix Time Format. - */ - static time_t s_getTime(); - - /** - * Calculates the daylight saving for a given date. - * @param[in] Year. - * @param[in] Month. - * @param[in] Day. - * @param[in] Hour. - * @param[in] Time zone offset. - * @param[out] true if date and time are inside summertime period. - */ - bool summertime(int year, byte month, byte day, byte hour, byte tzHours); - - /** - * Helper function to add leading 0 to hour, minutes or seconds if < 10. - * @param[in] Digit to evaluate the need of leading 0. - * @param[out] Result digit with leading 0 if needed. - */ - String printDigits(int digits); - -#if defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 - - int _timeZone = 0; - char* _ntpServerName; - -public: - /** - * Decode NTP response contained in buffer. - * @param[in] Pointer to message buffer. - * @param[out] Decoded time from message, 0 if error ocurred. - */ - time_t decodeNtpMessage(char *messageBuffer); - - /** - * Set last successful synchronization time. - * @param[out] Last sync time. - */ - void setLastNTPSync(time_t moment); - -private: - /** - * Sends NTP request packet to given IP address. - * @param[in] NTP server's IP address. - * @param[out] True if everything went ok. - */ - //bool sendNTPpacket(IPAddress &address); -#endif -}; - -extern NTPClient NTP; - -#endif // _NtpClientLib_h - diff --git a/src/NtpClientLib_ESP.cpp b/src/NtpClientLib_ESP.cpp deleted file mode 100755 index 7313a6b..0000000 --- a/src/NtpClientLib_ESP.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/* -Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are -permitted provided that the following conditions are met : - -1. Redistributions of source code must retain the above copyright notice, this list of -conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list -of conditions and the following disclaimer in the documentation and / or other materials -provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -The views and conclusions contained in the software and documentation are those of the -authors and should not be interpreted as representing official policies, either expressed -or implied, of German Martin -*/ -// -// -// - -#ifdef ARDUINO_ARCH_ESP8266 - -#include "NtpClientLib.h" -#include - -#define DBG_PORT Serial - -#ifdef DEBUG_NTPCLIENT -#define DEBUGLOG(...) DBG_PORT.printf(__VA_ARGS__) -#else -#define DEBUGLOG(...) -#endif - - -NTPClient NTP; - -NTPClient::NTPClient() -{ -} - -bool NTPClient::setNtpServerName(String ntpServerName, int idx) -{ - char * buffer = (char *)malloc((ntpServerName.length()+1) * sizeof(char)); - if ((idx >= 0) && (idx <= 2)) { - sntp_stop(); - ntpServerName.toCharArray(buffer, ntpServerName.length()+1); - sntp_setservername(idx, buffer); - DEBUGLOG("NTP server %d set to: %s \r\n", idx, buffer); - sntp_init(); - return true; - } - return false; -} - -String NTPClient::getNtpServerName(int idx) -{ - if ((idx >= 0) && (idx <= 2)) { - return String(sntp_getservername(idx)); - } - return ""; -} - -bool NTPClient::setTimeZone(int timeZone) -{ - //if ((timeZone >= -11) && (timeZone <= 13)) { - sntp_stop(); - bool result = sntp_set_timezone(timeZone); - sntp_init(); - DEBUGLOG("NTP time zone set to: %d, result: %s\r\n", timeZone, result?"OK":"error"); - return result; - //return true; - //} - //return false; -} - -int NTPClient::getTimeZone() -{ - return sntp_get_timezone(); -} - -/*void NTPClient::setLastNTPSync(time_t moment) { - _lastSyncd = moment; -}*/ - -time_t NTPClient::s_getTime() { - return NTP.getTime(); -} - -time_t NTPClient::getTime() -{ - DEBUGLOG("-- NTP Server hostname: %s\r\n", sntp_getservername(0)); - if (WiFi.isConnected()) { - DEBUGLOG("-- Transmit NTP Request\r\n"); - uint32 secsSince1970 = sntp_get_current_timestamp(); - NTP.getUptime(); - if (secsSince1970) { - setSyncInterval(NTP.getInterval()); // Normal refresh frequency - DEBUGLOG("Sync frequency set low\r\n"); - if (getDayLight()) { - if (summertime(year(secsSince1970), month(secsSince1970), day(secsSince1970), hour(secsSince1970), getTimeZone())) { - secsSince1970 += SECS_PER_HOUR; - DEBUGLOG("Summer Time\r\n"); - } - else { - DEBUGLOG("Winter Time\r\n"); - } - - } - else { - DEBUGLOG("No daylight\r\n"); - - } - getFirstSync(); - _lastSyncd = secsSince1970; - if (!_firstSync) { - _firstSync = secsSince1970; - DEBUGLOG("First sync! %s\r\n", getTimeDateString(getFirstSync()).c_str()); - } - DEBUGLOG("Succeccful NTP sync at %s\r\n", getTimeDateString(getLastNTPSync()).c_str()); - } - else { - DEBUGLOG("-- NTP error :-(\r\n"); - setSyncInterval(getShortInterval()); // Fast refresh frequency, until successful sync - if (onSyncEvent) - onSyncEvent(noResponse); - return 0; - } - - if (onSyncEvent) - onSyncEvent(timeSyncd); - return secsSince1970; - } - else { - DEBUGLOG("-- NTP Error. WiFi not connected.\r\n"); - if (onSyncEvent) - onSyncEvent(noResponse); - return 0; - } -} - -bool NTPClient::begin(String ntpServerName, int timeOffset, bool daylight) -{ - if (!setNtpServerName(ntpServerName)) { - return false; - } - if (!setTimeZone(timeOffset)) { - return false; - } - sntp_init(); - setDayLight(daylight); - _lastSyncd = 0; - - if (!setInterval(DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) { - return false; - } - DEBUGLOG("Time sync started\r\n"); - - setSyncInterval(getShortInterval()); - setSyncProvider(s_getTime); - - return true; -} - -bool NTPClient::stop() { - setSyncProvider(NULL); - DEBUGLOG("Time sync disabled\r\n"); - sntp_stop(); - return true; -} - -bool NTPClient::setInterval(int interval) -{ - if (interval >= 5) {//10) { - if (_longInterval != interval) { - _longInterval = interval; - DEBUGLOG("Long sync interval set to %d\r\n", interval); - if (timeStatus() == timeSet) - setSyncInterval(interval); - } - return true; - } - DEBUGLOG("Error setting interval %d\r\n", interval); - - return false; -} - -bool NTPClient::setInterval(int shortInterval, int longInterval) { - if (shortInterval >= 5 && longInterval >= 10) { - _shortInterval = shortInterval; - _longInterval = longInterval; - if (timeStatus() != timeSet) { - setSyncInterval(shortInterval); - } - else { - setSyncInterval(longInterval); - } - DEBUGLOG("Short sync interval set to %d\r\n", shortInterval); - DEBUGLOG("Long sync interval set to %d\r\n", longInterval); - return true; - } - DEBUGLOG("Error setting interval. Short: %d Long: %d\r\n", shortInterval, longInterval); - return false; -} - -int NTPClient::getInterval() -{ - return _longInterval; -} - -int NTPClient::getShortInterval() -{ - return _shortInterval; -} - -void NTPClient::setDayLight(bool daylight) -{ - _daylight = daylight; - DEBUGLOG("--Set daylight %s\r\n", daylight? "ON" : "OFF"); -} - -bool NTPClient::getDayLight() -{ - return _daylight; -} - -String NTPClient::getTimeStr(time_t moment) { - if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += printDigits(hour(moment)); - timeStr += ":"; - timeStr += printDigits(minute(moment)); - timeStr += ":"; - timeStr += printDigits(second(moment)); - - return timeStr; - } - else return "Time not set"; -} - -String NTPClient::getTimeStr() { - return getTimeStr(now()); -} - -String NTPClient::getDateStr(time_t moment) { - if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - - timeStr += printDigits(day(moment)); - timeStr += "/"; - timeStr += printDigits(month(moment)); - timeStr += "/"; - timeStr += String(year(moment)); - - return timeStr; - } - else return "Date not set"; -} - -String NTPClient::getDateStr() { - return getDateStr(now()); -} - -String NTPClient::getTimeDateString(time_t moment) { - if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += getTimeStr(moment); - timeStr += " "; - timeStr += getDateStr(moment); - - return timeStr; - } - else { - return "Time not set"; - } -} - -String NTPClient::getTimeDateString() { - if (timeStatus() == timeSet) { - return getTimeDateString(now()); - } - return "Time not set"; -} - -String NTPClient::printDigits(int digits) { - // utility for digital clock display: prints preceding colon and leading 0 - String digStr = ""; - - if (digits < 10) - digStr += '0'; - digStr += String(digits); - - return digStr; -} - -bool NTPClient::summertime(int year, byte month, byte day, byte hour, byte tzHours) -// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) -{ - if ((month<3) || (month>10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez - if ((month>3) && (month<10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep - if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day)<(1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) - return true; - else - return false; -} - -time_t NTPClient::getLastBootTime() { - if (timeStatus() == timeSet) { - return (now() - getUptime()); - } - return 0; -} - -time_t NTPClient::getUptime() -{ - _uptime = _uptime + (millis() - _uptime); - return _uptime / 1000; -} - -time_t NTPClient::getFirstSync() -{ - if (!_firstSync) { - if (timeStatus() == timeSet) { - _firstSync = now() - getUptime(); - } - } - - return _firstSync; -} - -String NTPClient::getUptimeString() { - uint days; - uint8 hours; - uint8 minutes; - uint8 seconds; - - long uptime = getUptime(); - - seconds = uptime % SECS_PER_MIN; - uptime -= seconds; - minutes = (uptime % SECS_PER_HOUR)/ SECS_PER_MIN; - uptime -= minutes * SECS_PER_MIN; - hours = (uptime % SECS_PER_DAY) / SECS_PER_HOUR; - uptime -= hours * SECS_PER_HOUR; - days = uptime / SECS_PER_DAY; - - String uptimeStr = ""; - char buffer[20]; - sprintf(buffer, "%d days %02d:%02d:%02d", days, hours, minutes, seconds); - uptimeStr += buffer; - - return uptimeStr; -} - -time_t NTPClient::getLastNTPSync() { - return _lastSyncd; -} - -void NTPClient::onNTPSyncEvent(onSyncEvent_t handler) { - onSyncEvent = handler; -} - -boolean NTPClient::isSummerTimePeriod(time_t moment) { - return summertime(year(), month(), day(), hour(), getTimeZone()); -} - -#endif // ARDUINO_ARCH_ESP8266 \ No newline at end of file diff --git a/src/PubSubClient_JSON.h b/src/PubSubClient_JSON.h deleted file mode 100755 index bfd8f3f..0000000 --- a/src/PubSubClient_JSON.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -PubSubClient_JSON.h - ArduinoJson support for PubSubClient -Copyright (C) 2016 Ian Tester - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#pragma once - -#include - -namespace MQTT { - class ConnectJSON : public Connect { - public: - //! Set the "will" flag and attributes, with a JSON object "will" message - template - Connect& set_will(String willTopic, ArduinoJson::Internals::JsonPrintable& willMessage, uint8_t willQos, bool willRetain) { - _will_topic = willTopic; - _will_qos = willQos; - _will_retain = willRetain; - - if (_will_message != NULL) - delete [] _will_message; - - _will_message_len = willMessage.measureLength() + 1; - _will_message = new uint8_t[_will_message_len]; - if (_will_message != NULL) - willMessage.printTo((char*)_will_message, _will_message_len); - - return *this; - } - - }; - - class PublishJSON : public Publish { - public: - //! Publish a JSON object from the ArduinoJson library - /*! - \param topic Topic of the message - \param payload Object of the message - */ - template - PublishJSON(String topic, ArduinoJson::Internals::JsonPrintable& object) : - Publish(topic, NULL, object.measureLength() + 1) - { - _payload = new uint8_t[_payload_len]; - if (_payload != NULL) - object.printTo((char*)_payload, _payload_len); - } - - }; - -}; diff --git a/src/Utils.cpp b/src/Utils.cpp deleted file mode 100644 index 34e42c0..0000000 --- a/src/Utils.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// -// Created by Andri Yadi on 10/29/16. -// - -#include "Utils.h" - -//http://hardwarefun.com/tutorials/url-encoding-in-arduino -String urlEncode(const char* msg) -{ - const char *hex = "0123456789abcdef"; - String encodedMsg = ""; - - while (*msg!='\0'){ - if( ('a' <= *msg && *msg <= 'z') - || ('A' <= *msg && *msg <= 'Z') - || ('0' <= *msg && *msg <= '9') ) { - encodedMsg += *msg; - } else { - encodedMsg += '%'; - encodedMsg += hex[*msg >> 4]; - encodedMsg += hex[*msg & 15]; - } - msg++; - } - return encodedMsg; -} - -// http://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string -String splitStringByIndex(String data, char separator, int index) -{ - int found = 0; - int strIndex[] = { 0, -1 }; - int maxIndex = data.length()-1; - - for(int i=0; i<=maxIndex && found<=index; i++){ - if(data.charAt(i)==separator || i==maxIndex){ - found++; - strIndex[0] = strIndex[1]+1; - strIndex[1] = (i == maxIndex) ? i+1 : i; - } - } - return found>index ? data.substring(strIndex[0], strIndex[1]) : ""; -} - - -const char *GetValue(const char* value){ - char *temp = new char[strlen(value) + 1]; - strcpy(temp, value); - return temp; -} - -const char *GetStringValue(String value){ - int len = value.length() + 1; - char *temp = new char[len]; - value.toCharArray(temp, len); - return temp; -} diff --git a/src/Utils.h b/src/Utils.h deleted file mode 100644 index 6b06bd6..0000000 --- a/src/Utils.h +++ /dev/null @@ -1,20 +0,0 @@ -// -// Created by Andri Yadi on 10/29/16. -// - -#ifndef PIOMQTTAZUREIOTHUB_UTILS_H -#define PIOMQTTAZUREIOTHUB_UTILS_H - -#include - -//http://hardwarefun.com/tutorials/url-encoding-in-arduino -String urlEncode(const char* msg); - -// http://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string -String splitStringByIndex(String data, char separator, int index); - -const char *GetValue(const char* value); -const char *GetStringValue(String value); - - -#endif //PIOMQTTAZUREIOTHUB_UTILS_H diff --git a/src/sha256.cpp b/src/sha256.cpp deleted file mode 100755 index a321d12..0000000 --- a/src/sha256.cpp +++ /dev/null @@ -1,167 +0,0 @@ -#include -#include "sha256.h" - - -uint32_t sha256K[] = { - 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, - 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, - 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, - 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, - 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, - 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, - 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, - 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 -}; - -#define BUFFER_SIZE 64 - -uint8_t sha256InitState[] = { - 0x67,0xe6,0x09,0x6a, // H0 - 0x85,0xae,0x67,0xbb, // H1 - 0x72,0xf3,0x6e,0x3c, // H2 - 0x3a,0xf5,0x4f,0xa5, // H3 - 0x7f,0x52,0x0e,0x51, // H4 - 0x8c,0x68,0x05,0x9b, // H5 - 0xab,0xd9,0x83,0x1f, // H6 - 0x19,0xcd,0xe0,0x5b // H7 -}; - -void Sha256Class::init(void) { - memcpy_P(state.b,sha256InitState,32); - byteCount = 0; - bufferOffset = 0; -} - -uint32_t Sha256Class::ror32(uint32_t number, uint8_t bits) { - return ((number << (32-bits)) | (number >> bits)); -} - -void Sha256Class::hashBlock() { - uint8_t i; - uint32_t a,b,c,d,e,f,g,h,t1,t2; - - a=state.w[0]; - b=state.w[1]; - c=state.w[2]; - d=state.w[3]; - e=state.w[4]; - f=state.w[5]; - g=state.w[6]; - h=state.w[7]; - - for (i=0; i<64; i++) { - if (i>=16) { - t1 = buffer.w[i&15] + buffer.w[(i-7)&15]; - t2 = buffer.w[(i-2)&15]; - t1 += ror32(t2,17) ^ ror32(t2,19) ^ (t2>>10); - t2 = buffer.w[(i-15)&15]; - t1 += ror32(t2,7) ^ ror32(t2,18) ^ (t2>>3); - buffer.w[i&15] = t1; - } - t1 = h; - t1 += ror32(e,6) ^ ror32(e,11) ^ ror32(e,25); // ∑1(e) - t1 += g ^ (e & (g ^ f)); // Ch(e,f,g) - t1 += pgm_read_dword(sha256K+i); // Ki - t1 += buffer.w[i&15]; // Wi - t2 = ror32(a,2) ^ ror32(a,13) ^ ror32(a,22); // ∑0(a) - t2 += ((b & c) | (a & (b | c))); // Maj(a,b,c) - h=g; g=f; f=e; e=d+t1; d=c; c=b; b=a; a=t1+t2; - } - state.w[0] += a; - state.w[1] += b; - state.w[2] += c; - state.w[3] += d; - state.w[4] += e; - state.w[5] += f; - state.w[6] += g; - state.w[7] += h; -} - -void Sha256Class::addUncounted(uint8_t data) { - buffer.b[bufferOffset ^ 3] = data; - bufferOffset++; - if (bufferOffset == BUFFER_SIZE) { - hashBlock(); - bufferOffset = 0; - } -} - -size_t Sha256Class::write(uint8_t data) { - ++byteCount; - addUncounted(data); -} - -void Sha256Class::pad() { - // Implement SHA-256 padding (fips180-2 §5.1.1) - - // Pad with 0x80 followed by 0x00 until the end of the block - addUncounted(0x80); - while (bufferOffset != 56) addUncounted(0x00); - - // Append length in the last 8 bytes - addUncounted(0); // We're only using 32 bit lengths - addUncounted(0); // But SHA-1 supports 64 bit lengths - addUncounted(0); // So zero pad the top bits - addUncounted(byteCount >> 29); // Shifting to multiply by 8 - addUncounted(byteCount >> 21); // as SHA-1 supports bitstreams as well as - addUncounted(byteCount >> 13); // byte. - addUncounted(byteCount >> 5); - addUncounted(byteCount << 3); -} - - -uint8_t* Sha256Class::result(void) { - // Pad to complete the last block - pad(); - - // Swap byte order back - for (int i=0; i<8; i++) { - uint32_t a,b; - a=state.w[i]; - b=a<<24; - b|=(a<<8) & 0x00ff0000; - b|=(a>>8) & 0x0000ff00; - b|=a>>24; - state.w[i]=b; - } - - // Return pointer to hash (20 characters) - return state.b; -} - -#define HMAC_IPAD 0x36 -#define HMAC_OPAD 0x5c - -uint8_t keyBuffer[BLOCK_LENGTH]; // K0 in FIPS-198a -uint8_t innerHash[HASH_LENGTH]; - -void Sha256Class::initHmac(const uint8_t* key, int keyLength) { - uint8_t i; - memset(keyBuffer,0,BLOCK_LENGTH); - if (keyLength > BLOCK_LENGTH) { - // Hash long keys - init(); - for (;keyLength--;) write(*key++); - memcpy(keyBuffer,result(),HASH_LENGTH); - } else { - // Block length keys are used as is - memcpy(keyBuffer,key,keyLength); - } - // Start inner hash - init(); - for (i=0; i -#include "Print.h" - -#define HASH_LENGTH 32 -#define BLOCK_LENGTH 64 - -union _buffer { - uint8_t b[BLOCK_LENGTH]; - uint32_t w[BLOCK_LENGTH/4]; -}; -union _state { - uint8_t b[HASH_LENGTH]; - uint32_t w[HASH_LENGTH/4]; -}; - -class Sha256Class : public Print -{ - public: - void init(void); - void initHmac(const uint8_t* secret, int secretLength); - uint8_t* result(void); - uint8_t* resultHmac(void); - virtual size_t write(uint8_t); - using Print::write; - private: - void pad(); - void addUncounted(uint8_t data); - void hashBlock(); - uint32_t ror32(uint32_t number, uint8_t bits); - _buffer buffer; - uint8_t bufferOffset; - _state state; - uint32_t byteCount; - uint8_t keyBuffer[BLOCK_LENGTH]; - uint8_t innerHash[HASH_LENGTH]; -}; -extern Sha256Class Sha256; - -#endif From 4e86f19f4d5831a35e3c109d176c6fd5a1e99539 Mon Sep 17 00:00:00 2001 From: erikoleary Date: Sun, 18 Nov 2018 17:24:57 -0600 Subject: [PATCH 6/6] Removed esp8266 reference --- library.properties | 2 +- src/AzureIoTHubMQTTClient.cpp | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/library.properties b/library.properties index 60cf9c6..f98eaaa 100644 --- a/library.properties +++ b/library.properties @@ -6,4 +6,4 @@ sentence=Azure IoT Hub client library for ESP8266 via MQTT protocol. paragraph=Azure IoT Hub client library for ESP8266 that specifically uses MQTT protocol. See readme for more details. category=Communication url=https://github.com/andriyadi/AzureIoTHubMQTTClient -architectures=esp8266 +architectures=esp8266,esp32 \ No newline at end of file diff --git a/src/AzureIoTHubMQTTClient.cpp b/src/AzureIoTHubMQTTClient.cpp index d9807cf..c33a2f0 100644 --- a/src/AzureIoTHubMQTTClient.cpp +++ b/src/AzureIoTHubMQTTClient.cpp @@ -4,8 +4,6 @@ #include "AzureIoTHubMQTTClient.h" -#include - AzureIoTHubMQTTClient::AzureIoTHubMQTTClient(Client& c, String iotHubHostName, String deviceId, String deviceKey): iotHubHostName_(iotHubHostName), deviceId_(deviceId), deviceKey_(deviceKey), PubSubClient(c, iotHubHostName, AZURE_IOTHUB_MQTT_PORT) {