16 #include <MD5Builder.h>
24 #include <StreamString.h>
25 #include <ArduinoJson.h>
33 TimerHandle_t ledTimer;
34 #elif defined(ESP8266)
49 DEBUG_WARN (
"Config file %s deleted. Restarting");
78 data->lastMessageCounter = 0;
81 memset (
data->gateway, 0, 6);
85 data->nodeKeyValid =
false;
89 Serial.println (
"RTC MEM DATA:");
91 Serial.printf (
" -- CRC: %s\n",
printHexBuffer ((uint8_t*)&(
data->crc32), sizeof (uint32_t)));
93 Serial.printf (
" -- Node key is %svalid\n",
data->nodeKeyValid ?
"" :
"NOT ");
94 Serial.printf (
" -- Node status is %d: %s\n",
data->nodeRegisterStatus,
data->nodeRegisterStatus ==
REGISTERED ?
"REGISTERED" :
"NOT REGISTERED");
95 Serial.printf (
" -- Node name: %s\n",
data->nodeName);
96 Serial.printf (
" -- Last message counter: %d\n",
data->lastMessageCounter);
97 Serial.printf (
" -- NodeID: %d\n",
data->nodeId);
98 Serial.printf (
" -- Channel: %d\n",
data->channel);
99 Serial.printf (
" -- RSSI: %d\n",
data->rssi);
100 Serial.printf (
" -- Network name: %s\n",
data->networkName);
102 Serial.printf (
" -- Gateway: %s\n",
mac2str (
data->gateway, gwAddress));
103 Serial.printf (
" -- Comm errors: %d\n",
data->commErrors);
105 Serial.printf (
" -- Gateway address: %s\n",
mac2str (gateway, gwAddress));
107 Serial.printf (
" -- Mode: %s\n",
data->sleepy ?
"sleepy" :
"non sleepy");
109 Serial.println (
"rtcmem_data pointer is NULL");
118 DEBUG_ERROR (
"Error reading RTC memory");
127 DEBUG_DBG (
"RTC Data is not valid");
149 DEBUG_DBG (
"Set %s mode",
node.
getSleepy () ?
"sleepy" :
"non sleepy");
150 #if DEBUG_LEVEL >= VERBOSE
161 bool json_correct =
false;
168 size_t size = configFile.size ();
170 const size_t capacity = JSON_ARRAY_SIZE (32) + JSON_OBJECT_SIZE (5) + 100;
171 DynamicJsonDocument doc (capacity);
172 DeserializationError error = deserializeJson (doc, configFile);
174 DEBUG_ERROR (
"Failed to parse file");
176 DEBUG_DBG (
"JSON file parsed");
179 if (doc.containsKey (
"networkName") && doc.containsKey (
"networkKey")
180 && doc.containsKey (
"sleepTime")) {
189 JsonArray netKeyJson = doc[
"networkKey"];
191 DEBUG_WARN (
"Error in stored network key. Expected length: %d, actual length %d",
KEY_LENGTH, netKeyJson.size ());
203 if (doc.containsKey (
"gateway")) {
204 strncpy (gwAddrStr, doc[
"gateway"],
sizeof (gwAddrStr));
211 DEBUG_VERBOSE (
"Configuration successfuly read");
214 DEBUG_DBG (
"==== EnigmaIOT Node Configuration ====");
218 DEBUG_DBG (
"Gateway: %s", gwAddrStr);
222 serializeJsonPretty (doc, output);
224 DEBUG_DBG (
"JSON file %s", output.c_str ());
242 DEBUG_WARN (
"failed to open config file %s for writing",
CONFIG_FILE);
246 const size_t capacity = JSON_ARRAY_SIZE (32) + JSON_OBJECT_SIZE (5) + 100;
247 DynamicJsonDocument doc (capacity);
253 JsonArray netKeyJson = doc.createNestedArray (
"networkKey");
258 doc[
"gateway"] = gwAddrStr;
261 if (serializeJson (doc, configFile) == 0) {
262 DEBUG_ERROR (
"Failed to write to file");
269 serializeJsonPretty (doc, output);
271 DEBUG_DBG (
"%s", output.c_str ());
274 size_t size = configFile.size ();
277 DEBUG_DBG (
"Configuration saved to flash. %u bytes", size);
278 #if DEBUG_LEVEL >= DBG
292 DEBUG_DBG (
"Write configuration data to RTC memory");
293 #if DEBUG_LEVEL >= VERBOSE
302 rtcmem_data_storage.crc32 =
calculateCRC32 ((uint8_t*)rtcmem_data_storage.nodeKey, sizeof (
rtcmem_data) -
sizeof (uint32_t));
310 if (!SPIFFS.begin ()) {
311 DEBUG_ERROR (
"Error on SPIFFS.begin()");
316 DEBUG_ERROR (
"Error on SPIFFS.remove(\"%s\")",
CONFIG_FILE);
322 AsyncWebServer server (80);
329 char sleepy[5] =
"10";
333 wifiManager =
new AsyncWiFiManager (&server, &dns);
337 AsyncWiFiManagerParameter sleepyParam (
"sleepy",
"Sleep Time", sleepy, 5,
"required type=\"number\" min=\"0\" max=\"13600\" step=\"1\"");
338 AsyncWiFiManagerParameter nodeNameParam (
"nodename",
"Node Name", nodeName,
NODE_NAME_LENGTH,
"type=\"text\" pattern=\"^[^/\\\\]+$\" maxlength=32");
340 wifiManager->setCustomHeadElement (
"<style>input:invalid {border: 2px dashed red;input:valid{border: 2px solid black;}</style>");
353 wifiManager->setTryConnectDuringConfigPortal (
false);
356 snprintf (apname, 64,
"EnigmaIoTNode%06x", ESP.getChipId ());
359 snprintf (apname, 64,
"EnigmaIoTNode%06x", (uint32_t)(ESP.getEfuseMac ()) & (uint64_t)0x0000000000FFFFFF);
362 DEBUG_VERBOSE (
"Start AP: %s", apname);
364 boolean result =
wifiManager->startConfigPortal (apname, NULL);
366 DEBUG_DBG (
"==== Config Portal result ====");
368 DEBUG_DBG (
"Network Name: %s", WiFi.SSID ().c_str ());
370 station_config wifiConfig;
371 if (!wifi_station_get_config (&wifiConfig)) {
372 DEBUG_WARN (
"Error getting WiFi config");
374 DEBUG_DBG (
"WiFi password: %s", wifiConfig.password);
375 const char* netkey = (
char*)(wifiConfig.password);
377 const char* netkey = WiFi.psk ().c_str ();
379 DEBUG_DBG (
"Network Key: %s", netkey);
380 DEBUG_DBG (
"Sleppy time: %s", sleepyParam.getValue ());
381 DEBUG_DBG (
"Node Name: %s", nodeNameParam.getValue ());
383 data->lastMessageCounter = 0;
386 DEBUG_DBG (
"Stored network key before hash: %.*s",
KEY_LENGTH, (
char*)(
data->networkKey));
392 const char* netName = WiFi.SSID ().c_str ();
393 memcpy (
data->networkName, netName, strlen (netName));
394 DEBUG_DBG (
"Stored network name: %s",
data->networkName);
396 std::regex sleepTimeRegex (
"(\\d)+");
397 regexResult = std::regex_match (sleepyParam.getValue (), sleepTimeRegex);
399 DEBUG_DBG (
"Sleep time check ok");
400 int sleepyVal = atoi (sleepyParam.getValue ());
404 data->sleepTime = sleepyVal;
406 DEBUG_WARN (
"Sleep time parameter error");
410 std::regex nodeNameRegex (
"^[^/\\\\]+$");
411 regexResult = std::regex_match (nodeNameParam.getValue (), nodeNameRegex);
414 DEBUG_DBG (
"Node name: %s",
data->nodeName);
416 DEBUG_WARN (
"Node name parameter error");
420 data->nodeKeyValid =
false;
433 digitalWrite (*(
int*)led, !digitalRead (*(
int*)led));
435 bool led_on = !digitalRead (
localLed);
436 DEBUG_VERBOSE (
"Change LED %d to %d",
localLed, led_on);
444 DEBUG_INFO (
"Start flash");
447 ledTimer = xTimerCreate (
"led_flash", pdMS_TO_TICKS (period), pdTRUE, (
void*)0, &
flashLed);
448 if (xTimerStart (ledTimer, 0) != pdPASS) {
449 DEBUG_WARN (
"Problem starting LED timer");
452 #elif defined (ESP8266)
453 ets_timer_disarm (&ledTimer);
456 ets_timer_arm_new (&ledTimer, period,
true,
true);
465 xTimerStop (ledTimer, 0);
466 xTimerDelete (ledTimer, 0);
468 #elif defined(ESP8266)
471 ets_timer_disarm (&ledTimer);
492 if (digitalRead (
resetPin) == LOW) {
493 time_t resetPinGrounded = millis ();
494 while (digitalRead (
resetPin) == LOW) {
496 DEBUG_WARN (
"Produce reset");
511 pinMode (
led, OUTPUT);
513 ets_timer_setfn (&ledTimer,
flashLed, (
void*)&
led);
529 DEBUG_DBG (
"Set %s mode: %s",
node.
getSleepy () ?
"sleepy" :
"non sleepy", sleepy ?
"sleepy" :
"non sleepy");
532 #if DEBUG_LEVEL >= DBG
538 if (gateway && networkKey) {
539 DEBUG_DBG (
"EnigmaIot started with config data con begin() call");
548 if (!SPIFFS.begin ()) {
549 DEBUG_ERROR (
"Error mounting flash");
550 if (SPIFFS.format ()) {
551 DEBUG_INFO (
"SPIFFS formatted");
553 DEBUG_ERROR (
"Error formatting SPIFFS");
561 DEBUG_DBG (
"Flash data loaded");
569 DEBUG_DBG (
"No flash data present. Starting Configuration AP");
572 DEBUG_DBG (
"Got configuration. Searching for Gateway");
574 DEBUG_DBG (
"Found EnigmaIOT Gateway. Storing configuration");
576 DEBUG_ERROR (
"Error saving data on flash");
585 DEBUG_ERROR (
"Configuration error. Restarting");
601 if ((err_ok = esp_wifi_set_promiscuous (
true))) {
602 DEBUG_ERROR (
"Error setting promiscuous mode: %s", esp_err_to_name (err_ok));
605 DEBUG_ERROR (
"Error setting wifi channel: %s", esp_err_to_name (err_ok));
607 if ((err_ok = esp_wifi_set_promiscuous (
false))) {
608 DEBUG_ERROR (
"Error setting promiscuous mode off: %s", esp_err_to_name (err_ok));
616 int scanGatewaySSID (
char* name,
int& wifiIndex) {
617 uint32_t scanStarted;
619 const int MAX_INDEXES = 10;
621 int indexes[MAX_INDEXES];
624 DEBUG_WARN (
"SSID Name is NULL");
628 scanStarted = millis ();
629 numAP = WiFi.scanNetworks (
false,
false,
false, 300U);
630 DEBUG_DBG (
"Found %d APs in %lu ms", numAP, millis () - scanStarted);
631 DEBUG_DBG (
"Scan finished. Result = %d", WiFi.scanComplete ());
632 while (!(WiFi.scanComplete ()) && (millis () - scanStarted) > 1500) {
633 #if DEBUG_LEVEL >= DBG
635 Serial.printf (
"%lu.", millis () - scanStarted);
640 DEBUG_DBG (
"Scan finished. Result = %d", WiFi.scanComplete ());
642 DEBUG_DBG (
"Found %d APs in %lu ms", numAP, millis () - scanStarted);
644 wifi_ap_record_t* wifiAP;
646 for (
int i = 0; i < numAP; i++) {
647 wifiAP = (wifi_ap_record_t*)WiFi.getScanInfoByIndex (i);
648 DEBUG_DBG (
"Found AP %.*s with BSSID " MACSTR " and RSSI %d dBm", 32, wifiAP->ssid, MAC2STR (wifiAP->bssid), wifiAP->rssi);
649 if (!strncmp (name, (
char*)(wifiAP->ssid), 32)) {
650 indexes[numFound] = i;
652 if (numFound >= MAX_INDEXES) {
658 wifiIndex = indexes[0];
665 DEBUG_DBG (
"Searching for AP %s",
data->networkName);
671 time_t scanStarted = millis ();
673 numWifi = WiFi.scanNetworks (
false,
false, 0, (uint8_t*)(
data->networkName));
674 while (!(WiFi.scanComplete () || (millis () - scanStarted) > 1500)) {
675 #if DEBUG_LEVEL >= DBG
677 Serial.printf (
"%lu.", millis () - scanStarted);
683 numWifi = scanGatewaySSID (
data->networkName, wifiIndex);
687 memcpy (prevGwAddr,
data->gateway, 6);
690 DEBUG_INFO (
"Gateway %s found: %d",
data->networkName, numWifi);
691 DEBUG_INFO (
"BSSID: %s", WiFi.BSSIDstr (wifiIndex).c_str ());
692 DEBUG_INFO (
"Channel: %d", WiFi.channel (wifiIndex));
693 DEBUG_INFO (
"RSSI: %d", WiFi.RSSI (wifiIndex));
694 data->channel = WiFi.channel (wifiIndex);
695 data->rssi = WiFi.RSSI (wifiIndex);
696 memcpy (
data->gateway, WiFi.BSSID (wifiIndex), 6);
698 if (shouldStoreData) {
699 DEBUG_DBG (
"Found gateway. Storing");
701 DEBUG_ERROR (
"Error saving data on RTC");
703 if (memcmp (prevGwAddr,
data->gateway, 6)) {
705 DEBUG_ERROR (
"Error saving data on flash");
715 wifi_set_channel (
data->channel);
718 if ((err_ok = esp_wifi_set_promiscuous (
true))) {
719 DEBUG_ERROR (
"Error setting promiscuous mode: %s", esp_err_to_name (err_ok));
721 if ((err_ok = esp_wifi_set_channel (
data->channel, WIFI_SECOND_CHAN_NONE))) {
722 DEBUG_ERROR (
"Error setting wifi channel: %s", esp_err_to_name (err_ok));
724 if ((err_ok = esp_wifi_set_promiscuous (
false))) {
725 DEBUG_ERROR (
"Error setting promiscuous mode off: %s", esp_err_to_name (err_ok));
732 DEBUG_WARN (
"Gateway %s not found",
data->networkName);
738 DEBUG_DBG (
"Communication layer uninitalized");
748 #ifdef ESP8266 // ESP32 does not have this limitation
749 uint64_t maxSleepTime = (ESP.deepSleepMax () / (uint64_t)1000000);
765 DEBUG_DBG (
"Max sleep time is %lu", (uint32_t)maxSleepTime);
771 DEBUG_DBG (
"Sleep time set to %d. Sleepy mode is %s",
776 DEBUG_WARN (
"Cannot set sleep time to %u seconds as this node started as non sleepy",
sleepTime);
784 DEBUG_DBG (
"Report RSSI and channel");
791 if (
sendData (buffer, bufLength,
true)) {
792 DEBUG_DBG (
"Sleep time is %d seconds",
sleepTime / 1000000);
796 DEBUG_WARN (
"Error sending version response");
802 static unsigned long blueOntime;
820 blueOntime = millis ();
826 if ( millis () - blueOntime >
ledOnTime) {
835 uint64_t msSleep =
sleepTime / (uint64_t)1000;
836 DEBUG_INFO (
"Go to sleep for %lu ms", (uint32_t)(msSleep));
846 static time_t lastRegistration = millis ();
856 DEBUG_ERROR (
"Error saving data on RTC");
861 DEBUG_INFO (
"Registration timeout. Go to sleep for %lu ms", (uint32_t)(
RECONNECTION_PERIOD * 4 + rnd/1000));
881 lastRegistration = millis ();
884 DEBUG_INFO (
"Random delay (%u)", rnd);
894 uint8_t responseBuffer[2];
897 if (
sendData (responseBuffer,
sizeof (responseBuffer),
true)) {
898 DEBUG_INFO (
"OTA TIMEOUT");
918 static time_t lastTimeSync;
921 lastTimeSync = millis ();
922 DEBUG_DBG (
"Clock Request");
930 static unsigned long retartRequest = millis ();
931 if (millis () - retartRequest > 2500) {
932 DEBUG_WARN (
"Restart");
961 memcpy (&recvdCRC, crc,
sizeof (uint32_t));
964 DEBUG_VERBOSE (
"CRC32 = Calc: 0x%08X Recvd: 0x%08X Length: %d", _crc, recvdCRC, count);
965 return (_crc == recvdCRC);
975 struct __attribute__ ((packed, aligned (1))) {
983 #define CHMSG_LEN sizeof(clientHello_msg)
1002 DEBUG_ERROR (
"Error calculating public ECDH key");
1013 clientHello_msg.publicKey[i] = key[i];
1020 random = random | 0x00000001U;
1021 DEBUG_DBG (
"Signal sleepy node");
1023 random = random & 0xFFFFFFFEU;
1024 DEBUG_DBG (
"Signal non sleepy node");
1034 memcpy (aad, (uint8_t*)&clientHello_msg, addDataLen);
1042 aad, sizeof (aad), clientHello_msg.tag,
TAG_LENGTH)) {
1043 DEBUG_ERROR (
"Error during encryption");
1052 DEBUG_INFO (
" -------> CLIENT HELLO");
1058 struct __attribute__ ((packed, aligned (1))) {
1065 static const uint8_t
CRMSG_LEN =
sizeof (clockRequest_msg);
1076 memcpy (&(clockRequest_msg.t1), &(
node.
t1), sizeof (int64_t));
1079 DEBUG_DBG (
"T1: %llu",
node.
t1);
1084 memcpy (aad, (uint8_t*)&clockRequest_msg, addDataLen);
1092 aad, sizeof (aad), clockRequest_msg.tag,
TAG_LENGTH)) {
1093 DEBUG_ERROR (
"Error during encryption");
1097 DEBUG_VERBOSE (
"Encrypted Clock Request message: %s",
printHexBuffer ((uint8_t*)&clockRequest_msg,
CRMSG_LEN));
1099 DEBUG_INFO (
" -------> CLOCK REQUEST");
1110 struct __attribute__ ((packed, aligned (1))) {
1116 } clockResponse_msg;
1118 #define CRSMSG_LEN sizeof(clockResponse_msg)
1120 memcpy (&clockResponse_msg, buf, count);
1125 memcpy (aad, buf, addDataLen);
1135 aad, sizeof (aad), clockResponse_msg.tag,
TAG_LENGTH)) {
1136 DEBUG_ERROR (
"Error during decryption");
1140 DEBUG_VERBOSE (
"Decripted Clock Response message: %s",
printHexBuffer ((uint8_t*)&clockResponse_msg, packetLen));
1143 node.
t2 = clockResponse_msg.t2;
1144 node.
t3 = clockResponse_msg.t3;
1148 DEBUG_WARN (
"Message too short");
1152 memcpy (&clockResponse_msg, buf, count);
1163 DEBUG_DBG (
"T1: %llu",
node.
t1);
1164 DEBUG_DBG (
"T2: %llu",
node.
t2);
1165 DEBUG_DBG (
"T3: %llu",
node.
t3);
1166 DEBUG_DBG (
"T4: %llu",
node.
t4);
1167 DEBUG_DBG (
"Offest adjusted to %lld ms, Roundtrip delay is %lld", offset,
TimeManager.
getDelay ());
1183 return millis () / 1000;
1203 struct __attribute__ ((packed, aligned (1))) {
1212 #define SHMSG_LEN sizeof(serverHello_msg)
1217 DEBUG_WARN (
"Message too short");
1221 memcpy (&serverHello_msg, buf, count);
1226 memcpy (aad, (uint8_t*)&serverHello_msg, addDataLen);
1234 aad, sizeof (aad), serverHello_msg.tag,
TAG_LENGTH)) {
1235 DEBUG_ERROR (
"Error during decryption");
1241 bool cError =
Crypto.
getDH2 (serverHello_msg.publicKey);
1244 DEBUG_ERROR (
"DH2 error");
1248 memcpy (&nodeId, &serverHello_msg.nodeId, sizeof (uint16_t));
1261 if (!controlMessage) {
1271 if (controlMessage) {
1274 DEBUG_VERBOSE (
"%s data sent: %s", encrypt ?
"Encrypted" :
"Unencrypted",
printHexBuffer (
data, len));
1293 DEBUG_VERBOSE (
"Node is non sleepy. Sleep rejected");
1308 uint8_t nodeId_idx = 1;
1309 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1310 uint8_t encoding_idx = counter_idx +
sizeof (int16_t);
1311 uint8_t data_idx = encoding_idx +
sizeof (int8_t);
1313 uint8_t packet_length = data_idx + len;
1319 if (controlMessage) {
1325 memcpy (buf + nodeId_idx, &nodeId,
sizeof (uint16_t));
1327 if (!controlMessage) {
1336 memcpy (buf + counter_idx, &counter,
sizeof (uint16_t));
1339 buf[encoding_idx] = (uint8_t)payloadEncoding;
1341 memcpy (buf + data_idx,
data, len);
1343 DEBUG_INFO (
" -------> UNENCRYPTED DATA");
1344 DEBUG_VERBOSE (
"Unencrypted data message: %s",
printHexBuffer (buf, packet_length));
1346 #if DEBUG_LEVEL >= VERBOSE
1353 DEBUG_ERROR (
"Error saving data on RTC");
1378 uint8_t length_idx = iv_idx +
IV_LENGTH;
1379 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1380 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1381 uint8_t encoding_idx;
1383 if (!controlMessage) {
1384 encoding_idx = counter_idx +
sizeof (int16_t);
1385 data_idx = encoding_idx +
sizeof (int8_t);
1387 data_idx = counter_idx +
sizeof (int16_t);
1389 uint8_t tag_idx = data_idx + len;
1396 if (controlMessage) {
1406 memcpy (buf + nodeId_idx, &nodeId,
sizeof (uint16_t));
1408 if (!controlMessage) {
1417 memcpy (buf + counter_idx, &counter,
sizeof (uint16_t));
1420 buf[encoding_idx] = payloadEncoding;
1422 memcpy (buf + data_idx,
data, len);
1424 uint16_t packet_length = tag_idx;
1426 memcpy (buf + length_idx, &packet_length,
sizeof (uint16_t));
1428 DEBUG_VERBOSE (
"Data message: %s",
printHexBuffer (buf, packet_length));
1429 DEBUG_DBG (
"Encoding: 0x%02X", payloadEncoding);
1431 uint8_t* crypt_buf = buf + length_idx;
1433 size_t cryptLen = packet_length - 1 -
IV_LENGTH;
1438 memcpy (aad, buf, addDataLen);
1446 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1447 DEBUG_ERROR (
"Error during encryption");
1453 if (controlMessage) {
1454 DEBUG_INFO (
" -------> CONTROL MESSAGE");
1456 DEBUG_INFO (
" -------> DATA");
1458 #if DEBUG_LEVEL >= VERBOSE
1465 DEBUG_ERROR (
"Error saving data on RTC");
1476 DEBUG_DBG (
"Get Sleep command received");
1485 if (
sendData (buffer, bufLength,
true)) {
1486 DEBUG_DBG (
"Sleep time is %d seconds",
sleepTime);
1490 DEBUG_WARN (
"Error sending version response");
1499 DEBUG_DBG (
"Get Name command received");
1509 nameLen = strlen (name);
1511 DEBUG_WARN (
"Emprty name");
1519 if (
sendData (buffer, bufLength,
true)) {
1520 DEBUG_DBG (
"Node name is %s", name ? name :
"NULL name");
1524 DEBUG_WARN (
"Error sending name response");
1535 struct __attribute__ ((packed, aligned (1))) {
1540 } nodeNameSetResponse_msg;
1542 const unsigned int NNSRMSG_LEN =
sizeof (nodeNameSetResponse_msg);
1544 if (len < NNSRMSG_LEN) {
1545 DEBUG_WARN (
"Message too short");
1548 memcpy (&nodeNameSetResponse_msg,
data, len);
1550 const uint8_t addDataLen = 1 +
IV_LENGTH;
1553 memcpy (aad, (uint8_t*)&nodeNameSetResponse_msg, addDataLen);
1561 aad, sizeof (aad), nodeNameSetResponse_msg.tag,
TAG_LENGTH)) {
1562 DEBUG_ERROR (
"Error during decryption");
1566 DEBUG_VERBOSE (
"Decrypted Node Name Set response message: %s",
printHexBuffer ((uint8_t*)&nodeNameSetResponse_msg, NNSRMSG_LEN -
TAG_LENGTH));
1568 if (nodeNameSetResponse_msg.errorCode !=
NAME_OK) {
1569 DEBUG_WARN (
"Name error: %d", nodeNameSetResponse_msg.errorCode);
1571 DEBUG_DBG (
"Name set correctly");
1581 DEBUG_DBG (
"Set Name command received");
1604 if (
sendData (buffer, bufLength,
true)) {
1609 DEBUG_WARN (
"Error sending name response");
1618 size_t nameLength = strlen (name);
1620 DEBUG_INFO (
"Setting node name to %s. Size: %d", name, nameLength);
1637 uint8_t nodeId_idx = iv_idx +
IV_LENGTH;
1638 uint8_t nodeName_idx = nodeId_idx +
sizeof (int16_t);
1639 uint8_t tag_idx = nodeName_idx + nameLength;
1641 size_t packet_length = 1 +
IV_LENGTH +
sizeof (int16_t) + nameLength;
1650 memcpy (buf + nodeId_idx, &nodeId,
sizeof (uint16_t));
1652 memcpy (buf + nodeName_idx, name, nameLength);
1654 DEBUG_VERBOSE (
"Set node name message: %s",
printHexBuffer (buf, packet_length));
1656 uint8_t* crypt_buf = buf + nodeId_idx;
1658 size_t cryptLen = packet_length - 1 -
IV_LENGTH;
1663 memcpy (aad, buf, addDataLen);
1671 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1672 DEBUG_ERROR (
"Error during encryption");
1678 #if DEBUG_LEVEL >= VERBOSE
1685 DEBUG_INFO (
"-------> NODE NAME SEND");
1695 DEBUG_DBG (
"Set Identify command received");
1698 DEBUG_WARN (
"IDENTIFY");
1715 DEBUG_DBG (
"Reset Config command received");
1725 if ((result =
sendData (buffer, bufLength,
true))) {
1726 DEBUG_DBG (
"Reset Config about to be executed",
sleepTime);
1729 DEBUG_WARN (
"Error sending Reset Config response");
1748 memset (&rtcmem_data_storage, 0,
sizeof (
rtcmem_data));
1751 DEBUG_DBG (
"RTC Cleared");
1758 DEBUG_DBG (
"Set Sleep command received");
1760 if (!SPIFFS.begin ()) {
1761 DEBUG_ERROR (
"Error mounting flash");
1765 DEBUG_WARN (
"Error loading configuration");
1772 DEBUG_DBG (
"Sleep time requested: %d",
sleepTime);
1778 DEBUG_DBG (
"Saved config data after set sleep time command");
1780 DEBUG_WARN (
"Error saving data after set sleep time command");
1788 if (
sendData (buffer, bufLength,
true)) {
1789 DEBUG_DBG (
"Sleep time is %d seconds",
sleepTime);
1793 DEBUG_WARN (
"Error sending version response");
1806 DEBUG_DBG (
"Version command received");
1807 if (
sendData (buffer, bufLength,
true)) {
1812 DEBUG_WARN (
"Error sending version response");
1818 const uint8_t MAX_OTA_RESPONSE_LENGTH = 4;
1820 uint8_t responseBuffer[MAX_OTA_RESPONSE_LENGTH];
1824 static char md5buffer[33];
1826 static uint16_t numMsgs;
1827 static uint32_t otaSize;
1828 static uint16_t oldIdx;
1829 static bool otaRecoverRequested =
false;
1830 static MD5Builder _md5;
1831 uint8_t* dataPtr = (uint8_t*)(
data + 1);
1832 uint8_t dataLen = len - 1;
1835 DEBUG_ERROR (
"OTA message is too short: %u bytes", dataLen + 1);
1839 memcpy (&msgIdx, dataPtr,
sizeof (uint16_t));
1840 dataPtr +=
sizeof (uint16_t);
1841 dataLen -=
sizeof (uint16_t);
1842 DEBUG_WARN (
"OTA message #%u", msgIdx);
1844 if (msgIdx != (oldIdx + 1)) {
1845 if (!otaRecoverRequested) {
1846 otaRecoverRequested =
true;
1849 memcpy (responseBuffer + 2, (uint8_t*)&oldIdx,
sizeof (oldIdx));
1850 sendData (responseBuffer, 4,
true);
1851 DEBUG_ERROR (
"%u OTA messages missing before %u", msgIdx - oldIdx - 1, msgIdx);
1858 otaRecoverRequested =
false;
1865 DEBUG_ERROR (
"OTA message #0 is too short: %u bytes", dataLen + 3);
1868 memcpy (&otaSize, dataPtr,
sizeof (uint32_t));
1869 DEBUG_INFO (
"OTA size: %u bytes", otaSize);
1870 dataPtr +=
sizeof (uint32_t);
1871 dataLen -=
sizeof (uint32_t);
1872 memcpy (&numMsgs, dataPtr,
sizeof (uint16_t));
1873 DEBUG_INFO (
"Number of OTA messages: %u", numMsgs);
1874 dataPtr +=
sizeof (uint16_t);
1875 dataLen -=
sizeof (uint16_t);
1876 memcpy (md5buffer, dataPtr, 32);
1877 md5buffer[32] =
'\0';
1878 DEBUG_VERBOSE (
"MD5: %s",
printHexBuffer ((uint8_t*)md5buffer, 32));
1884 if (
sendData (responseBuffer, 2,
true)) {
1885 DEBUG_WARN (
"OTA STARTED");
1888 if (!Update.begin (otaSize)) {
1889 DEBUG_ERROR (
"Error begginning OTA. OTA size: %u", otaSize);
1893 Update.runAsync (
true);
1895 if (!Update.setMD5 (md5buffer)) {
1896 DEBUG_ERROR (
"Error setting MD5");
1902 static size_t totalBytes = 0;
1904 _md5.add (dataPtr, dataLen);
1906 size_t numBytes = Update.write (dataPtr, dataLen);
1907 totalBytes += dataLen;
1908 DEBUG_WARN (
"%u bytes written. Total %u", numBytes, totalBytes);
1914 sendData (responseBuffer, 2,
true);
1915 DEBUG_ERROR (
"OTA error. Message 0 not received");
1921 StreamString otaErrorStr;
1923 DEBUG_INFO (
"OTA end");
1925 DEBUG_DBG (
"OTA MD5 %s", _md5.toString ().c_str ());
1926 _md5.getChars (md5calc);
1927 if (!memcmp (md5calc, md5buffer, 32)) {
1930 sendData (responseBuffer, 2,
true);
1931 DEBUG_WARN (
"OTA MD5 check OK");
1935 sendData (responseBuffer, 2,
true);
1936 DEBUG_ERROR (
"OTA MD5 check failed");
1939 while (!Update.isFinished ()) {
1945 if (Update.end ()) {
1948 sendData (responseBuffer, 2,
true);
1949 uint8_t otaErrorCode = Update.getError ();
1950 DEBUG_WARN (
"OTA Finished OK");
1951 DEBUG_WARN (
"OTA eror code: %d", otaErrorCode);
1960 sendData (responseBuffer, 2,
true);
1961 uint8_t otaErrorCode = Update.getError ();
1962 Update.printError (otaErrorStr);
1963 otaErrorStr.trim ();
1964 DEBUG_ERROR (
"OTA Failed");
1965 DEBUG_WARN (
"OTA eror code: %s", otaErrorStr.c_str ());
1966 Serial.println (
"OTA failed");
1980 DEBUG_ERROR (
"Error saving data on RTC");
1982 DEBUG_WARN (
"Reset configuration data in RTC memory");
2011 DEBUG_ERROR (
"Error processing OTA");
2026 uint8_t length_idx = iv_idx +
IV_LENGTH;
2027 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
2028 uint8_t encoding_idx;
2031 encoding_idx = nodeId_idx +
sizeof (int16_t);
2032 data_idx = encoding_idx +
sizeof (int8_t);
2034 data_idx = nodeId_idx +
sizeof (int16_t);
2041 memcpy (aad, buf, addDataLen);
2051 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
2052 DEBUG_ERROR (
"Error during decryption");
2059 DEBUG_INFO (
"Control command");
2060 DEBUG_VERBOSE (
"Data: %s",
printHexBuffer (&buf[data_idx], tag_idx - data_idx));
2064 DEBUG_VERBOSE (
"Sending data notification. Payload length: %d", tag_idx - data_idx);
2080 DEBUG_WARN (
"Invalidate key request. Reason: %u", buf[1]);
2081 uint8_t reason = buf[1];
2091 DEBUG_INFO (
"Reveived message. Origin MAC: %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
2092 DEBUG_VERBOSE (
"Received data: %s",
printHexBuffer (
const_cast<uint8_t*
>(buf), count));
2096 DEBUG_ERROR (
"Empty message received");
2102 DEBUG_ERROR (
"Message comes not from gateway");
2108 DEBUG_INFO (
" <------- SERVER HELLO");
2126 DEBUG_ERROR (
"Error saving data on RTC");
2133 #if DEBUG_LEVEL >= INFO
2146 if (invalidateReason < KEY_EXPIRED && dataMessageSentLength > 0) {
2169 DEBUG_INFO (
" <------- INVALIDATE KEY");
2180 DEBUG_INFO (
" <------- DOWNSTREAM DATA SET");
2182 DEBUG_INFO (
"Downstream Data set OK");
2186 DEBUG_INFO (
" <------- DOWNSTREAM DATA GET");
2188 DEBUG_INFO (
"Downstream Data set OK");
2192 DEBUG_INFO (
" <------- DOWNSTREAM CONTROL DATA");
2194 DEBUG_INFO (
"Downstream Data OK");
2198 DEBUG_INFO (
" <------- CLOCK RESPONSE");
2201 DEBUG_INFO (
"Clock Response OK");
2206 DEBUG_INFO (
" <------- SET NODE NAME RESULT");
2208 DEBUG_INFO (
"Set Node Name OK");
2217 DEBUG_DBG (
"SENDStatus OK");
2222 DEBUG_ERROR (
"Error saving data on RTC");