diff --git a/.travis.yml b/.travis.yml index 10e2cf9da..a54ffd678 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,10 +2,34 @@ language: generic env: global: - IDE_VERSION=1.8.9 - matrix: - - BOARD="arduino:samd:mkr1000" - - BOARD="arduino:samd:mkrwifi1010" - - BOARD="arduino:samd:mkrgsm1400" +matrix: + include: + - env: + - BOARD="arduino:samd:mkr1000" + - env: + - BOARD="arduino:samd:mkrwifi1010" + - env: + - BOARD="arduino:samd:mkrgsm1400" + - env: + - NAME=Code Formatting Check + # must define an empty before_install phase, otherwise the default one is used + before_install: true + install: + # install Artistic Style code formatter tool: http://astyle.sourceforge.net + - | + mkdir "${HOME}/astyle"; + wget --no-verbose --output-document="${HOME}/astyle/astyle.tar.gz" "https://iweb.dl.sourceforge.net/project/astyle/astyle/astyle%203.1/astyle_3.1_linux.tar.gz"; + tar --extract --file="${HOME}/astyle/astyle.tar.gz" --directory="${HOME}/astyle"; + cd "${HOME}/astyle/astyle/build/gcc"; + make; + export PATH=$PWD/bin:$PATH; + cd "$TRAVIS_BUILD_DIR" + # download Arduino's Artistic Style configuration file + - wget --directory-prefix="${HOME}/astyle" https://raw.githubusercontent.com/arduino/Arduino/master/build/shared/examples_formatter.conf + script: + # check code formatting + - find . -regextype posix-extended -path './.git' -prune -or \( -iregex '.*\.((ino)|(h)|(hpp)|(hh)|(hxx)|(h\+\+)|(cpp)|(cc)|(cxx)|(c\+\+)|(cp)|(c)|(ipp)|(ii)|(ixx)|(inl)|(tpp)|(txx)|(tpl))$' -and -type f \) -print0 | xargs -0 -L1 bash -c 'if ! diff $0 <(astyle --options=${HOME}/astyle/examples_formatter.conf --dry-run < $0); then echo "Non-compliant code formatting in $0"; false; fi' +# default phases before_install: - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz - tar xf arduino-$IDE_VERSION-linux64.tar.xz @@ -31,4 +55,10 @@ script: - buildExampleSketch ArduinoIoTCloud_LED_switch - buildExampleSketch ArduinoIoTCloud_Travis_CI - buildExampleUtilitySketch Provisioning +notifications: + webhooks: + urls: + - https://www.travisbuddy.com/ + on_success: never + on_failure: always diff --git a/examples/ArduinoIoTCloud_LED_switch/ArduinoIoTCloud_LED_switch.ino b/examples/ArduinoIoTCloud_LED_switch/ArduinoIoTCloud_LED_switch.ino index 9516eb158..0ea674d5c 100644 --- a/examples/ArduinoIoTCloud_LED_switch/ArduinoIoTCloud_LED_switch.ino +++ b/examples/ArduinoIoTCloud_LED_switch/ArduinoIoTCloud_LED_switch.ino @@ -29,13 +29,13 @@ void setup() { // tell ArduinoIoTCloud to use our WiFi connection ArduinoCloud.begin(ArduinoIoTPreferredConnection); - /* - The following function allows you to obtain more information + /* + The following function allows you to obtain more information related to the state of network and IoT Cloud connection and errors the higher number the more granular information you'll get. The default is 0 (only errors). Maximum is 3 - + setDebugMessageLevel(3); */ ArduinoCloud.printDebugInfo(); diff --git a/examples/ArduinoIoTCloud_LED_switch/arduino_secrets.h b/examples/ArduinoIoTCloud_LED_switch/arduino_secrets.h index 343d85ce9..d727cfb77 100644 --- a/examples/ArduinoIoTCloud_LED_switch/arduino_secrets.h +++ b/examples/ArduinoIoTCloud_LED_switch/arduino_secrets.h @@ -1,13 +1,13 @@ /* - Fill in your login credentials: + Fill in your login credentials: - The following lines are used for WiFi enabled boards (MKR1000, MKR WiFi 1010) + The following lines are used for WiFi enabled boards (MKR1000, MKR WiFi 1010) */ #define SECRET_SSID "YOUR_WIFI_NETWORK_NAME" #define SECRET_PASS "YOUR_WIFI_PASSWORD" /* - If you prefer using a MKR GSM 1400 comment the lines above and uncommet the following. - PIN, APN, Login and Password are supplied by your Cellular Data provider. + If you prefer using a MKR GSM 1400 comment the lines above and uncommet the following. + PIN, APN, Login and Password are supplied by your Cellular Data provider. */ #define SECRET_PIN "" #define SECRET_APN "" diff --git a/examples/ArduinoIoTCloud_LED_switch/thingProperties.h b/examples/ArduinoIoTCloud_LED_switch/thingProperties.h index 79edd5f52..061dcc0af 100644 --- a/examples/ArduinoIoTCloud_LED_switch/thingProperties.h +++ b/examples/ArduinoIoTCloud_LED_switch/thingProperties.h @@ -5,7 +5,7 @@ #include #elif defined(BOARD_HAS_GSM) #include -#else +#else #error "Arduino IoT Cloud currently only supports MKR1000, MKR WiFi 1010 and MKR GSM 1400" #endif @@ -25,9 +25,9 @@ void initProperties() { } #if defined(BOARD_HAS_WIFI) -ConnectionManager * ArduinoIoTPreferredConnection = new WiFiConnectionManager(SECRET_SSID, SECRET_PASS); + ConnectionManager * ArduinoIoTPreferredConnection = new WiFiConnectionManager(SECRET_SSID, SECRET_PASS); #elif defined(BOARD_HAS_GSM) -ConnectionManager * ArduinoIoTPreferredConnection = new GSMConnectionManager (SECRET_PIN, SECRET_APN, SECRET_LOGIN, SECRET_PASS); + ConnectionManager * ArduinoIoTPreferredConnection = new GSMConnectionManager(SECRET_PIN, SECRET_APN, SECRET_LOGIN, SECRET_PASS); #endif diff --git a/examples/ArduinoIoTCloud_Travis_CI/ArduinoIoTCloud_Travis_CI.ino b/examples/ArduinoIoTCloud_Travis_CI/ArduinoIoTCloud_Travis_CI.ino index b97331497..16ba6451d 100644 --- a/examples/ArduinoIoTCloud_Travis_CI/ArduinoIoTCloud_Travis_CI.ino +++ b/examples/ArduinoIoTCloud_Travis_CI/ArduinoIoTCloud_Travis_CI.ino @@ -1,8 +1,8 @@ /* - * This sketch is used in combination with Travis CI to check if - * unintentional breaking changes are made to the used facing - * Arduino IoT Cloud API. - */ + This sketch is used in combination with Travis CI to check if + unintentional breaking changes are made to the used facing + Arduino IoT Cloud API. +*/ #include "arduino_secrets.h" #include "thingProperties.h" diff --git a/examples/ArduinoIoTCloud_Travis_CI/thingProperties.h b/examples/ArduinoIoTCloud_Travis_CI/thingProperties.h index ab8a856a4..77d124fea 100644 --- a/examples/ArduinoIoTCloud_Travis_CI/thingProperties.h +++ b/examples/ArduinoIoTCloud_Travis_CI/thingProperties.h @@ -1,5 +1,5 @@ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include @@ -9,25 +9,25 @@ #include #elif defined(BOARD_HAS_GSM) #include -#else +#else #error "Arduino IoT Cloud currently only supports MKR1000, MKR WiFi 1010 and MKR GSM 1400" #endif /****************************************************************************** - * DEFINES + DEFINES ******************************************************************************/ #define THING_ID "ARDUINO_IOT_CLOUD_THING_ID" /****************************************************************************** - * GLOBAL CONSTANTS + GLOBAL CONSTANTS ******************************************************************************/ int const MIN_DELTA_INT_PROPERTY = 5; float const MIN_DELTA_FLOAT_PROPERTY = 10.0f; /****************************************************************************** - * GLOBAL VARIABLES + GLOBAL VARIABLES ******************************************************************************/ bool bool_property_1; @@ -55,36 +55,36 @@ String str_property_7; String str_property_8; #if defined(BOARD_HAS_WIFI) -ConnectionManager * ArduinoIoTPreferredConnection = new WiFiConnectionManager(SECRET_SSID, SECRET_PASS); + ConnectionManager * ArduinoIoTPreferredConnection = new WiFiConnectionManager(SECRET_SSID, SECRET_PASS); #elif defined(BOARD_HAS_GSM) -ConnectionManager * ArduinoIoTPreferredConnection = new GSMConnectionManager (SECRET_PIN, SECRET_APN, SECRET_LOGIN, SECRET_PASS); + ConnectionManager * ArduinoIoTPreferredConnection = new GSMConnectionManager(SECRET_PIN, SECRET_APN, SECRET_LOGIN, SECRET_PASS); #endif /****************************************************************************** - * PROTOTYPES + PROTOTYPES ******************************************************************************/ -void onBoolPropertyChange (); -void onIntPropertyChange (); -void onFloatPropertyChange (); +void onBoolPropertyChange(); +void onIntPropertyChange(); +void onFloatPropertyChange(); void onStringPropertyChange(); /****************************************************************************** - * FUNCTIONS + FUNCTIONS ******************************************************************************/ void initProperties() { ArduinoCloud.setThingId(THING_ID); - ArduinoCloud.addProperty(bool_property_1, READWRITE, 1*SECONDS); - ArduinoCloud.addProperty(int_property_1, READ, 2*MINUTES); - ArduinoCloud.addProperty(float_property_1, WRITE, 3*HOURS ); - ArduinoCloud.addProperty(str_property_1, READWRITE, 4*DAYS ); + ArduinoCloud.addProperty(bool_property_1, READWRITE, 1 * SECONDS); + ArduinoCloud.addProperty(int_property_1, READ, 2 * MINUTES); + ArduinoCloud.addProperty(float_property_1, WRITE, 3 * HOURS); + ArduinoCloud.addProperty(str_property_1, READWRITE, 4 * DAYS); - ArduinoCloud.addProperty(bool_property_2, Permission::ReadWrite).publishEvery(1*SECONDS); - ArduinoCloud.addProperty(int_property_2, Permission::Read ).publishEvery(1*MINUTES); - ArduinoCloud.addProperty(float_property_2, Permission::Write ).publishEvery(3*HOURS ); - ArduinoCloud.addProperty(str_property_2, Permission::ReadWrite).publishEvery(4*DAYS ); + ArduinoCloud.addProperty(bool_property_2, Permission::ReadWrite).publishEvery(1 * SECONDS); + ArduinoCloud.addProperty(int_property_2, Permission::Read).publishEvery(1 * MINUTES); + ArduinoCloud.addProperty(float_property_2, Permission::Write).publishEvery(3 * HOURS); + ArduinoCloud.addProperty(str_property_2, Permission::ReadWrite).publishEvery(4 * DAYS); ArduinoCloud.addProperty(int_property_3, READWRITE, ON_CHANGE); /* Default 'minDelta' = 0 */ ArduinoCloud.addProperty(int_property_4, READWRITE, ON_CHANGE, onIntPropertyChange); /* Default 'minDelta' = 0 */ @@ -94,11 +94,11 @@ void initProperties() { ArduinoCloud.addProperty(float_property_3, Permission::ReadWrite).publishOnChange(MIN_DELTA_FLOAT_PROPERTY); ArduinoCloud.addProperty(float_property_4, Permission::ReadWrite).publishOnChange(MIN_DELTA_FLOAT_PROPERTY).onUpdate(onFloatPropertyChange); - ArduinoCloud.addProperty(str_property_3, READWRITE, 1*SECONDS, 0 /* onStringPropertyChange */, "" /* 'minDelta' */, MOST_RECENT_WINS); - ArduinoCloud.addProperty(str_property_4, READWRITE, 1*SECONDS, 0 /* onStringPropertyChange */, "" /* 'minDelta' */, CLOUD_WINS); - ArduinoCloud.addProperty(str_property_5, READWRITE, 1*SECONDS, 0 /* onStringPropertyChange */, "" /* 'minDelta' */, DEVICE_WINS); + ArduinoCloud.addProperty(str_property_3, READWRITE, 1 * SECONDS, 0 /* onStringPropertyChange */, "" /* 'minDelta' */, MOST_RECENT_WINS); + ArduinoCloud.addProperty(str_property_4, READWRITE, 1 * SECONDS, 0 /* onStringPropertyChange */, "" /* 'minDelta' */, CLOUD_WINS); + ArduinoCloud.addProperty(str_property_5, READWRITE, 1 * SECONDS, 0 /* onStringPropertyChange */, "" /* 'minDelta' */, DEVICE_WINS); - ArduinoCloud.addProperty(str_property_6, Permission::ReadWrite).publishEvery(1*SECONDS).onSync(MOST_RECENT_WINS); - ArduinoCloud.addProperty(str_property_7, Permission::ReadWrite).publishEvery(1*SECONDS).onSync(CLOUD_WINS); - ArduinoCloud.addProperty(str_property_8, Permission::ReadWrite).publishEvery(1*SECONDS).onSync(DEVICE_WINS); + ArduinoCloud.addProperty(str_property_6, Permission::ReadWrite).publishEvery(1 * SECONDS).onSync(MOST_RECENT_WINS); + ArduinoCloud.addProperty(str_property_7, Permission::ReadWrite).publishEvery(1 * SECONDS).onSync(CLOUD_WINS); + ArduinoCloud.addProperty(str_property_8, Permission::ReadWrite).publishEvery(1 * SECONDS).onSync(DEVICE_WINS); } diff --git a/examples/utility/Provisioning/Provisioning.ino b/examples/utility/Provisioning/Provisioning.ino index 310a848b8..179b03d2d 100644 --- a/examples/utility/Provisioning/Provisioning.ino +++ b/examples/utility/Provisioning/Provisioning.ino @@ -88,7 +88,7 @@ void setup() { hexStringToBytes(serialNumber, serialNumberBytes, sizeof(serialNumberBytes)); hexStringToBytes(authorityKeyIdentifier, authorityKeyIdentifierBytes, sizeof(authorityKeyIdentifierBytes)); hexStringToBytes(signature, signatureBytes, sizeof(signatureBytes)); - + if (!ECCX08.writeSlot(deviceIdSlot, deviceIdBytes, sizeof(deviceIdBytes))) { Serial.println("Error storing device id!"); while (1); diff --git a/src/ArduinoIoTCloud.cpp b/src/ArduinoIoTCloud.cpp index 575af22a2..2be28f562 100644 --- a/src/ArduinoIoTCloud.cpp +++ b/src/ArduinoIoTCloud.cpp @@ -1,19 +1,19 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #include #include "utility/ECCX08Cert.h" @@ -37,45 +37,45 @@ const static int CONNECT_FAILURE_SUBSCRIBE = -1; static ConnectionManager *getTimeConnection = NULL; static unsigned long getTime() { - if (!getTimeConnection) return 0; + if (!getTimeConnection) { + return 0; + } unsigned long time = getTimeConnection->getTime(); if (!NTPUtils::isTimeValid(time)) { debugMessage(DebugLevel::Error, "Bogus NTP time from API, fallback to UDP method"); time = NTPUtils(getTimeConnection->getUDP()).getTime(); } #ifdef ARDUINO_ARCH_SAMD - rtc.setEpoch(time); + rtc.setEpoch(time); #endif return time; } static unsigned long getTimestamp() { #ifdef ARDUINO_ARCH_SAMD - return rtc.getEpoch(); + return rtc.getEpoch(); #else - #warning "No RTC available on this architecture - ArduinoIoTCloud will not keep track of local change timestamps ." - return 0; +#warning "No RTC available on this architecture - ArduinoIoTCloud will not keep track of local change timestamps ." + return 0; #endif } ArduinoIoTCloudClass::ArduinoIoTCloudClass() : - _thing_id (""), + _thing_id(""), _bearSslClient(NULL), - _mqttClient (NULL), - connection (NULL), - _stdinTopic (""), - _stdoutTopic (""), - _shadowTopicOut (""), - _shadowTopicIn (""), - _dataTopicOut (""), - _dataTopicIn (""), - _otaTopic (""), - _lastSyncRequestTickTime(0) -{ + _mqttClient(NULL), + connection(NULL), + _stdinTopic(""), + _stdoutTopic(""), + _shadowTopicOut(""), + _shadowTopicIn(""), + _dataTopicOut(""), + _dataTopicIn(""), + _otaTopic(""), + _lastSyncRequestTickTime(0) { } -ArduinoIoTCloudClass::~ArduinoIoTCloudClass() -{ +ArduinoIoTCloudClass::~ArduinoIoTCloudClass() { if (_mqttClient) { delete _mqttClient; _mqttClient = NULL; @@ -87,20 +87,18 @@ ArduinoIoTCloudClass::~ArduinoIoTCloudClass() } } -int ArduinoIoTCloudClass::begin(ConnectionManager *c, String brokerAddress, uint16_t brokerPort) -{ +int ArduinoIoTCloudClass::begin(ConnectionManager *c, String brokerAddress, uint16_t brokerPort) { connection = c; Client &connectionClient = c->getClient(); _brokerAddress = brokerAddress; _brokerPort = brokerPort; #ifdef ARDUINO_ARCH_SAMD - rtc.begin(); + rtc.begin(); #endif return begin(connectionClient, _brokerAddress, _brokerPort); } -int ArduinoIoTCloudClass::begin(Client& net, String brokerAddress, uint16_t brokerPort) -{ +int ArduinoIoTCloudClass::begin(Client& net, String brokerAddress, uint16_t brokerPort) { _net = &net; // store the broker address as class member @@ -138,22 +136,22 @@ int ArduinoIoTCloudClass::begin(Client& net, String brokerAddress, uint16_t brok if (_bearSslClient) { delete _bearSslClient; } - if(connection != NULL){ + if (connection != NULL) { _bearSslClient = new BearSSLClient(connection->getClient()); - }else{ + } else { _bearSslClient = new BearSSLClient(*_net); } - + _bearSslClient->setEccSlot(keySlot, ECCX08Cert.bytes(), ECCX08Cert.length()); _mqttClient = new MqttClient(*_bearSslClient); // Bind ArduinoBearSSL callback using static "non-method" function - if(connection != NULL){ + if (connection != NULL) { getTimeConnection = connection; ArduinoBearSSL.onGetTime(getTime); } - - + + // TODO: Find a better way to allow callback into object method // Begin function for the MQTTClient mqttClientBegin(); @@ -162,22 +160,19 @@ int ArduinoIoTCloudClass::begin(Client& net, String brokerAddress, uint16_t brok return 1; } -void ArduinoIoTCloudClass::onGetTime(unsigned long(*callback)(void)) -{ +void ArduinoIoTCloudClass::onGetTime(unsigned long(*callback)(void)) { ArduinoBearSSL.onGetTime(callback); } // private class method used to initialize mqttClient class member. (called in the begin class method) -void ArduinoIoTCloudClass::mqttClientBegin() -{ +void ArduinoIoTCloudClass::mqttClientBegin() { // MQTT topics definition _stdoutTopic = "/a/d/" + _device_id + "/s/o"; _stdinTopic = "/a/d/" + _device_id + "/s/i"; - if(_thing_id == "") { + if (_thing_id == "") { _dataTopicIn = "/a/d/" + _device_id + "/e/i"; _dataTopicOut = "/a/d/" + _device_id + "/e/o"; - } - else { + } else { _dataTopicIn = "/a/t/" + _thing_id + "/e/i"; _dataTopicOut = "/a/t/" + _thing_id + "/e/o"; _shadowTopicIn = "/a/t/" + _thing_id + "/shadow/i"; @@ -191,17 +186,22 @@ void ArduinoIoTCloudClass::mqttClientBegin() _mqttClient->setId(_device_id.c_str()); } -int ArduinoIoTCloudClass::connect() -{ +int ArduinoIoTCloudClass::connect() { // Username: device id // Password: empty if (!_mqttClient->connect(_brokerAddress.c_str(), _brokerPort)) { return CONNECT_FAILURE; } - if(_mqttClient->subscribe(_stdinTopic ) == 0) return CONNECT_FAILURE_SUBSCRIBE; - if(_mqttClient->subscribe(_dataTopicIn ) == 0) return CONNECT_FAILURE_SUBSCRIBE; - if(_shadowTopicIn != "") { - if(_mqttClient->subscribe(_shadowTopicIn) == 0) return CONNECT_FAILURE_SUBSCRIBE; + if (_mqttClient->subscribe(_stdinTopic) == 0) { + return CONNECT_FAILURE_SUBSCRIBE; + } + if (_mqttClient->subscribe(_dataTopicIn) == 0) { + return CONNECT_FAILURE_SUBSCRIBE; + } + if (_shadowTopicIn != "") { + if (_mqttClient->subscribe(_shadowTopicIn) == 0) { + return CONNECT_FAILURE_SUBSCRIBE; + } _syncStatus = ArduinoIoTSynchronizationStatus::SYNC_STATUS_WAIT_FOR_CLOUD_VALUES; _lastSyncRequestTickTime = 0; @@ -210,32 +210,30 @@ int ArduinoIoTCloudClass::connect() return CONNECT_SUCCESS; } -bool ArduinoIoTCloudClass::disconnect() -{ +bool ArduinoIoTCloudClass::disconnect() { _mqttClient->stop(); return true; } -void ArduinoIoTCloudClass::poll() -{ +void ArduinoIoTCloudClass::poll() { update(); } -void ArduinoIoTCloudClass::update(CallbackFunc onSyncCompleteCallback) -{ +void ArduinoIoTCloudClass::update(CallbackFunc onSyncCompleteCallback) { // If user call update() without parameters use the default ones update(MAX_RETRIES, RECONNECTION_TIMEOUT, onSyncCompleteCallback); } -void ArduinoIoTCloudClass::update(int const reconnectionMaxRetries, int const reconnectionTimeoutMs, CallbackFunc onSyncCompleteCallback) -{ - unsigned long const timestamp = getTimestamp(); - //check if a property is changed - if(timestamp != 0) Thing.updateTimestampOnChangedProperties(timestamp); - +void ArduinoIoTCloudClass::update(int const reconnectionMaxRetries, int const reconnectionTimeoutMs, CallbackFunc onSyncCompleteCallback) { + unsigned long const timestamp = getTimestamp(); + //check if a property is changed + if (timestamp != 0) { + Thing.updateTimestampOnChangedProperties(timestamp); + } + connectionCheck(); - if(iotStatus != ArduinoIoTConnectionStatus::CONNECTED){ + if (iotStatus != ArduinoIoTConnectionStatus::CONNECTED) { return; } @@ -253,15 +251,15 @@ void ArduinoIoTCloudClass::update(int const reconnectionMaxRetries, int const re } break; case ArduinoIoTSynchronizationStatus::SYNC_STATUS_VALUES_PROCESSED: - if(onSyncCompleteCallback != NULL) + if (onSyncCompleteCallback != NULL) { (*onSyncCompleteCallback)(); + } _syncStatus = ArduinoIoTSynchronizationStatus::SYNC_STATUS_SYNCHRONIZED; break; } } -void ArduinoIoTCloudClass::sendPropertiesToCloud() -{ +void ArduinoIoTCloudClass::sendPropertiesToCloud() { uint8_t data[MQTT_TRANSMIT_BUFFER_SIZE]; int const length = Thing.encode(data, sizeof(data)); if (length > 0) { @@ -269,8 +267,7 @@ void ArduinoIoTCloudClass::sendPropertiesToCloud() } } -int ArduinoIoTCloudClass::reconnect(Client& /* net */) -{ +int ArduinoIoTCloudClass::reconnect(Client& /* net */) { if (_mqttClient->connected()) { _mqttClient->stop(); } @@ -279,13 +276,11 @@ int ArduinoIoTCloudClass::reconnect(Client& /* net */) return connect(); } -int ArduinoIoTCloudClass::connected() -{ +int ArduinoIoTCloudClass::connected() { return _mqttClient->connected(); } -int ArduinoIoTCloudClass::writeProperties(const byte data[], int length) -{ +int ArduinoIoTCloudClass::writeProperties(const byte data[], int length) { if (!_mqttClient->beginMessage(_dataTopicOut, length, false, 0)) { return 0; } @@ -301,8 +296,7 @@ int ArduinoIoTCloudClass::writeProperties(const byte data[], int length) return 1; } -int ArduinoIoTCloudClass::writeStdout(const byte data[], int length) -{ +int ArduinoIoTCloudClass::writeStdout(const byte data[], int length) { if (!_mqttClient->beginMessage(_stdoutTopic, length, false, 0)) { return 0; } @@ -318,8 +312,7 @@ int ArduinoIoTCloudClass::writeStdout(const byte data[], int length) return 1; } -int ArduinoIoTCloudClass::writeShadowOut(const byte data[], int length) -{ +int ArduinoIoTCloudClass::writeShadowOut(const byte data[], int length) { if (!_mqttClient->beginMessage(_shadowTopicOut, length, false, 0)) { return 0; } @@ -335,13 +328,11 @@ int ArduinoIoTCloudClass::writeShadowOut(const byte data[], int length) return 1; } -void ArduinoIoTCloudClass::onMessage(int length) -{ +void ArduinoIoTCloudClass::onMessage(int length) { ArduinoCloud.handleMessage(length); } -void ArduinoIoTCloudClass::handleMessage(int length) -{ +void ArduinoIoTCloudClass::handleMessage(int length) { String topic = _mqttClient->messageTopic(); byte bytes[length]; @@ -364,8 +355,7 @@ void ArduinoIoTCloudClass::handleMessage(int length) } } -void ArduinoIoTCloudClass::requestLastValue() -{ +void ArduinoIoTCloudClass::requestLastValue() { // Send the getLastValues CBOR message to the cloud // [{0: "r:m", 3: "getLastValues"}] = 81 A2 00 63 72 3A 6D 03 6D 67 65 74 4C 61 73 74 56 61 6C 75 65 73 // Use http://cbor.me to easily generate CBOR encoding @@ -373,69 +363,66 @@ void ArduinoIoTCloudClass::requestLastValue() writeShadowOut(CBOR_REQUEST_LAST_VALUE_MSG, sizeof(CBOR_REQUEST_LAST_VALUE_MSG)); } -void ArduinoIoTCloudClass::connectionCheck() -{ - if(connection != NULL){ +void ArduinoIoTCloudClass::connectionCheck() { + if (connection != NULL) { connection->check(); - + if (connection->getStatus() != NetworkConnectionState::CONNECTED) { - if(iotStatus == ArduinoIoTConnectionStatus::CONNECTED){ + if (iotStatus == ArduinoIoTConnectionStatus::CONNECTED) { setIoTConnectionState(ArduinoIoTConnectionStatus::DISCONNECTED); } return; } } - + switch (iotStatus) { case ArduinoIoTConnectionStatus::IDLE: { - setIoTConnectionState(ArduinoIoTConnectionStatus::CONNECTING); - } - break; + setIoTConnectionState(ArduinoIoTConnectionStatus::CONNECTING); + } + break; case ArduinoIoTConnectionStatus::ERROR: { - debugMessage(DebugLevel::Error, "Cloud Error. Retrying..."); - setIoTConnectionState(ArduinoIoTConnectionStatus::RECONNECTING); - } - break; + debugMessage(DebugLevel::Error, "Cloud Error. Retrying..."); + setIoTConnectionState(ArduinoIoTConnectionStatus::RECONNECTING); + } + break; case ArduinoIoTConnectionStatus::CONNECTED: { - debugMessageNoTimestamp(DebugLevel::Verbose, "."); - if (!_mqttClient->connected()){ - setIoTConnectionState(ArduinoIoTConnectionStatus::DISCONNECTED); + debugMessageNoTimestamp(DebugLevel::Verbose, "."); + if (!_mqttClient->connected()) { + setIoTConnectionState(ArduinoIoTConnectionStatus::DISCONNECTED); + } } - } - break; + break; case ArduinoIoTConnectionStatus::DISCONNECTED: { - setIoTConnectionState(ArduinoIoTConnectionStatus::RECONNECTING); - } - break; + setIoTConnectionState(ArduinoIoTConnectionStatus::RECONNECTING); + } + break; case ArduinoIoTConnectionStatus::RECONNECTING: { - int const ret_code_reconnect = reconnect(*_net); - debugMessage(DebugLevel::Info, "ArduinoCloud.reconnect(): %d", ret_code_reconnect); - if (ret_code_reconnect == CONNECT_SUCCESS) { - setIoTConnectionState(ArduinoIoTConnectionStatus::CONNECTED); - CloudSerial.begin(9600); - CloudSerial.println("Hello from Cloud Serial!"); + int const ret_code_reconnect = reconnect(*_net); + debugMessage(DebugLevel::Info, "ArduinoCloud.reconnect(): %d", ret_code_reconnect); + if (ret_code_reconnect == CONNECT_SUCCESS) { + setIoTConnectionState(ArduinoIoTConnectionStatus::CONNECTED); + CloudSerial.begin(9600); + CloudSerial.println("Hello from Cloud Serial!"); + } } - } - break; + break; case ArduinoIoTConnectionStatus::CONNECTING: { - int const ret_code_connect = connect(); - debugMessage(DebugLevel::Verbose, "ArduinoCloud.connect(): %d", ret_code_connect); - if (ret_code_connect == CONNECT_SUCCESS) { - setIoTConnectionState(ArduinoIoTConnectionStatus::CONNECTED); - CloudSerial.begin(9600); - CloudSerial.println("Hello from Cloud Serial!"); - } - else if (ret_code_connect == CONNECT_FAILURE_SUBSCRIBE) { - debugMessage(DebugLevel::Info, "ERROR - Please verify your THING ID"); + int const ret_code_connect = connect(); + debugMessage(DebugLevel::Verbose, "ArduinoCloud.connect(): %d", ret_code_connect); + if (ret_code_connect == CONNECT_SUCCESS) { + setIoTConnectionState(ArduinoIoTConnectionStatus::CONNECTED); + CloudSerial.begin(9600); + CloudSerial.println("Hello from Cloud Serial!"); + } else if (ret_code_connect == CONNECT_FAILURE_SUBSCRIBE) { + debugMessage(DebugLevel::Info, "ERROR - Please verify your THING ID"); + } } - } - break; + break; } } -void ArduinoIoTCloudClass::setIoTConnectionState(ArduinoIoTConnectionStatus _newState) -{ - switch(_newState){ +void ArduinoIoTCloudClass::setIoTConnectionState(ArduinoIoTConnectionStatus _newState) { + switch (_newState) { case ArduinoIoTConnectionStatus::ERROR: debugMessage(DebugLevel::Error, "Arduino, we have a problem."); break; case ArduinoIoTConnectionStatus::CONNECTING: debugMessage(DebugLevel::Error, "Connecting to Arduino IoT Cloud..."); break; case ArduinoIoTConnectionStatus::RECONNECTING: debugMessage(DebugLevel::Error, "Reconnecting to Arduino IoT Cloud..."); break; @@ -445,8 +432,7 @@ void ArduinoIoTCloudClass::setIoTConnectionState(ArduinoIoTConnectionStatus _new iotStatus = _newState; } -void ArduinoIoTCloudClass::printDebugInfo() -{ +void ArduinoIoTCloudClass::printDebugInfo() { debugMessage(DebugLevel::Info, "***** Arduino IoT Cloud - configuration info *****"); debugMessage(DebugLevel::Info, "Device ID: %s", getDeviceId().c_str()); debugMessage(DebugLevel::Info, "Thing ID: %s", getThingId().c_str()); diff --git a/src/ArduinoIoTCloud.h b/src/ArduinoIoTCloud.h index a5c1df53c..49db37f03 100644 --- a/src/ArduinoIoTCloud.h +++ b/src/ArduinoIoTCloud.h @@ -1,19 +1,19 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef ARDUINO_IOT_CLOUD_H #define ARDUINO_IOT_CLOUD_H @@ -61,112 +61,128 @@ enum class ArduinoIoTSynchronizationStatus { class ArduinoIoTCloudClass { -public: - ArduinoIoTCloudClass(); - ~ArduinoIoTCloudClass(); + public: + ArduinoIoTCloudClass(); + ~ArduinoIoTCloudClass(); - int begin(ConnectionManager *connection = ArduinoIoTPreferredConnection, String brokerAddress = DEFAULT_BROKER_ADDRESS, uint16_t brokerPort = DEFAULT_BROKER_PORT); - int begin(Client& net, String brokerAddress = DEFAULT_BROKER_ADDRESS, uint16_t brokerPort = DEFAULT_BROKER_PORT); - // Class constant declaration - static const int MQTT_TRANSMIT_BUFFER_SIZE = 256; - static const int MAX_RETRIES = 5; - static const int RECONNECTION_TIMEOUT = 2000; - static const int TIMEOUT_FOR_LASTVALUES_SYNC = 10000; + int begin(ConnectionManager *connection = ArduinoIoTPreferredConnection, String brokerAddress = DEFAULT_BROKER_ADDRESS, uint16_t brokerPort = DEFAULT_BROKER_PORT); + int begin(Client& net, String brokerAddress = DEFAULT_BROKER_ADDRESS, uint16_t brokerPort = DEFAULT_BROKER_PORT); + // Class constant declaration + static const int MQTT_TRANSMIT_BUFFER_SIZE = 256; + static const int MAX_RETRIES = 5; + static const int RECONNECTION_TIMEOUT = 2000; + static const int TIMEOUT_FOR_LASTVALUES_SYNC = 10000; - void onGetTime(unsigned long(*callback)(void)); + void onGetTime(unsigned long(*callback)(void)); - int connect (); - bool disconnect(); + int connect(); + bool disconnect(); - void poll() __attribute__((deprecated)); /* Attention: Function is deprecated - use 'update' instead */ - void update(CallbackFunc onSyncCompleteCallback = NULL); + void poll() __attribute__((deprecated)); /* Attention: Function is deprecated - use 'update' instead */ + void update(CallbackFunc onSyncCompleteCallback = NULL); - // defined for users who want to specify max reconnections reties and timeout between them - void update(int const reconnectionMaxRetries, int const reconnectionTimeoutMs, CallbackFunc onSyncCompleteCallback = NULL); + // defined for users who want to specify max reconnections reties and timeout between them + void update(int const reconnectionMaxRetries, int const reconnectionTimeoutMs, CallbackFunc onSyncCompleteCallback = NULL); - int connected(); - // Clean up existing Mqtt connection, create a new one and initialize it - int reconnect(Client& /* net */); + int connected(); + // Clean up existing Mqtt connection, create a new one and initialize it + int reconnect(Client& /* net */); - inline void setThingId(String const thing_id) { _thing_id = thing_id; }; + inline void setThingId(String const thing_id) { + _thing_id = thing_id; + }; - inline String getThingId() const { return _thing_id; }; - inline String getDeviceId() const { return _device_id; }; + inline String getThingId() const { + return _thing_id; + }; + inline String getDeviceId() const { + return _device_id; + }; - #define addProperty( v, ...) addPropertyReal(v, #v, __VA_ARGS__) +#define addProperty( v, ...) addPropertyReal(v, #v, __VA_ARGS__) - static unsigned long const DEFAULT_MIN_TIME_BETWEEN_UPDATES_MILLIS = 500; /* Data rate throttled to 2 Hz */ + static unsigned long const DEFAULT_MIN_TIME_BETWEEN_UPDATES_MILLIS = 500; /* Data rate throttled to 2 Hz */ - template - void addPropertyReal(T & property, String name, permissionType permission_type = READWRITE, long seconds = ON_CHANGE, void(*fn)(void) = NULL, N minDelta = N(0), void(*synFn)(ArduinoCloudProperty property) = CLOUD_WINS) { - Permission permission = Permission::ReadWrite; - if (permission_type == READ ) permission = Permission::Read; - else if(permission_type == WRITE) permission = Permission::Write; - else permission = Permission::ReadWrite; + template + void addPropertyReal(T & property, String name, permissionType permission_type = READWRITE, long seconds = ON_CHANGE, void(*fn)(void) = NULL, N minDelta = N(0), void(*synFn)(ArduinoCloudProperty property) = CLOUD_WINS) { + Permission permission = Permission::ReadWrite; + if (permission_type == READ) { + permission = Permission::Read; + } else if (permission_type == WRITE) { + permission = Permission::Write; + } else { + permission = Permission::ReadWrite; + } + + if (seconds == ON_CHANGE) { + Thing.addPropertyReal(property, name, permission).publishOnChange((T)minDelta, DEFAULT_MIN_TIME_BETWEEN_UPDATES_MILLIS).onUpdate(fn).onSync(synFn); + } else { + Thing.addPropertyReal(property, name, permission).publishEvery(seconds).onUpdate(fn).onSync(synFn); + } + } - if(seconds == ON_CHANGE) { - Thing.addPropertyReal(property, name, permission).publishOnChange((T)minDelta, DEFAULT_MIN_TIME_BETWEEN_UPDATES_MILLIS).onUpdate(fn).onSync(synFn); - } else { - Thing.addPropertyReal(property, name, permission).publishEvery(seconds).onUpdate(fn).onSync(synFn); + template + ArduinoCloudProperty addPropertyReal(T & property, String const & name, Permission const permission) { + return Thing.addPropertyReal(property, name, permission); + } + + void connectionCheck(); + String getBrokerAddress() { + return _brokerAddress; + } + uint16_t getBrokerPort() { + return _brokerPort; + } + void printDebugInfo(); + + protected: + friend class CloudSerialClass; + int writeStdout(const byte data[], int length); + int writeProperties(const byte data[], int length); + int writeShadowOut(const byte data[], int length); + + // Used to initialize MQTTClient + void mqttClientBegin(); + // Function in charge of perform MQTT reconnection, basing on class parameters(retries,and timeout) + bool mqttReconnect(int const maxRetries, int const timeout); + // Used to retrieve last values from _shadowTopicIn + void requestLastValue(); + + ArduinoIoTConnectionStatus getIoTStatus() { + return iotStatus; } - } - - template - ArduinoCloudProperty addPropertyReal(T & property, String const & name, Permission const permission) { - return Thing.addPropertyReal(property, name, permission); - } - - void connectionCheck(); - String getBrokerAddress(){ return _brokerAddress; } - uint16_t getBrokerPort() { return _brokerPort; } - void printDebugInfo(); - -protected: - friend class CloudSerialClass; - int writeStdout(const byte data[], int length); - int writeProperties(const byte data[], int length); - int writeShadowOut(const byte data[], int length); - - // Used to initialize MQTTClient - void mqttClientBegin(); - // Function in charge of perform MQTT reconnection, basing on class parameters(retries,and timeout) - bool mqttReconnect(int const maxRetries, int const timeout); - // Used to retrieve last values from _shadowTopicIn - void requestLastValue(); - - ArduinoIoTConnectionStatus getIoTStatus() { return iotStatus; } - void setIoTConnectionState(ArduinoIoTConnectionStatus _newState); -private: - ArduinoIoTConnectionStatus iotStatus = ArduinoIoTConnectionStatus::IDLE; - ConnectionManager *connection; - static void onMessage(int length); - void handleMessage(int length); - ArduinoIoTSynchronizationStatus _syncStatus = ArduinoIoTSynchronizationStatus::SYNC_STATUS_SYNCHRONIZED; - - void sendPropertiesToCloud(); - - - String _device_id, - _thing_id, - _brokerAddress; - uint16_t _brokerPort; - ArduinoCloudThing Thing; - BearSSLClient* _bearSslClient; - MqttClient* _mqttClient; - int _lastSyncRequestTickTime; - - - // Class attribute to define MTTQ topics 2 for stdIn/out and 2 for data, in order to avoid getting previous pupblished payload - String _stdinTopic; - String _stdoutTopic; - String _shadowTopicOut; - String _shadowTopicIn; - String _dataTopicOut; - String _dataTopicIn; - String _otaTopic; - Client *_net; + void setIoTConnectionState(ArduinoIoTConnectionStatus _newState); + private: + ArduinoIoTConnectionStatus iotStatus = ArduinoIoTConnectionStatus::IDLE; + ConnectionManager *connection; + static void onMessage(int length); + void handleMessage(int length); + ArduinoIoTSynchronizationStatus _syncStatus = ArduinoIoTSynchronizationStatus::SYNC_STATUS_SYNCHRONIZED; + + void sendPropertiesToCloud(); + + + String _device_id, + _thing_id, + _brokerAddress; + uint16_t _brokerPort; + ArduinoCloudThing Thing; + BearSSLClient* _bearSslClient; + MqttClient* _mqttClient; + int _lastSyncRequestTickTime; + + + // Class attribute to define MTTQ topics 2 for stdIn/out and 2 for data, in order to avoid getting previous pupblished payload + String _stdinTopic; + String _stdoutTopic; + String _shadowTopicOut; + String _shadowTopicIn; + String _dataTopicOut; + String _dataTopicIn; + String _otaTopic; + Client *_net; }; extern ArduinoIoTCloudClass ArduinoCloud; diff --git a/src/CloudSerial.cpp b/src/CloudSerial.cpp index e4e3a16a8..19f380a76 100644 --- a/src/CloudSerial.cpp +++ b/src/CloudSerial.cpp @@ -1,67 +1,58 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #include "ArduinoIoTCloud.h" #include "CloudSerial.h" -CloudSerialClass::CloudSerialClass() -{ +CloudSerialClass::CloudSerialClass() { } -CloudSerialClass::~CloudSerialClass() -{ +CloudSerialClass::~CloudSerialClass() { } -void CloudSerialClass::begin(int /*baud*/) -{ +void CloudSerialClass::begin(int /*baud*/) { _txBuffer.clear(); _rxBuffer.clear(); } -void CloudSerialClass::end() -{ +void CloudSerialClass::end() { } -int CloudSerialClass::available() -{ +int CloudSerialClass::available() { return _rxBuffer.available(); } -int CloudSerialClass::availableForWrite() -{ +int CloudSerialClass::availableForWrite() { return _txBuffer.availableForStore(); } -int CloudSerialClass::peek() -{ +int CloudSerialClass::peek() { return _rxBuffer.peek(); } -int CloudSerialClass::read() -{ +int CloudSerialClass::read() { return _rxBuffer.read_char(); } -void CloudSerialClass::flush() -{ +void CloudSerialClass::flush() { byte out[CLOUD_SERIAL_TX_BUFFER_SIZE]; int length = 0; @@ -73,8 +64,7 @@ void CloudSerialClass::flush() ArduinoCloud.writeStdout(out, length); } -size_t CloudSerialClass::write(const uint8_t data) -{ +size_t CloudSerialClass::write(const uint8_t data) { _txBuffer.store_char(data); if (_txBuffer.isFull() || data == '\n') { @@ -84,14 +74,12 @@ size_t CloudSerialClass::write(const uint8_t data) return 1; } -CloudSerialClass::operator bool() -{ +CloudSerialClass::operator bool() { return ArduinoCloud.connected(); } -void CloudSerialClass::appendStdin(const uint8_t *buffer, size_t size) -{ +void CloudSerialClass::appendStdin(const uint8_t *buffer, size_t size) { while (!_rxBuffer.isFull() && size--) { _rxBuffer.store_char(*buffer++); } diff --git a/src/CloudSerial.h b/src/CloudSerial.h index 462b575c5..3fbe78e06 100644 --- a/src/CloudSerial.h +++ b/src/CloudSerial.h @@ -1,19 +1,19 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef CLOUD_SERIAL_H #define CLOUD_SERIAL_H @@ -26,32 +26,31 @@ class ArduinoIoTCloudClass; -class CloudSerialClass : public Stream -{ -public: - CloudSerialClass(); - ~CloudSerialClass(); +class CloudSerialClass : public Stream { + public: + CloudSerialClass(); + ~CloudSerialClass(); - void begin(int baud); - void end(); - int available(); - int availableForWrite(); - int peek(); - int read(); - void flush(); - size_t write(const uint8_t data); - using Print::write; // pull in write(str) and write(buf, size) from Print + void begin(int baud); + void end(); + int available(); + int availableForWrite(); + int peek(); + int read(); + void flush(); + size_t write(const uint8_t data); + using Print::write; // pull in write(str) and write(buf, size) from Print - operator bool(); + operator bool(); -protected: - friend class ArduinoIoTCloudClass; + protected: + friend class ArduinoIoTCloudClass; - void appendStdin(const uint8_t *buffer, size_t size); + void appendStdin(const uint8_t *buffer, size_t size); -private: - RingBufferN _txBuffer; - RingBufferN _rxBuffer; + private: + RingBufferN _txBuffer; + RingBufferN _rxBuffer; }; extern CloudSerialClass CloudSerial; diff --git a/src/ConnectionManager.h b/src/ConnectionManager.h index 8f6e329af..c82b42804 100644 --- a/src/ConnectionManager.h +++ b/src/ConnectionManager.h @@ -1,25 +1,25 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef CONNECTION_MANAGER_H_ #define CONNECTION_MANAGER_H_ /****************************************************************************** - * INCLUDES + INCLUDES ******************************************************************************/ #include @@ -29,7 +29,7 @@ #include "utility/DebugUtils.h" /****************************************************************************** - * TYPEDEFS + TYPEDEFS ******************************************************************************/ enum class NetworkConnectionState { @@ -43,49 +43,51 @@ enum class NetworkConnectionState { }; /****************************************************************************** - * CLASS DECLARATION + CLASS DECLARATION ******************************************************************************/ class ConnectionManager { -public: - virtual void init() = 0; - virtual void check() = 0; - virtual unsigned long getTime() = 0; - virtual Client &getClient(); - virtual UDP &getUDP(); + public: + virtual void init() = 0; + virtual void check() = 0; + virtual unsigned long getTime() = 0; + virtual Client &getClient(); + virtual UDP &getUDP(); - virtual NetworkConnectionState getStatus() { return netConnectionState; } + virtual NetworkConnectionState getStatus() { + return netConnectionState; + } -protected: - unsigned long lastValidTimestamp = 0; - NetworkConnectionState netConnectionState = NetworkConnectionState::INIT; + protected: + unsigned long lastValidTimestamp = 0; + NetworkConnectionState netConnectionState = NetworkConnectionState::INIT; }; #ifdef ARDUINO_SAMD_MKR1000 -#include -#define BOARD_HAS_WIFI -#define NETWORK_HARDWARE_ERROR WL_NO_SHIELD -#define NETWORK_IDLE_STATUS WL_IDLE_STATUS -#define NETWORK_CONNECTED WL_CONNECTED -#define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_REQUIRED + #include + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED + #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_REQUIRED #endif #ifdef ARDUINO_SAMD_MKRWIFI1010 -#include -#define BOARD_HAS_WIFI -#define NETWORK_HARDWARE_ERROR WL_NO_MODULE -#define NETWORK_IDLE_STATUS WL_IDLE_STATUS -#define NETWORK_CONNECTED WL_CONNECTED -#define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_LATEST_VERSION + #include + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_MODULE + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED + #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_LATEST_VERSION #endif #ifdef ARDUINO_SAMD_MKRGSM1400 -#include -#define BOARD_HAS_GSM -#define NETWORK_HARDWARE_ERROR GPRS_PING_ERROR -#define NETWORK_IDLE_STATUS GSM3_NetworkStatus_t::IDLE -#define NETWORK_CONNECTED GSM3_NetworkStatus_t::GPRS_READY + #include + #define BOARD_HAS_GSM + #define NETWORK_HARDWARE_ERROR GPRS_PING_ERROR + #define NETWORK_IDLE_STATUS GSM3_NetworkStatus_t::IDLE + #define NETWORK_CONNECTED GSM3_NetworkStatus_t::GPRS_READY #endif #endif /* CONNECTION_MANAGER_H_ */ diff --git a/src/EthernetConnectionManager.cpp b/src/EthernetConnectionManager.cpp index 954217132..7c7f50050 100644 --- a/src/EthernetConnectionManager.cpp +++ b/src/EthernetConnectionManager.cpp @@ -1,22 +1,22 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include "EthernetConnectionManager.h" @@ -24,13 +24,13 @@ #ifdef BOARD_HAS_ETHERNET /* Only compile if the board has ethernet */ /****************************************************************************** - * CONSTANTS + CONSTANTS ******************************************************************************/ static const unsigned long NETWORK_CONNECTION_INTERVAL = 30000; /****************************************************************************** - * CTOR + CTOR ******************************************************************************/ EthConnectionManager::EthConnectionManager(uint8_t * mac, int const ss_pin) : @@ -41,7 +41,7 @@ EthConnectionManager::EthConnectionManager(uint8_t * mac, int const ss_pin) : } /****************************************************************************** - * PUBLIC MEMBER FUNCTIONS + PUBLIC MEMBER FUNCTIONS ******************************************************************************/ void EthConnectionManager::init() { @@ -58,90 +58,90 @@ void EthConnectionManager::check() { if (now - lastConnectionTickTime > connectionTickTimeInterval) { switch (netConnectionState) { case NetworkConnectionState::INIT: { - if (ss_pin == -1) { - networkStatus = Ethernet.begin(mac); - } else { - networkStatus = Ethernet.begin(mac, ss_pin); - } - networkStatus = Ethernet.hardwareStatus(); - debugMessage(DebugLevel::Info, "Eth hardware status(): %d", networkStatus); - if (networkStatus == EthernetNoHardware) { - debugMessage(DebugLevel::Error, "No Ethernet chip connected"); - // don't continue: - changeConnectionState(NetworkConnectionState::ERROR); - lastConnectionTickTime = now; - return; + if (ss_pin == -1) { + networkStatus = Ethernet.begin(mac); + } else { + networkStatus = Ethernet.begin(mac, ss_pin); + } + networkStatus = Ethernet.hardwareStatus(); + debugMessage(DebugLevel::Info, "Eth hardware status(): %d", networkStatus); + if (networkStatus == EthernetNoHardware) { + debugMessage(DebugLevel::Error, "No Ethernet chip connected"); + // don't continue: + changeConnectionState(NetworkConnectionState::ERROR); + lastConnectionTickTime = now; + return; + } + networkStatus = Ethernet.linkStatus(); + debugMessage(DebugLevel::Info, "Eth link status(): %d", networkStatus); + if (networkStatus == LinkOFF) { + debugMessage(DebugLevel::Error, "Failed to configure Ethernet via dhcp"); + // don't continue: + changeConnectionState(NetworkConnectionState::ERROR); + lastConnectionTickTime = now; + return; + } + debugMessage(DebugLevel::Error, "Ethernet shield recognized: ID", Ethernet.hardwareStatus()); + changeConnectionState(NetworkConnectionState::CONNECTING); } - networkStatus = Ethernet.linkStatus(); - debugMessage(DebugLevel::Info, "Eth link status(): %d", networkStatus); - if (networkStatus == LinkOFF) { - debugMessage(DebugLevel::Error, "Failed to configure Ethernet via dhcp"); - // don't continue: - changeConnectionState(NetworkConnectionState::ERROR); - lastConnectionTickTime = now; - return; - } - debugMessage(DebugLevel::Error, "Ethernet shield recognized: ID", Ethernet.hardwareStatus()); - changeConnectionState(NetworkConnectionState::CONNECTING); - } - break; + break; case NetworkConnectionState::CONNECTING: { - debugMessage(DebugLevel::Info, "Connecting via dhcp"); - if (ss_pin == -1) { - networkStatus = Ethernet.begin(mac); - } else { - networkStatus = Ethernet.begin(mac, ss_pin); - } - debugMessage(DebugLevel::Info, "Ethernet.status(): %d", networkStatus); - if (networkStatus == 0) { - debugMessage(DebugLevel::Error, "Connection failed"); - debugMessage(DebugLevel::Info, "Retrying in \"%d\" milliseconds", connectionTickTimeInterval); - //changeConnectionState(NetworkConnectionState::CONNECTING); - return; - } else { - debugMessage(DebugLevel::Info, "Connected!"); - changeConnectionState(NetworkConnectionState::GETTIME); - return; + debugMessage(DebugLevel::Info, "Connecting via dhcp"); + if (ss_pin == -1) { + networkStatus = Ethernet.begin(mac); + } else { + networkStatus = Ethernet.begin(mac, ss_pin); + } + debugMessage(DebugLevel::Info, "Ethernet.status(): %d", networkStatus); + if (networkStatus == 0) { + debugMessage(DebugLevel::Error, "Connection failed"); + debugMessage(DebugLevel::Info, "Retrying in \"%d\" milliseconds", connectionTickTimeInterval); + //changeConnectionState(NetworkConnectionState::CONNECTING); + return; + } else { + debugMessage(DebugLevel::Info, "Connected!"); + changeConnectionState(NetworkConnectionState::GETTIME); + return; + } } - } - break; + break; case NetworkConnectionState::GETTIME: { - debugMessage(DebugLevel::Debug, "Acquiring Time from Network"); - unsigned long networkTime; - networkTime = getTime(); - debugMessage(DebugLevel::Debug, "Network Time: %u", networkTime); - if(networkTime > lastValidTimestamp){ - lastValidTimestamp = networkTime; - changeConnectionState(NetworkConnectionState::CONNECTED); + debugMessage(DebugLevel::Debug, "Acquiring Time from Network"); + unsigned long networkTime; + networkTime = getTime(); + debugMessage(DebugLevel::Debug, "Network Time: %u", networkTime); + if (networkTime > lastValidTimestamp) { + lastValidTimestamp = networkTime; + changeConnectionState(NetworkConnectionState::CONNECTED); + } } - } - break; + break; case NetworkConnectionState::CONNECTED: { - // keep testing connection - Ethernet.maintain(); - networkStatus = Ethernet.linkStatus(); - debugMessage(DebugLevel::Verbose, "Eth link status(): %d", networkStatus); - if (networkStatus != LinkON) { - changeConnectionState(NetworkConnectionState::DISCONNECTED); - return; + // keep testing connection + Ethernet.maintain(); + networkStatus = Ethernet.linkStatus(); + debugMessage(DebugLevel::Verbose, "Eth link status(): %d", networkStatus); + if (networkStatus != LinkON) { + changeConnectionState(NetworkConnectionState::DISCONNECTED); + return; + } + debugMessage(DebugLevel::Info, "Connected"); } - debugMessage(DebugLevel::Info, "Connected"); - } - break; + break; case NetworkConnectionState::DISCONNECTED: { - debugMessage(DebugLevel::Error, "Connection lost."); - debugMessage(DebugLevel::Info, "Attempting reconnection"); - changeConnectionState(NetworkConnectionState::CONNECTING); - //wifiClient.stop(); - } - break; + debugMessage(DebugLevel::Error, "Connection lost."); + debugMessage(DebugLevel::Info, "Attempting reconnection"); + changeConnectionState(NetworkConnectionState::CONNECTING); + //wifiClient.stop(); + } + break; } lastConnectionTickTime = now; } } /****************************************************************************** - * PRIVATE MEMBER FUNCTIONS + PRIVATE MEMBER FUNCTIONS ******************************************************************************/ void EthConnectionManager::changeConnectionState(NetworkConnectionState _newState) { diff --git a/src/EthernetConnectionManager.h b/src/EthernetConnectionManager.h index 9aeb72175..4feecb2c2 100644 --- a/src/EthernetConnectionManager.h +++ b/src/EthernetConnectionManager.h @@ -1,25 +1,25 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef ETHERNET_CONNECTION_MANAGER_H_ #define ETHERNET_CONNECTION_MANAGER_H_ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include "ConnectionManager.h" @@ -30,38 +30,42 @@ #include /****************************************************************************** - * CLASS DECLARATION + CLASS DECLARATION ******************************************************************************/ class EthConnectionManager : public ConnectionManager { -public: - EthConnectionManager(uint8_t * mac, int const ss_pin = -1); - - virtual void init(); - virtual unsigned long getTime(); - virtual void check(); - virtual Client &getClient() { return ethClient; }; - virtual UDP &getUDP() { return udp; }; - -private: - - void changeConnectionState(NetworkConnectionState _newState); - - const int CHECK_INTERVAL_IDLE = 100; - const int CHECK_INTERVAL_INIT = 100; - const int CHECK_INTERVAL_CONNECTING = 500; - const int CHECK_INTERVAL_GETTIME = 100; - const int CHECK_INTERVAL_CONNECTED = 10000; - const int CHECK_INTERVAL_RETRYING = 5000; - const int CHECK_INTERVAL_DISCONNECTED = 1000; - const int CHECK_INTERVAL_ERROR = 500; - - unsigned long lastConnectionTickTime, lastNetworkStep; - uint8_t* mac; - int ss_pin; - EthernetClient ethClient; - EthernetUDP udp; - int connectionTickTimeInterval; + public: + EthConnectionManager(uint8_t * mac, int const ss_pin = -1); + + virtual void init(); + virtual unsigned long getTime(); + virtual void check(); + virtual Client &getClient() { + return ethClient; + }; + virtual UDP &getUDP() { + return udp; + }; + + private: + + void changeConnectionState(NetworkConnectionState _newState); + + const int CHECK_INTERVAL_IDLE = 100; + const int CHECK_INTERVAL_INIT = 100; + const int CHECK_INTERVAL_CONNECTING = 500; + const int CHECK_INTERVAL_GETTIME = 100; + const int CHECK_INTERVAL_CONNECTED = 10000; + const int CHECK_INTERVAL_RETRYING = 5000; + const int CHECK_INTERVAL_DISCONNECTED = 1000; + const int CHECK_INTERVAL_ERROR = 500; + + unsigned long lastConnectionTickTime, lastNetworkStep; + uint8_t* mac; + int ss_pin; + EthernetClient ethClient; + EthernetUDP udp; + int connectionTickTimeInterval; }; #endif /* #ifdef BOARD_HAS_ETHERNET */ diff --git a/src/GSMConnectionManager.cpp b/src/GSMConnectionManager.cpp index 3b2b44335..1cca7e0a5 100644 --- a/src/GSMConnectionManager.cpp +++ b/src/GSMConnectionManager.cpp @@ -1,22 +1,22 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include "GSMConnectionManager.h" @@ -24,13 +24,13 @@ #ifdef BOARD_HAS_GSM /* Only compile if this is a board with GSM */ /****************************************************************************** - * CONSTANTS + CONSTANTS ******************************************************************************/ static const unsigned long NETWORK_CONNECTION_INTERVAL = 30000; /****************************************************************************** - * CTOR/DTOR + CTOR/DTOR ******************************************************************************/ GSMConnectionManager::GSMConnectionManager(const char *pin, const char *apn, const char *login, const char *pass) : @@ -43,7 +43,7 @@ GSMConnectionManager::GSMConnectionManager(const char *pin, const char *apn, con } /****************************************************************************** - * PUBLIC MEMBER FUNCTIONS + PUBLIC MEMBER FUNCTIONS ******************************************************************************/ void GSMConnectionManager::init() { @@ -54,7 +54,7 @@ void GSMConnectionManager::init() { changeConnectionState(NetworkConnectionState::CONNECTING); } else { debugMessage(DebugLevel::Error, "SIM not present or wrong PIN"); - while(1); + while (1); } } @@ -68,86 +68,86 @@ void GSMConnectionManager::check() { if (now - lastConnectionTickTime > connectionTickTimeInterval) { switch (netConnectionState) { case NetworkConnectionState::INIT: { - init(); - } - break; - case NetworkConnectionState::CONNECTING: { - // NOTE: Blocking Call when 4th parameter == true - GSM3_NetworkStatus_t networkStatus; - networkStatus = gprs.attachGPRS(apn, login, pass, true); - debugMessage(DebugLevel::Debug, "GPRS.attachGPRS(): %d", networkStatus); - if (networkStatus == GSM3_NetworkStatus_t::ERROR) { - // NO FURTHER ACTION WILL FOLLOW THIS - changeConnectionState(NetworkConnectionState::ERROR); - return; + init(); } - debugMessage(DebugLevel::Info, "Sending PING to outer space..."); - int pingResult; - pingResult = gprs.ping("time.arduino.cc"); - debugMessage(DebugLevel::Info, "GSM.ping(): %d", pingResult); - if (pingResult < 0) { - debugMessage(DebugLevel::Error, "PING failed"); - debugMessage(DebugLevel::Info, "Retrying in \"%d\" milliseconds", connectionTickTimeInterval); - return; - } else { - debugMessage(DebugLevel::Info, "Connected to GPRS Network"); - changeConnectionState(NetworkConnectionState::CONNECTED); - return; + break; + case NetworkConnectionState::CONNECTING: { + // NOTE: Blocking Call when 4th parameter == true + GSM3_NetworkStatus_t networkStatus; + networkStatus = gprs.attachGPRS(apn, login, pass, true); + debugMessage(DebugLevel::Debug, "GPRS.attachGPRS(): %d", networkStatus); + if (networkStatus == GSM3_NetworkStatus_t::ERROR) { + // NO FURTHER ACTION WILL FOLLOW THIS + changeConnectionState(NetworkConnectionState::ERROR); + return; + } + debugMessage(DebugLevel::Info, "Sending PING to outer space..."); + int pingResult; + pingResult = gprs.ping("time.arduino.cc"); + debugMessage(DebugLevel::Info, "GSM.ping(): %d", pingResult); + if (pingResult < 0) { + debugMessage(DebugLevel::Error, "PING failed"); + debugMessage(DebugLevel::Info, "Retrying in \"%d\" milliseconds", connectionTickTimeInterval); + return; + } else { + debugMessage(DebugLevel::Info, "Connected to GPRS Network"); + changeConnectionState(NetworkConnectionState::CONNECTED); + return; + } } - } - break; + break; case NetworkConnectionState::CONNECTED: { - gsmAccessAlive = gsmAccess.isAccessAlive(); - debugMessage(DebugLevel::Verbose, "GPRS.isAccessAlive(): %d", gsmAccessAlive); - if (gsmAccessAlive != 1) { - changeConnectionState(NetworkConnectionState::DISCONNECTED); - return; + gsmAccessAlive = gsmAccess.isAccessAlive(); + debugMessage(DebugLevel::Verbose, "GPRS.isAccessAlive(): %d", gsmAccessAlive); + if (gsmAccessAlive != 1) { + changeConnectionState(NetworkConnectionState::DISCONNECTED); + return; + } + debugMessage(DebugLevel::Verbose, "Connected to Cellular Network"); } - debugMessage(DebugLevel::Verbose, "Connected to Cellular Network"); - } - break; + break; case NetworkConnectionState::DISCONNECTED: { - gprs.detachGPRS(); - changeConnectionState(NetworkConnectionState::CONNECTING); - } - break; + gprs.detachGPRS(); + changeConnectionState(NetworkConnectionState::CONNECTING); + } + break; } lastConnectionTickTime = now; } } /****************************************************************************** - * PRIVATE MEMBER FUNCTIONS + PRIVATE MEMBER FUNCTIONS ******************************************************************************/ void GSMConnectionManager::changeConnectionState(NetworkConnectionState _newState) { int newInterval = CHECK_INTERVAL_IDLE; switch (_newState) { case NetworkConnectionState::INIT: { - newInterval = CHECK_INTERVAL_INIT; - } - break; + newInterval = CHECK_INTERVAL_INIT; + } + break; case NetworkConnectionState::CONNECTING: { - debugMessage(DebugLevel::Info, "Connecting to Cellular Network"); - newInterval = CHECK_INTERVAL_CONNECTING; - } - break; + debugMessage(DebugLevel::Info, "Connecting to Cellular Network"); + newInterval = CHECK_INTERVAL_CONNECTING; + } + break; case NetworkConnectionState::CONNECTED: { - newInterval = CHECK_INTERVAL_CONNECTED; - } - break; + newInterval = CHECK_INTERVAL_CONNECTED; + } + break; case NetworkConnectionState::DISCONNECTED: { - if(netConnectionState == NetworkConnectionState::CONNECTED){ - debugMessage(DebugLevel::Error, "Disconnected from Cellular Network"); - debugMessage(DebugLevel::Error, "Attempting reconnection"); + if (netConnectionState == NetworkConnectionState::CONNECTED) { + debugMessage(DebugLevel::Error, "Disconnected from Cellular Network"); + debugMessage(DebugLevel::Error, "Attempting reconnection"); + } + newInterval = CHECK_INTERVAL_DISCONNECTED; } - newInterval = CHECK_INTERVAL_DISCONNECTED; - } - break; + break; case NetworkConnectionState::ERROR: { - debugMessage(DebugLevel::Error, "GPRS attach failed\n\rMake sure the antenna is connected and reset your board."); - } - break; + debugMessage(DebugLevel::Error, "GPRS attach failed\n\rMake sure the antenna is connected and reset your board."); + } + break; } connectionTickTimeInterval = newInterval; lastConnectionTickTime = millis(); diff --git a/src/GSMConnectionManager.h b/src/GSMConnectionManager.h index 963d30f1f..4da8a6487 100644 --- a/src/GSMConnectionManager.h +++ b/src/GSMConnectionManager.h @@ -1,25 +1,25 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef GSM_CONNECTION_MANAGER_H_ #define GSM_CONNECTION_MANAGER_H_ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include "ConnectionManager.h" @@ -27,39 +27,43 @@ #ifdef BOARD_HAS_GSM /* Only compile if this is a board with GSM */ /****************************************************************************** - * CLASS DECLARATION + CLASS DECLARATION ******************************************************************************/ class GSMConnectionManager : public ConnectionManager { -public: - GSMConnectionManager(const char *pin, const char *apn, const char *login, const char *pass); - - virtual void init(); - virtual unsigned long getTime(); - virtual void check(); - virtual Client &getClient() { return networkClient; }; - virtual UDP &getUDP() { return udp; }; - - GSMClient networkClient; - GSM gsmAccess; - GPRS gprs; - GSMUDP udp; - -private: - - void changeConnectionState(NetworkConnectionState _newState); - - const int CHECK_INTERVAL_IDLE = 100; - const int CHECK_INTERVAL_INIT = 100; - const int CHECK_INTERVAL_CONNECTING = 500; - const int CHECK_INTERVAL_CONNECTED = 10000; - const int CHECK_INTERVAL_RETRYING = 5000; - const int CHECK_INTERVAL_DISCONNECTED = 1000; - const int CHECK_INTERVAL_ERROR = 500; - - const char *pin, *apn, *login, *pass; - unsigned long lastConnectionTickTime; - int connectionTickTimeInterval; + public: + GSMConnectionManager(const char *pin, const char *apn, const char *login, const char *pass); + + virtual void init(); + virtual unsigned long getTime(); + virtual void check(); + virtual Client &getClient() { + return networkClient; + }; + virtual UDP &getUDP() { + return udp; + }; + + GSMClient networkClient; + GSM gsmAccess; + GPRS gprs; + GSMUDP udp; + + private: + + void changeConnectionState(NetworkConnectionState _newState); + + const int CHECK_INTERVAL_IDLE = 100; + const int CHECK_INTERVAL_INIT = 100; + const int CHECK_INTERVAL_CONNECTING = 500; + const int CHECK_INTERVAL_CONNECTED = 10000; + const int CHECK_INTERVAL_RETRYING = 5000; + const int CHECK_INTERVAL_DISCONNECTED = 1000; + const int CHECK_INTERVAL_ERROR = 500; + + const char *pin, *apn, *login, *pass; + unsigned long lastConnectionTickTime; + int connectionTickTimeInterval; }; diff --git a/src/WiFiConnectionManager.cpp b/src/WiFiConnectionManager.cpp index ad1d2bb6e..e0c869160 100644 --- a/src/WiFiConnectionManager.cpp +++ b/src/WiFiConnectionManager.cpp @@ -1,22 +1,22 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include "WiFiConnectionManager.h" @@ -24,13 +24,13 @@ #ifdef BOARD_HAS_WIFI /* Only compile if the board has WiFi */ /****************************************************************************** - * CONSTANTS + CONSTANTS ******************************************************************************/ static const unsigned long NETWORK_CONNECTION_INTERVAL = 30000; /****************************************************************************** - * CTOR/DTOR + CTOR/DTOR ******************************************************************************/ WiFiConnectionManager::WiFiConnectionManager(const char *ssid, const char *pass) : @@ -41,7 +41,7 @@ WiFiConnectionManager::WiFiConnectionManager(const char *ssid, const char *pass) } /****************************************************************************** - * PUBLIC MEMBER FUNCTIONS + PUBLIC MEMBER FUNCTIONS ******************************************************************************/ void WiFiConnectionManager::init() { @@ -57,91 +57,91 @@ void WiFiConnectionManager::check() { if (now - lastConnectionTickTime > connectionTickTimeInterval) { switch (netConnectionState) { case NetworkConnectionState::INIT: { - networkStatus = WiFi.status(); - debugMessage(DebugLevel::Info, "WiFi.status(): %d", networkStatus); - if (networkStatus == NETWORK_HARDWARE_ERROR) { - // NO FURTHER ACTION WILL FOLLOW THIS - changeConnectionState(NetworkConnectionState::ERROR); - lastConnectionTickTime = now; - return; - } - debugMessage(DebugLevel::Error, "Current WiFi Firmware: %s", WiFi.firmwareVersion()); - if(WiFi.firmwareVersion() < WIFI_FIRMWARE_VERSION_REQUIRED){ - debugMessage(DebugLevel::Error, "Latest WiFi Firmware: %s", WIFI_FIRMWARE_VERSION_REQUIRED); - debugMessage(DebugLevel::Error, "Please update to the latest version for best performance."); - delay(5000); + networkStatus = WiFi.status(); + debugMessage(DebugLevel::Info, "WiFi.status(): %d", networkStatus); + if (networkStatus == NETWORK_HARDWARE_ERROR) { + // NO FURTHER ACTION WILL FOLLOW THIS + changeConnectionState(NetworkConnectionState::ERROR); + lastConnectionTickTime = now; + return; + } + debugMessage(DebugLevel::Error, "Current WiFi Firmware: %s", WiFi.firmwareVersion()); + if (WiFi.firmwareVersion() < WIFI_FIRMWARE_VERSION_REQUIRED) { + debugMessage(DebugLevel::Error, "Latest WiFi Firmware: %s", WIFI_FIRMWARE_VERSION_REQUIRED); + debugMessage(DebugLevel::Error, "Please update to the latest version for best performance."); + delay(5000); + } + changeConnectionState(NetworkConnectionState::CONNECTING); } - changeConnectionState(NetworkConnectionState::CONNECTING); - } - break; + break; case NetworkConnectionState::CONNECTING: { - networkStatus = WiFi.begin(ssid, pass); - debugMessage(DebugLevel::Verbose, "WiFi.status(): %d", networkStatus); - if (networkStatus != NETWORK_CONNECTED) { - debugMessage(DebugLevel::Error, "Connection to \"%s\" failed", ssid); - debugMessage(DebugLevel::Info, "Retrying in \"%d\" milliseconds", connectionTickTimeInterval); - //changeConnectionState(NetworkConnectionState::CONNECTING); - return; - } else { - debugMessage(DebugLevel::Info, "Connected to \"%s\"", ssid); - changeConnectionState(NetworkConnectionState::CONNECTED); - return; + networkStatus = WiFi.begin(ssid, pass); + debugMessage(DebugLevel::Verbose, "WiFi.status(): %d", networkStatus); + if (networkStatus != NETWORK_CONNECTED) { + debugMessage(DebugLevel::Error, "Connection to \"%s\" failed", ssid); + debugMessage(DebugLevel::Info, "Retrying in \"%d\" milliseconds", connectionTickTimeInterval); + //changeConnectionState(NetworkConnectionState::CONNECTING); + return; + } else { + debugMessage(DebugLevel::Info, "Connected to \"%s\"", ssid); + changeConnectionState(NetworkConnectionState::CONNECTED); + return; + } } - } - break; + break; case NetworkConnectionState::CONNECTED: { - // keep testing connection - networkStatus = WiFi.status(); - debugMessage(DebugLevel::Verbose, "WiFi.status(): %d", networkStatus); - if (networkStatus != WL_CONNECTED) { - changeConnectionState(NetworkConnectionState::DISCONNECTED); - return; + // keep testing connection + networkStatus = WiFi.status(); + debugMessage(DebugLevel::Verbose, "WiFi.status(): %d", networkStatus); + if (networkStatus != WL_CONNECTED) { + changeConnectionState(NetworkConnectionState::DISCONNECTED); + return; + } + debugMessage(DebugLevel::Verbose, "Connected to \"%s\"", ssid); } - debugMessage(DebugLevel::Verbose, "Connected to \"%s\"", ssid); - } - break; + break; case NetworkConnectionState::DISCONNECTED: { - WiFi.end(); - changeConnectionState(NetworkConnectionState::CONNECTING); - } - break; + WiFi.end(); + changeConnectionState(NetworkConnectionState::CONNECTING); + } + break; } lastConnectionTickTime = now; } } /****************************************************************************** - * PRIVATE MEMBER FUNCTIONS + PRIVATE MEMBER FUNCTIONS ******************************************************************************/ void WiFiConnectionManager::changeConnectionState(NetworkConnectionState _newState) { int newInterval = CHECK_INTERVAL_INIT; switch (_newState) { case NetworkConnectionState::INIT: { - newInterval = CHECK_INTERVAL_INIT; - } - break; + newInterval = CHECK_INTERVAL_INIT; + } + break; case NetworkConnectionState::CONNECTING: { - debugMessage(DebugLevel::Info, "Connecting to \"%s\"", ssid); - newInterval = CHECK_INTERVAL_CONNECTING; - } - break; + debugMessage(DebugLevel::Info, "Connecting to \"%s\"", ssid); + newInterval = CHECK_INTERVAL_CONNECTING; + } + break; case NetworkConnectionState::CONNECTED: { - newInterval = CHECK_INTERVAL_CONNECTED; - } - break; + newInterval = CHECK_INTERVAL_CONNECTED; + } + break; case NetworkConnectionState::DISCONNECTED: { - debugMessage(DebugLevel::Verbose, "WiFi.status(): %d", WiFi.status()); - debugMessage(DebugLevel::Error, "Connection to \"%s\" lost.", ssid); - debugMessage(DebugLevel::Error, "Attempting reconnection"); - newInterval = CHECK_INTERVAL_DISCONNECTED; - } - break; + debugMessage(DebugLevel::Verbose, "WiFi.status(): %d", WiFi.status()); + debugMessage(DebugLevel::Error, "Connection to \"%s\" lost.", ssid); + debugMessage(DebugLevel::Error, "Attempting reconnection"); + newInterval = CHECK_INTERVAL_DISCONNECTED; + } + break; case NetworkConnectionState::ERROR: { - debugMessage(DebugLevel::Error, "WiFi Hardware failure.\nMake sure you are using a WiFi enabled board/shield."); - debugMessage(DebugLevel::Error, "Then reset and retry."); - } - break; + debugMessage(DebugLevel::Error, "WiFi Hardware failure.\nMake sure you are using a WiFi enabled board/shield."); + debugMessage(DebugLevel::Error, "Then reset and retry."); + } + break; } connectionTickTimeInterval = newInterval; lastConnectionTickTime = millis(); diff --git a/src/WiFiConnectionManager.h b/src/WiFiConnectionManager.h index a6f815baa..8ee843680 100644 --- a/src/WiFiConnectionManager.h +++ b/src/WiFiConnectionManager.h @@ -1,25 +1,25 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef WIFI_CONNECTION_MANAGER_H_ #define WIFI_CONNECTION_MANAGER_H_ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include "ConnectionManager.h" @@ -29,38 +29,42 @@ #include /****************************************************************************** - * CLASS DECLARATION + CLASS DECLARATION ******************************************************************************/ class WiFiConnectionManager : public ConnectionManager { -public: - WiFiConnectionManager(const char *ssid, const char *pass); - - virtual void init(); - virtual unsigned long getTime(); - virtual void check(); - virtual Client &getClient() { return wifiClient; }; - virtual UDP &getUDP() { return udp; }; - - WiFiUDP udp; - -private: - - void changeConnectionState(NetworkConnectionState _newState); - - const int CHECK_INTERVAL_IDLE = 100; - const int CHECK_INTERVAL_INIT = 100; - const int CHECK_INTERVAL_CONNECTING = 500; - const int CHECK_INTERVAL_CONNECTED = 10000; - const int CHECK_INTERVAL_RETRYING = 5000; - const int CHECK_INTERVAL_DISCONNECTED = 1000; - const int CHECK_INTERVAL_ERROR = 500; - - const char *ssid, *pass; - unsigned long lastConnectionTickTime; - - WiFiClient wifiClient; - int connectionTickTimeInterval; + public: + WiFiConnectionManager(const char *ssid, const char *pass); + + virtual void init(); + virtual unsigned long getTime(); + virtual void check(); + virtual Client &getClient() { + return wifiClient; + }; + virtual UDP &getUDP() { + return udp; + }; + + WiFiUDP udp; + + private: + + void changeConnectionState(NetworkConnectionState _newState); + + const int CHECK_INTERVAL_IDLE = 100; + const int CHECK_INTERVAL_INIT = 100; + const int CHECK_INTERVAL_CONNECTING = 500; + const int CHECK_INTERVAL_CONNECTED = 10000; + const int CHECK_INTERVAL_RETRYING = 5000; + const int CHECK_INTERVAL_DISCONNECTED = 1000; + const int CHECK_INTERVAL_ERROR = 500; + + const char *ssid, *pass; + unsigned long lastConnectionTickTime; + + WiFiClient wifiClient; + int connectionTickTimeInterval; }; #endif /* #ifdef BOARD_HAS_WIFI */ diff --git a/src/utility/DebugUtils.cpp b/src/utility/DebugUtils.cpp index c309a71b7..03a72ae4f 100644 --- a/src/utility/DebugUtils.cpp +++ b/src/utility/DebugUtils.cpp @@ -1,22 +1,22 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include "DebugUtils.h" @@ -24,55 +24,51 @@ #include /****************************************************************************** - * GLOBAL VARIABLES + GLOBAL VARIABLES ******************************************************************************/ static DebugLevel current_debug_level = ARDUINO_IOT_CLOUD_DEFAULT_DEBUG_LEVEL; static Stream * debug_output_stream = &Serial; /****************************************************************************** - * PRIVATE PROTOTYPES + PRIVATE PROTOTYPES ******************************************************************************/ void vDebugMessage(char const * fmt, va_list args); /****************************************************************************** - * PUBLIC FUNCTIONS + PUBLIC FUNCTIONS ******************************************************************************/ -void setDebugMessageLevel(int const debug_level) -{ - switch(debug_level) { - case -1: setDebugMessageLevel(DebugLevel::None ); break; - case 0: setDebugMessageLevel(DebugLevel::Error ); break; - case 1: setDebugMessageLevel(DebugLevel::Warning ); break; - case 2: setDebugMessageLevel(DebugLevel::Info ); break; - case 3: setDebugMessageLevel(DebugLevel::Debug ); break; - case 4: setDebugMessageLevel(DebugLevel::Verbose ); break; +void setDebugMessageLevel(int const debug_level) { + switch (debug_level) { + case -1: setDebugMessageLevel(DebugLevel::None); break; + case 0: setDebugMessageLevel(DebugLevel::Error); break; + case 1: setDebugMessageLevel(DebugLevel::Warning); break; + case 2: setDebugMessageLevel(DebugLevel::Info); break; + case 3: setDebugMessageLevel(DebugLevel::Debug); break; + case 4: setDebugMessageLevel(DebugLevel::Verbose); break; default: setDebugMessageLevel(ARDUINO_IOT_CLOUD_DEFAULT_DEBUG_LEVEL); break; } } -void setDebugMessageLevel(DebugLevel const debug_level) -{ +void setDebugMessageLevel(DebugLevel const debug_level) { current_debug_level = debug_level; } -void setDebugOutputStream(Stream * stream) -{ +void setDebugOutputStream(Stream * stream) { debug_output_stream = stream; } -void debugMessage(DebugLevel const debug_level, char * fmt, ...) -{ - if(debug_level >= DebugLevel::Error && - debug_level <= DebugLevel::Verbose && - debug_level <= current_debug_level) { - +void debugMessage(DebugLevel const debug_level, char * fmt, ...) { + if (debug_level >= DebugLevel::Error && + debug_level <= DebugLevel::Verbose && + debug_level <= current_debug_level) { + char timestamp[20]; snprintf(timestamp, 20, "[ %d ] ", millis()); debug_output_stream->print(timestamp); - + va_list args; va_start(args, fmt); vDebugMessage(fmt, args); @@ -80,11 +76,10 @@ void debugMessage(DebugLevel const debug_level, char * fmt, ...) } } -void debugMessageNoTimestamp(DebugLevel const debug_level, char * fmt, ...) -{ - if(debug_level >= DebugLevel::Error && - debug_level <= DebugLevel::Verbose && - debug_level <= current_debug_level) { +void debugMessageNoTimestamp(DebugLevel const debug_level, char * fmt, ...) { + if (debug_level >= DebugLevel::Error && + debug_level <= DebugLevel::Verbose && + debug_level <= current_debug_level) { va_list args; va_start(args, fmt); @@ -94,11 +89,10 @@ void debugMessageNoTimestamp(DebugLevel const debug_level, char * fmt, ...) } /****************************************************************************** - * PRIVATE FUNCTIONS + PRIVATE FUNCTIONS ******************************************************************************/ -void vDebugMessage(char const * fmt, va_list args) -{ +void vDebugMessage(char const * fmt, va_list args) { static size_t const MSG_BUF_SIZE = 120; char msg_buf[MSG_BUF_SIZE] = {0}; diff --git a/src/utility/DebugUtils.h b/src/utility/DebugUtils.h index f96f2fc77..ca3583059 100644 --- a/src/utility/DebugUtils.h +++ b/src/utility/DebugUtils.h @@ -1,56 +1,56 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef DEBUG_UTILS_H_ #define DEBUG_UTILS_H_ /****************************************************************************** - * INCLUDE + INCLUDE ******************************************************************************/ #include /****************************************************************************** - * TYPEDEF + TYPEDEF ******************************************************************************/ enum class DebugLevel : int { - None = -1, - Error = 0, - Warning = 1, - Info = 2, - Debug = 3, - Verbose = 4 + None = -1, + Error = 0, + Warning = 1, + Info = 2, + Debug = 3, + Verbose = 4 }; /****************************************************************************** - * CONSTANTS + CONSTANTS ******************************************************************************/ static DebugLevel const ARDUINO_IOT_CLOUD_DEFAULT_DEBUG_LEVEL = DebugLevel::Info; /****************************************************************************** - * PROTOTYPES + PROTOTYPES ******************************************************************************/ -void setDebugMessageLevel (int const debug_level); /* For backwards compatibility */ -void setDebugMessageLevel (DebugLevel const debug_level); -void setDebugOutputStream (Stream * stream); -void debugMessage (DebugLevel const debug_level, char * fmt, ...); +void setDebugMessageLevel(int const debug_level); /* For backwards compatibility */ +void setDebugMessageLevel(DebugLevel const debug_level); +void setDebugOutputStream(Stream * stream); +void debugMessage(DebugLevel const debug_level, char * fmt, ...); void debugMessageNoTimestamp(DebugLevel const debug_level, char * fmt, ...); #endif /* DEBUG_UTILS_H_ */ \ No newline at end of file diff --git a/src/utility/ECCX08Cert.cpp b/src/utility/ECCX08Cert.cpp index c5a42ea14..ba6a1eb50 100644 --- a/src/utility/ECCX08Cert.cpp +++ b/src/utility/ECCX08Cert.cpp @@ -1,19 +1,19 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #include #include @@ -43,8 +43,7 @@ struct __attribute__((__packed__)) SerialNumberAndAuthorityKeyIdentifier { byte authorityKeyIdentifier[AUTHORITY_KEY_IDENTIFIER_LENGTH]; }; -static String base64Encode(const byte in[], unsigned int length, const char* prefix, const char* suffix) -{ +static String base64Encode(const byte in[], unsigned int length, const char* prefix, const char* suffix) { static const char* CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; int b; @@ -56,10 +55,10 @@ static String base64Encode(const byte in[], unsigned int length, const char* pre if (prefix) { out += prefix; } - + for (unsigned int i = 0; i < length; i += 3) { - if (i > 0 && (i / 3 * 4) % 76 == 0) { - out += '\n'; + if (i > 0 && (i / 3 * 4) % 76 == 0) { + out += '\n'; } b = (in[i] & 0xFC) >> 2; @@ -71,10 +70,10 @@ static String base64Encode(const byte in[], unsigned int length, const char* pre out += CODES[b]; b = (in[i + 1] & 0x0F) << 2; if (i + 2 < length) { - b |= (in[i + 2] & 0xC0) >> 6; - out += CODES[b]; - b = in[i + 2] & 0x3F; - out += CODES[b]; + b |= (in[i + 2] & 0xC0) >> 6; + out += CODES[b]; + b = in[i + 2] & 0x3F; + out += CODES[b]; } else { out += CODES[b]; out += '='; @@ -97,20 +96,17 @@ ECCX08CertClass::ECCX08CertClass() : _compressedCertSlot(-1), _serialNumberAndAuthorityKeyIdentifierSlot(-1), _bytes(NULL), - _length(0) -{ + _length(0) { } -ECCX08CertClass::~ECCX08CertClass() -{ +ECCX08CertClass::~ECCX08CertClass() { if (_bytes) { free(_bytes); _bytes = NULL; } } -int ECCX08CertClass::beginCSR(int keySlot, bool newPrivateKey) -{ +int ECCX08CertClass::beginCSR(int keySlot, bool newPrivateKey) { if (keySlot < 0 || keySlot > 8) { return 0; } @@ -130,15 +126,14 @@ int ECCX08CertClass::beginCSR(int keySlot, bool newPrivateKey) return 1; } -String ECCX08CertClass::endCSR() -{ +String ECCX08CertClass::endCSR() { int versionLen = versionLength(); int subjectLen = issuerOrSubjectLength(_subjectCountryName, - _subjectStateProvinceName, - _subjectLocalityName, - _subjectOrganizationName, - _subjectOrganizationalUnitName, - _subjectCommonName); + _subjectStateProvinceName, + _subjectLocalityName, + _subjectOrganizationName, + _subjectOrganizationalUnitName, + _subjectCommonName); int subjectHeaderLen = sequenceHeaderLength(subjectLen); int publicKeyLen = publicKeyLength(); @@ -207,8 +202,7 @@ String ECCX08CertClass::endCSR() return base64Encode(csr, csrLen + csrHeaderLen, "-----BEGIN CERTIFICATE REQUEST-----\n", "\n-----END CERTIFICATE REQUEST-----\n"); } -int ECCX08CertClass::beginStorage(int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot) -{ +int ECCX08CertClass::beginStorage(int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot) { if (compressedCertSlot < 8 || compressedCertSlot > 15) { return 0; } @@ -225,23 +219,20 @@ int ECCX08CertClass::beginStorage(int compressedCertSlot, int serialNumberAndAut return 1; } -void ECCX08CertClass::setSignature(byte signature[]) -{ +void ECCX08CertClass::setSignature(byte signature[]) { struct CompressedCert* compressedCert = (struct CompressedCert*)_temp; memcpy(compressedCert->signature, signature, 64); } -void ECCX08CertClass::setIssueYear(int issueYear) -{ +void ECCX08CertClass::setIssueYear(int issueYear) { struct CompressedCert* compressedCert = (struct CompressedCert*)_temp; compressedCert->dates[0] &= 0x07; compressedCert->dates[0] |= (issueYear - 2000) << 3; } -void ECCX08CertClass::setIssueMonth(int issueMonth) -{ +void ECCX08CertClass::setIssueMonth(int issueMonth) { struct CompressedCert* compressedCert = (struct CompressedCert*)_temp; compressedCert->dates[0] &= 0xf8; @@ -251,16 +242,14 @@ void ECCX08CertClass::setIssueMonth(int issueMonth) compressedCert->dates[1] |= issueMonth << 7; } -void ECCX08CertClass::setIssueDay(int issueDay) -{ +void ECCX08CertClass::setIssueDay(int issueDay) { struct CompressedCert* compressedCert = (struct CompressedCert*)_temp; compressedCert->dates[1] &= 0x83; compressedCert->dates[1] |= issueDay << 2; } -void ECCX08CertClass::setIssueHour(int issueHour) -{ +void ECCX08CertClass::setIssueHour(int issueHour) { struct CompressedCert* compressedCert = (struct CompressedCert*)_temp; compressedCert->dates[2] &= 0x1f; @@ -270,26 +259,22 @@ void ECCX08CertClass::setIssueHour(int issueHour) compressedCert->dates[1] |= issueHour >> 3; } -void ECCX08CertClass::setExpireYears(int expireYears) -{ +void ECCX08CertClass::setExpireYears(int expireYears) { struct CompressedCert* compressedCert = (struct CompressedCert*)_temp; compressedCert->dates[2] &= 0xe0; compressedCert->dates[2] |= expireYears; } -void ECCX08CertClass::setSerialNumber(const byte serialNumber[]) -{ +void ECCX08CertClass::setSerialNumber(const byte serialNumber[]) { memcpy(&_temp[72], serialNumber, SERIAL_NUMBER_LENGTH); } -void ECCX08CertClass::setAuthorityKeyIdentifier(const byte authorityKeyIdentifier[]) -{ +void ECCX08CertClass::setAuthorityKeyIdentifier(const byte authorityKeyIdentifier[]) { memcpy(&_temp[88], authorityKeyIdentifier, AUTHORITY_KEY_IDENTIFIER_LENGTH); } -int ECCX08CertClass::endStorage() -{ +int ECCX08CertClass::endStorage() { if (!ECCX08.writeSlot(_compressedCertSlot, &_temp[0], 72)) { return 0; } @@ -301,8 +286,7 @@ int ECCX08CertClass::endStorage() return 1; } -int ECCX08CertClass::beginReconstruction(int keySlot, int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot) -{ +int ECCX08CertClass::beginReconstruction(int keySlot, int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot) { if (keySlot < 0 || keySlot > 8) { return 0; } @@ -322,8 +306,7 @@ int ECCX08CertClass::beginReconstruction(int keySlot, int compressedCertSlot, in return 1; } -int ECCX08CertClass::endReconstruction() -{ +int ECCX08CertClass::endReconstruction() { byte publicKey[64]; struct CompressedCert compressedCert; struct SerialNumberAndAuthorityKeyIdentifier serialNumberAndAuthorityKeyIdentifier; @@ -371,21 +354,21 @@ int ECCX08CertClass::endReconstruction() int issuerHeaderLen = sequenceHeaderLength(issuerLen); int subjectLen = issuerOrSubjectLength(_subjectCountryName, - _subjectStateProvinceName, - _subjectLocalityName, - _subjectOrganizationName, - _subjectOrganizationalUnitName, - _subjectCommonName); + _subjectStateProvinceName, + _subjectLocalityName, + _subjectOrganizationName, + _subjectOrganizationalUnitName, + _subjectCommonName); int subjectHeaderLen = sequenceHeaderLength(subjectLen); int publicKeyLen = publicKeyLength(); int authorityKeyIdentifierLen = authorityKeyIdentifierLength(serialNumberAndAuthorityKeyIdentifier.authorityKeyIdentifier); - + int signatureLen = signatureLength(compressedCert.signature); - int certInfoLen = 5 + serialNumberLen + 12 + issuerHeaderLen + issuerLen + (datesSize + 2) + + int certInfoLen = 5 + serialNumberLen + 12 + issuerHeaderLen + issuerLen + (datesSize + 2) + subjectHeaderLen + subjectLen + publicKeyLen; if (authorityKeyIdentifierLen) { @@ -478,88 +461,72 @@ int ECCX08CertClass::endReconstruction() return 1; } -byte* ECCX08CertClass::bytes() -{ +byte* ECCX08CertClass::bytes() { return _bytes; } -int ECCX08CertClass::length() -{ +int ECCX08CertClass::length() { return _length; } -void ECCX08CertClass::setIssuerCountryName(const String& countryName) -{ +void ECCX08CertClass::setIssuerCountryName(const String& countryName) { _issuerCountryName = countryName; } -void ECCX08CertClass::setIssuerStateProvinceName(const String& stateProvinceName) -{ +void ECCX08CertClass::setIssuerStateProvinceName(const String& stateProvinceName) { _issuerStateProvinceName = stateProvinceName; } -void ECCX08CertClass::setIssuerLocalityName(const String& localityName) -{ +void ECCX08CertClass::setIssuerLocalityName(const String& localityName) { _issuerLocalityName = localityName; } -void ECCX08CertClass::setIssuerOrganizationName(const String& organizationName) -{ +void ECCX08CertClass::setIssuerOrganizationName(const String& organizationName) { _issuerOrganizationName = organizationName; } -void ECCX08CertClass::setIssuerOrganizationalUnitName(const String& organizationalUnitName) -{ +void ECCX08CertClass::setIssuerOrganizationalUnitName(const String& organizationalUnitName) { _issuerOrganizationalUnitName = organizationalUnitName; } -void ECCX08CertClass::setIssuerCommonName(const String& commonName) -{ +void ECCX08CertClass::setIssuerCommonName(const String& commonName) { _issuerCommonName = commonName; } -void ECCX08CertClass::setSubjectCountryName(const String& countryName) -{ +void ECCX08CertClass::setSubjectCountryName(const String& countryName) { _subjectCountryName = countryName; } -void ECCX08CertClass::setSubjectStateProvinceName(const String& stateProvinceName) -{ +void ECCX08CertClass::setSubjectStateProvinceName(const String& stateProvinceName) { _subjectStateProvinceName = stateProvinceName; } -void ECCX08CertClass::setSubjectLocalityName(const String& localityName) -{ +void ECCX08CertClass::setSubjectLocalityName(const String& localityName) { _subjectLocalityName = localityName; } -void ECCX08CertClass::setSubjectOrganizationName(const String& organizationName) -{ +void ECCX08CertClass::setSubjectOrganizationName(const String& organizationName) { _subjectOrganizationName = organizationName; } -void ECCX08CertClass::setSubjectOrganizationalUnitName(const String& organizationalUnitName) -{ +void ECCX08CertClass::setSubjectOrganizationalUnitName(const String& organizationalUnitName) { _subjectOrganizationName = organizationalUnitName; } -void ECCX08CertClass::setSubjectCommonName(const String& commonName) -{ +void ECCX08CertClass::setSubjectCommonName(const String& commonName) { _subjectCommonName = commonName; } -int ECCX08CertClass::versionLength() -{ +int ECCX08CertClass::versionLength() { return 3; } int ECCX08CertClass::issuerOrSubjectLength(const String& countryName, - const String& stateProvinceName, - const String& localityName, - const String& organizationName, - const String& organizationalUnitName, - const String& commonName) -{ + const String& stateProvinceName, + const String& localityName, + const String& organizationName, + const String& organizationalUnitName, + const String& commonName) { int length = 0; int countryNameLength = countryName.length(); int stateProvinceNameLength = stateProvinceName.length(); @@ -595,13 +562,11 @@ int ECCX08CertClass::issuerOrSubjectLength(const String& countryName, return length; } -int ECCX08CertClass::publicKeyLength() -{ +int ECCX08CertClass::publicKeyLength() { return (2 + 2 + 9 + 10 + 4 + 64); } -int ECCX08CertClass::authorityKeyIdentifierLength(const byte authorityKeyIdentifier[]) -{ +int ECCX08CertClass::authorityKeyIdentifierLength(const byte authorityKeyIdentifier[]) { bool set = false; // check if the authority key identifier is non-zero @@ -615,8 +580,7 @@ int ECCX08CertClass::authorityKeyIdentifierLength(const byte authorityKeyIdentif return (set ? 37 : 0); } -int ECCX08CertClass::signatureLength(const byte signature[]) -{ +int ECCX08CertClass::signatureLength(const byte signature[]) { const byte* r = &signature[0]; const byte* s = &signature[32]; @@ -644,8 +608,7 @@ int ECCX08CertClass::signatureLength(const byte signature[]) return (21 + rLength + sLength); } -int ECCX08CertClass::serialNumberLength(const byte serialNumber[]) -{ +int ECCX08CertClass::serialNumberLength(const byte serialNumber[]) { int length = SERIAL_NUMBER_LENGTH; while (*serialNumber == 0 && length) { @@ -660,8 +623,7 @@ int ECCX08CertClass::serialNumberLength(const byte serialNumber[]) return (2 + length); } -int ECCX08CertClass::sequenceHeaderLength(int length) -{ +int ECCX08CertClass::sequenceHeaderLength(int length) { if (length > 255) { return 4; } else if (length > 127) { @@ -671,21 +633,19 @@ int ECCX08CertClass::sequenceHeaderLength(int length) } } -void ECCX08CertClass::appendVersion(int version, byte out[]) -{ +void ECCX08CertClass::appendVersion(int version, byte out[]) { out[0] = ASN1_INTEGER; out[1] = 0x01; out[2] = version; } void ECCX08CertClass::appendIssuerOrSubject(const String& countryName, - const String& stateProvinceName, - const String& localityName, - const String& organizationName, - const String& organizationalUnitName, - const String& commonName, - byte out[]) -{ + const String& stateProvinceName, + const String& localityName, + const String& organizationName, + const String& organizationalUnitName, + const String& commonName, + byte out[]) { if (countryName.length() > 0) { out += appendName(countryName, 0x06, out); } @@ -711,8 +671,7 @@ void ECCX08CertClass::appendIssuerOrSubject(const String& countryName, } } -void ECCX08CertClass::appendPublicKey(const byte publicKey[], byte out[]) -{ +void ECCX08CertClass::appendPublicKey(const byte publicKey[], byte out[]) { int subjectPublicKeyDataLength = 2 + 9 + 10 + 4 + 64; // subject public key @@ -753,8 +712,7 @@ void ECCX08CertClass::appendPublicKey(const byte publicKey[], byte out[]) memcpy(out, publicKey, 64); } -void ECCX08CertClass::appendAuthorityKeyIdentifier(const byte authorityKeyIdentifier[], byte out[]) -{ +void ECCX08CertClass::appendAuthorityKeyIdentifier(const byte authorityKeyIdentifier[], byte out[]) { // [3] *out++ = 0xa3; *out++ = 0x23; @@ -788,8 +746,7 @@ void ECCX08CertClass::appendAuthorityKeyIdentifier(const byte authorityKeyIdenti memcpy(out, authorityKeyIdentifier, 20); } -void ECCX08CertClass::appendSignature(const byte signature[], byte out[]) -{ +void ECCX08CertClass::appendSignature(const byte signature[], byte out[]) { // signature algorithm *out++ = ASN1_SEQUENCE; *out++ = 0x0a; @@ -823,7 +780,7 @@ void ECCX08CertClass::appendSignature(const byte signature[], byte out[]) } if (*r & 0x80) { - rLength++; + rLength++; } if (*s & 0x80) { @@ -856,8 +813,7 @@ void ECCX08CertClass::appendSignature(const byte signature[], byte out[]) out += rLength; } -void ECCX08CertClass::appendSerialNumber(const byte serialNumber[], byte out[]) -{ +void ECCX08CertClass::appendSerialNumber(const byte serialNumber[], byte out[]) { int length = SERIAL_NUMBER_LENGTH; while (*serialNumber == 0 && length) { @@ -866,7 +822,7 @@ void ECCX08CertClass::appendSerialNumber(const byte serialNumber[], byte out[]) } if (*serialNumber & 0x80) { - length++; + length++; } *out++ = ASN1_INTEGER; @@ -880,8 +836,7 @@ void ECCX08CertClass::appendSerialNumber(const byte serialNumber[], byte out[]) memcpy(out, serialNumber, length); } -int ECCX08CertClass::appendName(const String& name, int type, byte out[]) -{ +int ECCX08CertClass::appendName(const String& name, int type, byte out[]) { int nameLength = name.length(); *out++ = ASN1_SET; @@ -903,8 +858,7 @@ int ECCX08CertClass::appendName(const String& name, int type, byte out[]) return (nameLength + 11); } -void ECCX08CertClass::appendSequenceHeader(int length, byte out[]) -{ +void ECCX08CertClass::appendSequenceHeader(int length, byte out[]) { *out++ = ASN1_SEQUENCE; if (length > 255) { *out++ = 0x82; @@ -915,8 +869,7 @@ void ECCX08CertClass::appendSequenceHeader(int length, byte out[]) *out++ = (length) & 0xff; } -int ECCX08CertClass::appendDate(int year, int month, int day, int hour, int minute, int second, byte out[]) -{ +int ECCX08CertClass::appendDate(int year, int month, int day, int hour, int minute, int second, byte out[]) { bool useGeneralizedTime = (year > 2049); if (useGeneralizedTime) { @@ -949,8 +902,7 @@ int ECCX08CertClass::appendDate(int year, int month, int day, int hour, int minu return (useGeneralizedTime ? 17 : 15); } -int ECCX08CertClass::appendEcdsaWithSHA256(byte out[]) -{ +int ECCX08CertClass::appendEcdsaWithSHA256(byte out[]) { *out++ = ASN1_SEQUENCE; *out++ = 0x0A; *out++ = ASN1_OBJECT_IDENTIFIER; diff --git a/src/utility/ECCX08Cert.h b/src/utility/ECCX08Cert.h index 4c0a0afad..a5a282efd 100644 --- a/src/utility/ECCX08Cert.h +++ b/src/utility/ECCX08Cert.h @@ -1,19 +1,19 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef _ECCX08_CERT_H_ #define _ECCC08_CERT_H_ @@ -22,112 +22,112 @@ class ECCX08CertClass { -public: - ECCX08CertClass(); - virtual ~ECCX08CertClass(); + public: + ECCX08CertClass(); + virtual ~ECCX08CertClass(); - int beginCSR(int keySlot, bool newPrivateKey = true); - String endCSR(); + int beginCSR(int keySlot, bool newPrivateKey = true); + String endCSR(); - int beginStorage(int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot); - void setSignature(byte signature[]); - void setIssueYear(int issueYear); - void setIssueMonth(int issueMonth); - void setIssueDay(int issueDay); - void setIssueHour(int issueHour); - void setExpireYears(int expireYears); - void setSerialNumber(const byte serialNumber[]); - void setAuthorityKeyIdentifier(const byte authorityKeyIdentifier[]); - int endStorage(); + int beginStorage(int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot); + void setSignature(byte signature[]); + void setIssueYear(int issueYear); + void setIssueMonth(int issueMonth); + void setIssueDay(int issueDay); + void setIssueHour(int issueHour); + void setExpireYears(int expireYears); + void setSerialNumber(const byte serialNumber[]); + void setAuthorityKeyIdentifier(const byte authorityKeyIdentifier[]); + int endStorage(); - int beginReconstruction(int keySlot, int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot); - int endReconstruction(); + int beginReconstruction(int keySlot, int compressedCertSlot, int serialNumberAndAuthorityKeyIdentifierSlot); + int endReconstruction(); - byte* bytes(); - int length(); + byte* bytes(); + int length(); - void setIssuerCountryName(const String& countryName); - void setIssuerStateProvinceName(const String& stateProvinceName); - void setIssuerLocalityName(const String& localityName); - void setIssuerOrganizationName(const String& organizationName); - void setIssuerOrganizationalUnitName(const String& organizationalUnitName); - void setIssuerCommonName(const String& commonName); + void setIssuerCountryName(const String& countryName); + void setIssuerStateProvinceName(const String& stateProvinceName); + void setIssuerLocalityName(const String& localityName); + void setIssuerOrganizationName(const String& organizationName); + void setIssuerOrganizationalUnitName(const String& organizationalUnitName); + void setIssuerCommonName(const String& commonName); - void setSubjectCountryName(const String& countryName); - void setSubjectStateProvinceName(const String& stateProvinceName); - void setSubjectLocalityName(const String& localityName); - void setSubjectOrganizationName(const String& organizationName); - void setSubjectOrganizationalUnitName(const String& organizationalUnitName); - void setSubjectCommonName(const String& commonName); + void setSubjectCountryName(const String& countryName); + void setSubjectStateProvinceName(const String& stateProvinceName); + void setSubjectLocalityName(const String& localityName); + void setSubjectOrganizationName(const String& organizationName); + void setSubjectOrganizationalUnitName(const String& organizationalUnitName); + void setSubjectCommonName(const String& commonName); -private: - int versionLength(); + private: + int versionLength(); - int issuerOrSubjectLength(const String& countryName, - const String& stateProvinceName, - const String& localityName, - const String& organizationName, - const String& organizationalUnitName, - const String& commonName); + int issuerOrSubjectLength(const String& countryName, + const String& stateProvinceName, + const String& localityName, + const String& organizationName, + const String& organizationalUnitName, + const String& commonName); - int publicKeyLength(); + int publicKeyLength(); - int authorityKeyIdentifierLength(const byte authorityKeyIdentifier[]); + int authorityKeyIdentifierLength(const byte authorityKeyIdentifier[]); - int signatureLength(const byte signature[]); + int signatureLength(const byte signature[]); - int serialNumberLength(const byte serialNumber[]); + int serialNumberLength(const byte serialNumber[]); - int sequenceHeaderLength(int length); + int sequenceHeaderLength(int length); - void appendVersion(int version, byte out[]); + void appendVersion(int version, byte out[]); - void appendIssuerOrSubject(const String& countryName, - const String& stateProvinceName, - const String& localityName, - const String& organizationName, - const String& organizationalUnitName, - const String& commonName, - byte out[]); + void appendIssuerOrSubject(const String& countryName, + const String& stateProvinceName, + const String& localityName, + const String& organizationName, + const String& organizationalUnitName, + const String& commonName, + byte out[]); - void appendPublicKey(const byte publicKey[], byte out[]); + void appendPublicKey(const byte publicKey[], byte out[]); - void appendAuthorityKeyIdentifier(const byte authorityKeyIdentifier[], byte out[]); + void appendAuthorityKeyIdentifier(const byte authorityKeyIdentifier[], byte out[]); - void appendSignature(const byte signature[], byte out[]); + void appendSignature(const byte signature[], byte out[]); - void appendSerialNumber(const byte serialNumber[], byte out[]); + void appendSerialNumber(const byte serialNumber[], byte out[]); - int appendName(const String& name, int type, byte out[]); + int appendName(const String& name, int type, byte out[]); - void appendSequenceHeader(int length, byte out[]); + void appendSequenceHeader(int length, byte out[]); - int appendDate(int year, int month, int day, int hour, int minute, int second, byte out[]); + int appendDate(int year, int month, int day, int hour, int minute, int second, byte out[]); - int appendEcdsaWithSHA256(byte out[]); + int appendEcdsaWithSHA256(byte out[]); -private: - int _keySlot; - int _compressedCertSlot; - int _serialNumberAndAuthorityKeyIdentifierSlot; + private: + int _keySlot; + int _compressedCertSlot; + int _serialNumberAndAuthorityKeyIdentifierSlot; - String _issuerCountryName; - String _issuerStateProvinceName; - String _issuerLocalityName; - String _issuerOrganizationName; - String _issuerOrganizationalUnitName; - String _issuerCommonName; + String _issuerCountryName; + String _issuerStateProvinceName; + String _issuerLocalityName; + String _issuerOrganizationName; + String _issuerOrganizationalUnitName; + String _issuerCommonName; - String _subjectCountryName; - String _subjectStateProvinceName; - String _subjectLocalityName; - String _subjectOrganizationName; - String _subjectOrganizationalUnitName; - String _subjectCommonName; + String _subjectCountryName; + String _subjectStateProvinceName; + String _subjectLocalityName; + String _subjectOrganizationName; + String _subjectOrganizationalUnitName; + String _subjectCommonName; - byte _temp[108]; - byte* _bytes; - int _length; + byte _temp[108]; + byte* _bytes; + int _length; }; extern ECCX08CertClass ECCX08Cert; diff --git a/src/utility/ECCX08TLSConfig.h b/src/utility/ECCX08TLSConfig.h index 998bbedbf..671c89b7e 100644 --- a/src/utility/ECCX08TLSConfig.h +++ b/src/utility/ECCX08TLSConfig.h @@ -1,25 +1,25 @@ /* - * This file is part of ArduinoIoTCloud. - * - * Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - * - * This software is released under the GNU General Public License version 3, - * which covers the main part of arduino-cli. - * The terms of this license can be found at: - * https://www.gnu.org/licenses/gpl-3.0.en.html - * - * You can be released from the requirements of the above licenses by purchasing - * a commercial license. Buying such a license is mandatory if you want to modify or - * otherwise use the software for commercial activities involving the Arduino - * software without disclosing the source code of your own applications. To purchase - * a commercial license, send an email to license@arduino.cc. - */ + This file is part of ArduinoIoTCloud. + + Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + + This software is released under the GNU General Public License version 3, + which covers the main part of arduino-cli. + The terms of this license can be found at: + https://www.gnu.org/licenses/gpl-3.0.en.html + + You can be released from the requirements of the above licenses by purchasing + a commercial license. Buying such a license is mandatory if you want to modify or + otherwise use the software for commercial activities involving the Arduino + software without disclosing the source code of your own applications. To purchase + a commercial license, send an email to license@arduino.cc. +*/ #ifndef _ECCX08_TLS_CONFIG_H_ #define _ECCX08_TLS_CONFIG_H_ const byte DEFAULT_ECCX08_TLS_CONFIG[128] = { -// Read only - start + // Read only - start // SN[0:3] 0x01, 0x23, 0x00, 0x00, // RevNum @@ -30,9 +30,9 @@ const byte DEFAULT_ECCX08_TLS_CONFIG[128] = { 0xC0, // I2C_Enable 0x71, - // Reserved + // Reserved 0x00, -// Read only - end + // Read only - end // I2C_Address 0xC0, // Reserved @@ -42,21 +42,21 @@ const byte DEFAULT_ECCX08_TLS_CONFIG[128] = { // ChipMode 0x00, // SlotConfig - 0x83, 0x20, // External Signatures | Internal Signatures | IsSecret | Write Configure Never, Default: 0x83, 0x20, + 0x83, 0x20, // External Signatures | Internal Signatures | IsSecret | Write Configure Never, Default: 0x83, 0x20, 0x87, 0x20, // External Signatures | Internal Signatures | ECDH | IsSecret | Write Configure Never, Default: 0x87, 0x20, 0x87, 0x20, // External Signatures | Internal Signatures | ECDH | IsSecret | Write Configure Never, Default: 0x8F, 0x20, 0x87, 0x2F, // External Signatures | Internal Signatures | ECDH | IsSecret | WriteKey all slots | Write Configure Never, Default: 0xC4, 0x8F, - 0x87, 0x2F, // External Signatures | Internal Signatures | ECDH | IsSecret | WriteKey all slots | Write Configure Never, Default: 0x8F, 0x8F, + 0x87, 0x2F, // External Signatures | Internal Signatures | ECDH | IsSecret | WriteKey all slots | Write Configure Never, Default: 0x8F, 0x8F, 0x8F, 0x8F, - 0x9F, 0x8F, + 0x9F, 0x8F, 0xAF, 0x8F, - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x00, 0xAF, 0x8F, // Counter[0] 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, @@ -67,9 +67,9 @@ const byte DEFAULT_ECCX08_TLS_CONFIG[128] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, -// Write via commands only - start + // Write via commands only - start // UserExtra - 0x00, + 0x00, // Selector 0x00, // LockValue @@ -78,7 +78,7 @@ const byte DEFAULT_ECCX08_TLS_CONFIG[128] = { 0x55, // SlotLocked 0xFF, 0xFF, -// Write via commands only - end + // Write via commands only - end // RFU 0x00, 0x00, // X509format diff --git a/src/utility/NTPUtils.cpp b/src/utility/NTPUtils.cpp index 32cde509d..dba8472e0 100644 --- a/src/utility/NTPUtils.cpp +++ b/src/utility/NTPUtils.cpp @@ -8,28 +8,28 @@ // could be a constexpr in C++14 static time_t cvt_TIME(char const *time) { - char s_month[5]; - int month, day, year; - struct tm t = {0}; - static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; + char s_month[5]; + int month, day, year; + struct tm t = {0}; + static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; - sscanf(time, "%s %d %d", s_month, &day, &year); + sscanf(time, "%s %d %d", s_month, &day, &year); - month = (strstr(month_names, s_month)-month_names)/3; + month = (strstr(month_names, s_month) - month_names) / 3; - t.tm_mon = month; - t.tm_mday = day; - t.tm_year = year - 1900; - t.tm_isdst = -1; + t.tm_mon = month; + t.tm_mday = day; + t.tm_year = year - 1900; + t.tm_isdst = -1; - return mktime(&t); + return mktime(&t); } NTPUtils::NTPUtils(UDP& Udp) : Udp(Udp) {} bool NTPUtils::isTimeValid(unsigned long time) { - return (time > cvt_TIME(__DATE__)); + return (time > cvt_TIME(__DATE__)); } void NTPUtils::sendNTPpacket(uint8_t* packetBuffer) { @@ -55,7 +55,7 @@ unsigned long NTPUtils::getTime() { Udp.begin(localPort); sendNTPpacket(packetBuffer); long start = millis(); - while (!Udp.parsePacket() && (millis() - start < 10000)){} + while (!Udp.parsePacket() && (millis() - start < 10000)) {} if (millis() - start >= 1000) { //timeout reached Udp.stop(); diff --git a/src/utility/NTPUtils.h b/src/utility/NTPUtils.h index 1759d3c7e..15c7a6585 100644 --- a/src/utility/NTPUtils.h +++ b/src/utility/NTPUtils.h @@ -9,15 +9,15 @@ #include class NTPUtils { - public: - NTPUtils(UDP& Udp); - void sendNTPpacket(uint8_t* packetBuffer); - unsigned long getTime(); - static bool isTimeValid(unsigned long time); - private: - const char* timeServer = "time.arduino.cc"; - const int NTP_PACKET_SIZE = 48; - UDP& Udp; + public: + NTPUtils(UDP& Udp); + void sendNTPpacket(uint8_t* packetBuffer); + unsigned long getTime(); + static bool isTimeValid(unsigned long time); + private: + const char* timeServer = "time.arduino.cc"; + const int NTP_PACKET_SIZE = 48; + UDP& Udp; }; #endif