16 #include <MD5Builder.h>
23 #include <StreamString.h>
24 #include <ArduinoJson.h>
32 TimerHandle_t ledTimer;
33 #elif defined(ESP8266)
50 DEBUG_WARN (
"Config file %s deleted. Restarting");
63 DEBUG_WARN (
"Message Len %d\n", len);
66 DEBUG_WARN (
"Error sending restart");
68 DEBUG_WARN (
"Restart sent");
100 data->lastMessageCounter = 0;
103 memset (
data->gateway, 0, 6);
106 data->sleepy =
false;
107 data->nodeKeyValid =
false;
108 data->broadcastKeyRequested =
false;
109 data->broadcastKeyValid =
false;
110 DEBUG_DBG (
"RTC Cleared");
114 Serial.println (
"RTC MEM DATA:");
116 Serial.printf (
" -- CRC: %s\n",
printHexBuffer ((uint8_t*)&(
data->crc32), sizeof (uint32_t)));
118 Serial.printf (
" -- Node key is %svalid\n",
data->nodeKeyValid ?
"" :
"NOT ");
119 Serial.printf (
" -- Node status is %d: %s\n",
data->nodeRegisterStatus,
data->nodeRegisterStatus ==
REGISTERED ?
"REGISTERED" :
"NOT REGISTERED");
120 Serial.printf (
" -- Node name: %s\n",
data->nodeName);
121 Serial.printf (
" -- Last message counter: %d\n",
data->lastMessageCounter);
122 Serial.printf (
" -- Last control counter: %d\n",
data->lastControlCounter);
123 Serial.printf (
" -- Last downlink counter: %d\n",
data->lastDownlinkMsgCounter);
124 Serial.printf (
" -- NodeID: %d\n",
data->nodeId);
125 Serial.printf (
" -- Channel: %d\n",
data->channel);
126 Serial.printf (
" -- RSSI: %d\n",
data->rssi);
127 Serial.printf (
" -- Network name: %s\n",
data->networkName);
129 Serial.printf (
" -- Gateway: %s\n",
mac2str (
data->gateway, gwAddress));
130 Serial.printf (
" -- Comm errors: %d\n",
data->commErrors);
132 Serial.printf (
" -- Gateway address: %s\n",
mac2str (gateway, gwAddress));
134 Serial.printf (
" -- Mode: %s\n",
data->sleepy ?
"sleepy" :
"non sleepy");
136 Serial.printf (
" -- Broadcast key is %s and %s requested\n",
137 data->broadcastKeyValid ?
"valid" :
"not valid",
138 data->broadcastKeyRequested ?
"is" :
"is not");
140 Serial.println (
"rtcmem_data pointer is NULL");
144 #if USE_FLASH_INSTEAD_RTC
145 const char* RTC_DATA_FILE =
"/context.bin";
149 clock_t start_load = millis ();
154 if (FILESYSTEM.exists (RTC_DATA_FILE)) {
155 DEBUG_DBG (
"Opening %s file", RTC_DATA_FILE);
156 File contextFile = FILESYSTEM.open (RTC_DATA_FILE,
"r");
158 DEBUG_DBG (
"%s opened", RTC_DATA_FILE);
159 size_t size = contextFile.size ();
161 DEBUG_WARN (
"File size error. Expected %d bytes. Got %d",
sizeof (
rtcmem_data_t), size);
162 contextFile.close ();
163 FILESYSTEM.remove (RTC_DATA_FILE);
166 size = contextFile.readBytes ((
char*)&context,
sizeof (
rtcmem_data_t));
167 contextFile.close ();
169 DEBUG_WARN (
"File read error. Expected %d bytes. Got %d",
sizeof (
rtcmem_data_t), size);
171 FILESYSTEM.remove (RTC_DATA_FILE);
174 if (!
checkCRC ((uint8_t*)context.nodeKey, sizeof (
rtcmem_data_t) -
sizeof (uint32_t), &context.crc32)) {
175 DEBUG_WARN (
"RTC Data is not valid. Wrong CRC");
177 FILESYSTEM.remove (RTC_DATA_FILE);
201 DEBUG_DBG (
"Set %s mode",
node.
getSleepy () ?
"sleepy" :
"non sleepy");
202 #if DEBUG_LEVEL >= VERBOSE
207 DEBUG_WARN (
"Error opening file %s", RTC_DATA_FILE);
208 FILESYSTEM.remove (RTC_DATA_FILE);
212 DEBUG_WARN (
"%s do not exist", RTC_DATA_FILE);
216 DEBUG_DBG (
"Load process finished in %lu ms", millis () - start_load);
226 DEBUG_ERROR (
"Error reading RTC memory");
235 DEBUG_DBG (
"RTC Data is not valid");
259 DEBUG_DBG (
"Set %s mode",
node.
getSleepy () ?
"sleepy" :
"non sleepy");
260 #if DEBUG_LEVEL >= VERBOSE
272 bool json_correct =
false;
276 File configFile = FILESYSTEM.open (
CONFIG_FILE,
"r");
281 const size_t capacity = JSON_ARRAY_SIZE (32) + JSON_OBJECT_SIZE (7) + 110;
282 DynamicJsonDocument doc (capacity);
283 DeserializationError error = deserializeJson (doc, configFile);
285 DEBUG_ERROR (
"Failed to parse file");
287 DEBUG_DBG (
"JSON file parsed");
291 if (doc.containsKey(
"type")){
292 if (!strcmp(
"node",doc[
"type"])) {
293 if (doc.containsKey (
"networkName") && doc.containsKey (
"networkKey")
294 && doc.containsKey (
"sleepTime")) {
299 DEBUG_ERROR (
"Wrong configuration. Removing file %s",
CONFIG_FILE);
309 JsonArray netKeyJson = doc[
"networkKey"];
311 DEBUG_WARN (
"Error in stored network key. Expected length: %d, actual length %d",
KEY_LENGTH, netKeyJson.size ());
323 if (doc.containsKey (
"gateway")) {
324 strncpy (gwAddrStr, doc[
"gateway"],
sizeof (gwAddrStr));
330 DEBUG_VERBOSE (
"Configuration successfuly read");
333 DEBUG_DBG (
"==== EnigmaIOT Node Configuration ====");
337 DEBUG_DBG (
"Gateway: %s", gwAddrStr);
341 serializeJsonPretty (doc, output);
343 DEBUG_DBG (
"JSON file %s", output.c_str ());
359 File configFile = FILESYSTEM.open (
CONFIG_FILE,
"w");
361 DEBUG_WARN (
"failed to open config file %s for writing",
CONFIG_FILE);
365 const size_t capacity = JSON_ARRAY_SIZE (32) + JSON_OBJECT_SIZE (7) + 110;
366 DynamicJsonDocument doc (capacity);
371 doc[
"type"] =
"node";
373 JsonArray netKeyJson = doc.createNestedArray (
"networkKey");
378 doc[
"gateway"] = gwAddrStr;
381 if (serializeJson (doc, configFile) == 0) {
382 DEBUG_ERROR (
"Failed to write to file");
389 serializeJsonPretty (doc, output);
391 DEBUG_DBG (
"%s", output.c_str ());
397 DEBUG_DBG (
"Configuration saved to flash. %u bytes", configFile.size ());
398 #if DEBUG_LEVEL >= DBG
406 #if USE_FLASH_INSTEAD_RTC
408 clock_t start_save = millis ();
412 File contextFile = FILESYSTEM.open (RTC_DATA_FILE,
"w");
414 DEBUG_WARN (
"failed to open config file %s for writing", RTC_DATA_FILE);
418 contextFile.flush ();
419 size_t size = contextFile.size ();
420 contextFile.close ();
421 DEBUG_DBG (
"Write configuration data to file %s in flash. %u bytes", RTC_DATA_FILE, size);
423 #if DEBUG_LEVEL >= VERBOSE
426 DEBUG_DBG (
"Save process finished in %lu ms", millis () - start_save);
437 DEBUG_WARN (
"Cannot write to RTC memory");
443 DEBUG_DBG (
"Write configuration data to RTC memory");
444 #if DEBUG_LEVEL >= VERBOSE
453 rtcmem_data_storage.crc32 =
calculateCRC32 ((uint8_t*)rtcmem_data_storage.nodeKey, sizeof (
rtcmem_data) -
sizeof (uint32_t));
455 #if DEBUG_LEVEL >= VERBOSE
465 if (!FILESYSTEM.begin ()) {
466 DEBUG_ERROR (
"Error on FILESYSTEM.begin()");
469 DEBUG_WARN (
"About to format Flash");
470 if (FILESYSTEM.format()) {
471 DEBUG_WARN (
"Filesystem formatted");
476 DEBUG_ERROR (
"Error on FILESYSTEM.format()",
CONFIG_FILE);
482 AsyncWebServer server (80);
486 bool regexResult =
true;
489 char sleepy[5] =
"10";
493 wifiManager =
new AsyncWiFiManager (&server, &dns);
494 #if DEBUG_LEVEL == NONE
500 AsyncWiFiManagerParameter sleepyParam (
"sleepy",
"Sleep Time", sleepy, 5,
"required type=\"number\" min=\"0\" max=\"13600\" step=\"1\"");
501 AsyncWiFiManagerParameter
nodeNameParam (
"nodename",
"Node Name", nodeName,
NODE_NAME_LENGTH,
"type=\"text\" pattern=\"^[^/\\\\]+$\" maxlength=32");
503 wifiManager->setCustomHeadElement (
"<style>input:invalid {border: 2px dashed red;input:valid{border: 2px solid black;}</style>");
514 wifiManager->setTryConnectDuringConfigPortal (
false);
517 snprintf (apname, 64,
"EnigmaIoTNode%06x", ESP.getChipId ());
520 snprintf (apname, 64,
"EnigmaIoTNode%06x", (uint32_t)(ESP.getEfuseMac () & (uint64_t)0x0000000000FFFFFF));
523 DEBUG_VERBOSE (
"Start AP: %s", apname);
525 boolean result =
wifiManager->startConfigPortal (apname, NULL);
527 DEBUG_DBG (
"==== Config Portal result ====");
529 DEBUG_DBG (
"Network Name: %s", WiFi.SSID ().c_str ());
531 station_config wifiConfig;
532 if (!wifi_station_get_config (&wifiConfig)) {
533 DEBUG_WARN (
"Error getting WiFi config");
535 DEBUG_DBG (
"WiFi password: %s", wifiConfig.password);
536 const char* netkey = (
char*)(wifiConfig.password);
538 wifi_config_t wifiConfig;
539 if (esp_wifi_get_config (WIFI_IF_STA, &wifiConfig)) {
540 DEBUG_WARN (
"Error getting WiFi config");
542 DEBUG_WARN (
"WiFi password: %.*s", 64, wifiConfig.sta.password);
543 const char* netkey = (
char*)(wifiConfig.sta.password);
545 DEBUG_DBG (
"Network Key: %s", netkey);
546 DEBUG_DBG (
"Sleppy time: %s", sleepyParam.getValue ());
549 data->lastMessageCounter = 0;
552 DEBUG_DBG (
"Stored network key before hash: %.*s",
KEY_LENGTH, (
char*)(
data->networkKey));
559 DEBUG_DBG (
"Temp network name: %s", WiFi.SSID ().c_str ());
561 DEBUG_DBG (
"Stored network name: %s",
data->networkName);
564 std::regex sleepTimeRegex (
"(\\d)+");
565 regexResult = std::regex_match (sleepyParam.getValue (), sleepTimeRegex);
568 DEBUG_DBG (
"Sleep time check ok");
569 int sleepyVal = atoi (sleepyParam.getValue ());
573 data->sleepTime = sleepyVal;
576 DEBUG_WARN (
"Sleep time parameter error");
585 std::regex nodeNameRegex (
"^[^/\\\\]+$");
586 regexResult = std::regex_match (
nodeNameParam.getValue (), nodeNameRegex);
587 #elif defined ESP8266
590 DEBUG_WARN (
"Node name parameter error. Contains '/'");
593 DEBUG_WARN (
"Node name parameter error. Contains '\\'");
598 DEBUG_DBG (
"Node name: %s",
data->nodeName);
600 DEBUG_WARN (
"Node name parameter error");
604 data->nodeKeyValid =
false;
619 digitalWrite (*(
int*)led, !digitalRead (*(
int*)led));
621 bool led_on = !digitalRead (
localLed);
622 DEBUG_VERBOSE (
"Change LED %d to %d",
localLed, led_on);
630 DEBUG_INFO (
"Start flash");
633 ledTimer = xTimerCreate (
"led_flash", pdMS_TO_TICKS (period), pdTRUE, (
void*)0, &
flashLed);
634 if (xTimerStart (ledTimer, 0) != pdPASS) {
635 DEBUG_WARN (
"Problem starting LED timer");
638 #elif defined (ESP8266)
639 ets_timer_disarm (&ledTimer);
642 ets_timer_arm_new (&ledTimer, period,
true,
true);
651 xTimerStop (ledTimer, 0);
652 xTimerDelete (ledTimer, 0);
654 #elif defined(ESP8266)
657 ets_timer_disarm (&ledTimer);
678 if (digitalRead (
resetPin) == LOW) {
679 time_t resetPinGrounded = millis ();
680 while (digitalRead (
resetPin) == LOW) {
682 DEBUG_WARN (
"Produce reset. Reset pin %d",
resetPin);
698 pinMode (
led, OUTPUT);
700 ets_timer_setfn (&ledTimer,
flashLed, (
void*)&
led);
716 DEBUG_DBG (
"Set %s mode: %s",
node.
getSleepy () ?
"sleepy" :
"non sleepy", sleepy ?
"sleepy" :
"non sleepy");
719 #if DEBUG_LEVEL >= DBG
725 if (gateway && networkKey) {
726 DEBUG_DBG (
"EnigmaIot started with config data con begin() call");
735 DEBUG_INFO (
"Starting from Flash");
736 if (!FILESYSTEM.begin ()) {
737 DEBUG_ERROR (
"Error mounting flash");
738 if (FILESYSTEM.format ()) {
739 DEBUG_INFO (
"FILESYSTEM formatted");
741 DEBUG_ERROR (
"Error formatting FILESYSTEM");
747 DEBUG_INFO (
"FILESYSTEM mounted");
751 DEBUG_DBG (
"Flash data loaded");
759 DEBUG_DBG (
"No flash data present. Starting Configuration AP");
762 DEBUG_DBG (
"Got configuration. Searching for Gateway");
764 DEBUG_DBG (
"Found EnigmaIOT Gateway. Storing configuration");
766 DEBUG_ERROR (
"Error saving data on flash");
774 DEBUG_WARN (
"No gateway found. Go to sleep for 120 seconds");
777 DEBUG_WARN (
"No gateway found. Restarting");
781 DEBUG_ERROR (
"Configuration error. Restarting");
797 if ((err_ok = esp_wifi_set_promiscuous (
true))) {
798 DEBUG_ERROR (
"Error setting promiscuous mode: %s", esp_err_to_name (err_ok));
801 DEBUG_ERROR (
"Error setting wifi channel: %s", esp_err_to_name (err_ok));
803 if ((err_ok = esp_wifi_set_promiscuous (
false))) {
804 DEBUG_ERROR (
"Error setting promiscuous mode off: %s", esp_err_to_name (err_ok));
812 int scanGatewaySSID (
char* name,
int& wifiIndex) {
813 uint32_t scanStarted;
815 const int MAX_INDEXES = 10;
817 int indexes[MAX_INDEXES];
820 DEBUG_WARN (
"SSID Name is NULL");
824 scanStarted = millis ();
825 numAP = WiFi.scanNetworks (
false,
false,
false, 300U);
826 DEBUG_DBG (
"Found %d APs in %lu ms", numAP, millis () - scanStarted);
827 DEBUG_DBG (
"Scan finished. Result = %d", WiFi.scanComplete ());
828 while (!(WiFi.scanComplete ()) && (millis () - scanStarted) > 1500) {
829 #if DEBUG_LEVEL >= DBG
831 Serial.printf (
"%lu.", millis () - scanStarted);
836 DEBUG_DBG (
"Scan finished. Result = %d", WiFi.scanComplete ());
838 DEBUG_DBG (
"Found %d APs in %lu ms", numAP, millis () - scanStarted);
840 wifi_ap_record_t* wifiAP;
842 for (
int i = 0; i < numAP; i++) {
843 wifiAP = (wifi_ap_record_t*)WiFi.getScanInfoByIndex (i);
844 DEBUG_DBG (
"Found AP %.*s with BSSID " MACSTR " and RSSI %d dBm", 32, wifiAP->ssid, MAC2STR (wifiAP->bssid), wifiAP->rssi);
845 if (!strncmp (name, (
char*)(wifiAP->ssid), 32)) {
846 indexes[numFound] = i;
848 if (numFound >= MAX_INDEXES) {
854 wifiIndex = indexes[0];
861 DEBUG_DBG (
"Searching for AP %s",
data->networkName);
868 DEBUG_DBG (
"Transmission disabled");
870 time_t scanStarted = millis ();
871 numWifi = WiFi.scanNetworks (
false,
false, 0, (uint8_t*)(
data->networkName));
872 while (!(WiFi.scanComplete () || (millis () - scanStarted) > 1500)) {
873 #if DEBUG_LEVEL >= DBG
875 Serial.printf (
"%lu.", millis () - scanStarted);
880 WiFiMode_t mode = WiFi.getMode ();
881 DEBUG_DBG (
"WiFi mode is %d. Restarting network interface after scan", mode);
882 WiFi.mode (WIFI_OFF);
885 numWifi = scanGatewaySSID (
data->networkName, wifiIndex);
888 DEBUG_DBG (
"Transmission enabled");
891 memcpy (prevGwAddr,
data->gateway, 6);
894 DEBUG_INFO (
"Gateway %s found: %d",
data->networkName, numWifi);
895 DEBUG_INFO (
"BSSID: %s", WiFi.BSSIDstr (wifiIndex).c_str ());
896 DEBUG_INFO (
"Channel: %d", WiFi.channel (wifiIndex));
897 DEBUG_INFO (
"RSSI: %d", WiFi.RSSI (wifiIndex));
898 data->channel = WiFi.channel (wifiIndex);
899 data->rssi = WiFi.RSSI (wifiIndex);
900 memcpy (
data->gateway, WiFi.BSSID (wifiIndex), 6);
902 if (shouldStoreData) {
903 DEBUG_DBG (
"Found gateway. Storing");
905 DEBUG_ERROR (
"Error saving data on RTC");
907 if (memcmp (prevGwAddr,
data->gateway, 6)) {
909 DEBUG_ERROR (
"Error saving data on flash");
917 wifi_set_channel (
data->channel);
920 if ((err_ok = esp_wifi_set_promiscuous (
true))) {
921 DEBUG_ERROR (
"Error setting promiscuous mode: %s", esp_err_to_name (err_ok));
923 if ((err_ok = esp_wifi_set_channel (
data->channel, WIFI_SECOND_CHAN_NONE))) {
924 DEBUG_ERROR (
"Error setting wifi channel: %s", esp_err_to_name (err_ok));
926 if ((err_ok = esp_wifi_set_promiscuous (
false))) {
927 DEBUG_ERROR (
"Error setting promiscuous mode off: %s", esp_err_to_name (err_ok));
934 DEBUG_WARN (
"Gateway %s not found",
data->networkName);
940 DEBUG_DBG (
"Communication layer uninitalized");
950 #ifdef ESP8266 // ESP32 does not have this limitation
951 uint64_t maxSleepTime = (ESP.deepSleepMax () / (uint64_t)1000000);
954 if (
sleepTime == 0 && !forceSleepForever) {
967 DEBUG_DBG (
"Max sleep time is %lu", (uint32_t)maxSleepTime);
973 DEBUG_DBG (
"Sleep time set to %d. Sleepy mode is %s",
978 DEBUG_WARN (
"Cannot set sleep time to %u seconds as this node started as non sleepy",
sleepTime);
986 DEBUG_DBG (
"Report RSSI and channel");
994 DEBUG_DBG (
"Sleep time is %d seconds",
sleepTime / 1000000);
998 DEBUG_WARN (
"Error sending version response");
1004 static unsigned long blueOntime;
1022 blueOntime = millis ();
1028 if ( millis () - blueOntime >
ledOnTime) {
1038 int64_t sleep_t = 0;
1042 if (sleep_t && sleep_t < 1000) {
1048 DEBUG_WARN (
"Go to sleep for %ld ms", (int32_t)(sleep_t / 1000L));
1050 DEBUG_WARN (
"Go to sleep indefinitely");
1052 DEBUG_WARN (
"%d", millis ());
1055 ESP.deepSleep (sleep_t);
1057 esp_deep_sleep (sleep_t);
1063 static time_t lastRegistration = millis ();
1073 DEBUG_ERROR (
"Error saving data on RTC");
1078 DEBUG_INFO (
"Registration timeout. Go to sleep for %lu ms", (uint32_t)(
RECONNECTION_PERIOD * 4 + rnd / 1000));
1098 lastRegistration = millis ();
1101 DEBUG_INFO (
"Random delay (%u)", rnd);
1111 uint8_t responseBuffer[2];
1115 DEBUG_INFO (
"OTA TIMEOUT");
1118 DEBUG_WARN (
"Restart due to OTA timeout");
1136 static time_t lastTimeSync;
1139 lastTimeSync = millis ();
1140 DEBUG_DBG (
"Clock Request");
1148 static bool restartSent =
false;
1150 DEBUG_WARN (
"Send restart");
1154 static unsigned long retartRequest = millis ();
1155 if (millis () - retartRequest > 2500) {
1156 DEBUG_WARN (
"Restart");
1185 memcpy (&recvdCRC, crc,
sizeof (uint32_t));
1188 DEBUG_VERBOSE (
"CRC32 = Calc: 0x%08X Recvd: 0x%08X Length: %d", _crc, recvdCRC, count);
1189 return (_crc == recvdCRC);
1199 struct __attribute__ ((packed, aligned (1))) {
1207 #define CHMSG_LEN sizeof(clientHello_msg)
1226 DEBUG_ERROR (
"Error calculating public ECDH key");
1237 clientHello_msg.publicKey[i] = key[i];
1244 random = random | 0x00000001U;
1245 DEBUG_DBG (
"Signal sleepy node");
1247 random = random & 0xFFFFFFFEU;
1248 DEBUG_DBG (
"Signal non sleepy node");
1252 random = random | 0x00000002U;
1254 DEBUG_DBG (
"Signal sleepy node");
1256 random = random & 0xFFFFFFFDU;
1258 DEBUG_DBG (
"Signal non sleepy node");
1268 memcpy (aad, (uint8_t*)&clientHello_msg, addDataLen);
1276 aad, sizeof (aad), clientHello_msg.tag,
TAG_LENGTH)) {
1277 DEBUG_ERROR (
"Error during encryption");
1286 DEBUG_INFO (
" -------> CLIENT HELLO");
1297 struct __attribute__ ((packed, aligned (1))) {
1306 static const uint8_t CRMSG_LEN =
sizeof (clockRequest_msg);
1322 DEBUG_INFO (
"Control message #%d", counter);
1324 memcpy (&(clockRequest_msg.counter), &counter, sizeof (uint16_t));
1328 memcpy (&(clockRequest_msg.t1), &t1, sizeof (int64_t));
1331 DEBUG_DBG (
"T1: %llu", t1);
1336 memcpy (aad, (uint8_t*)&clockRequest_msg, addDataLen);
1344 aad, sizeof (aad), clockRequest_msg.tag,
TAG_LENGTH)) {
1345 DEBUG_ERROR (
"Error during encryption");
1349 DEBUG_VERBOSE (
"Encrypted Clock Request message: %s",
printHexBuffer ((uint8_t*)&clockRequest_msg, CRMSG_LEN));
1351 DEBUG_INFO (
" -------> CLOCK REQUEST");
1359 DEBUG_ERROR (
"Error saving data on RTC");
1368 struct __attribute__ ((packed, aligned (1))) {
1376 } clockResponse_msg;
1378 uint64_t t1, t2, t3, t4;
1382 const unsigned int CRSMSG_LEN =
sizeof (clockResponse_msg);
1384 memcpy (&clockResponse_msg, buf, count);
1389 memcpy (aad, buf, addDataLen);
1399 aad, sizeof (aad), clockResponse_msg.tag,
TAG_LENGTH)) {
1400 DEBUG_ERROR (
"Error during decryption");
1404 DEBUG_VERBOSE (
"Decripted Clock Response message: %s",
printHexBuffer ((uint8_t*)&clockResponse_msg, count -
TAG_LENGTH));
1406 memcpy (&counter, &(clockResponse_msg.counter), sizeof (uint16_t));
1407 DEBUG_INFO (
"Downlink msg #%d", counter);
1410 DEBUG_INFO (
"Accepted");
1414 DEBUG_WARN (
"Downlink msg rejected");
1419 t1 = clockResponse_msg.t1;
1420 t2 = clockResponse_msg.t2;
1421 t3 = clockResponse_msg.t3;
1424 if (count < CRSMSG_LEN) {
1425 DEBUG_WARN (
"Message too short");
1429 memcpy (&clockResponse_msg, buf, count);
1438 DEBUG_VERBOSE (
"Clock Response message: %s",
printHexBuffer ((uint8_t*)&clockResponse_msg, CRSMSG_LEN -
TAG_LENGTH));
1440 DEBUG_DBG (
"T1: %llu", t1);
1441 DEBUG_DBG (
"T2: %llu", t2);
1442 DEBUG_DBG (
"T3: %llu", t3);
1443 DEBUG_DBG (
"T4: %llu", t4);
1444 DEBUG_INFO (
"Offest adjusted to %lld us, Roundtrip delay is %lld", offset,
TimeManager.
getDelay ());
1448 DEBUG_ERROR (
"Error saving data on RTC");
1478 struct __attribute__ ((packed, aligned (1))) {
1487 #define SHMSG_LEN sizeof(serverHello_msg)
1492 DEBUG_WARN (
"Message too short");
1496 memcpy (&serverHello_msg, buf, count);
1501 memcpy (aad, (uint8_t*)&serverHello_msg, addDataLen);
1509 aad, sizeof (aad), serverHello_msg.tag,
TAG_LENGTH)) {
1510 DEBUG_ERROR (
"Error during decryption");
1516 bool cError =
Crypto.
getDH2 (serverHello_msg.publicKey);
1519 DEBUG_ERROR (
"DH2 error");
1523 memcpy (&nodeId, &serverHello_msg.nodeId, sizeof (uint16_t));
1551 DEBUG_VERBOSE (
"%s data sent: %s", encrypt ?
"Encrypted" :
"Unencrypted",
printHexBuffer (
data, len));
1570 DEBUG_VERBOSE (
"Node is non sleepy. Sleep rejected");
1585 uint8_t nodeId_idx = 1;
1586 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1587 uint8_t encoding_idx = counter_idx +
sizeof (int16_t);
1588 uint8_t data_idx = encoding_idx +
sizeof (int8_t);
1590 uint8_t packet_length = data_idx + len;
1602 memcpy (buf + nodeId_idx, &nodeId,
sizeof (uint16_t));
1611 memcpy (buf + counter_idx, &counter,
sizeof (uint16_t));
1613 buf[encoding_idx] = (uint8_t)payloadEncoding;
1615 memcpy (buf + data_idx,
data, len);
1617 DEBUG_INFO (
" -------> UNENCRYPTED DATA");
1618 DEBUG_VERBOSE (
"Unencrypted data message: %s",
printHexBuffer (buf, packet_length));
1620 #if DEBUG_LEVEL >= VERBOSE
1627 DEBUG_ERROR (
"Error saving data on RTC");
1652 uint8_t length_idx = iv_idx +
IV_LENGTH;
1653 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1654 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1655 uint8_t encoding_idx;
1658 encoding_idx = counter_idx +
sizeof (int16_t);
1659 data_idx = encoding_idx +
sizeof (int8_t);
1661 data_idx = counter_idx +
sizeof (int16_t);
1663 uint8_t tag_idx = data_idx + len;
1682 memcpy (buf + nodeId_idx, &nodeId,
sizeof (uint16_t));
1703 DEBUG_INFO (
"Data message #%d", counter);
1705 DEBUG_INFO (
"Control message #%d", counter);
1708 memcpy (buf + counter_idx, &counter,
sizeof (uint16_t));
1710 buf[encoding_idx] = payloadEncoding;
1712 memcpy (buf + data_idx,
data, len);
1714 uint16_t packet_length = tag_idx;
1716 memcpy (buf + length_idx, &packet_length,
sizeof (uint16_t));
1718 DEBUG_VERBOSE (
"Data message: %s",
printHexBuffer (buf, packet_length));
1719 DEBUG_DBG (
"Encoding: 0x%02X", payloadEncoding);
1721 uint8_t* crypt_buf = buf + length_idx;
1723 size_t cryptLen = packet_length - 1 -
IV_LENGTH;
1728 memcpy (aad, buf, addDataLen);
1736 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1737 DEBUG_ERROR (
"Error during encryption");
1744 DEBUG_INFO (
" -------> CONTROL MESSAGE");
1746 DEBUG_INFO (
" -------> HA DISCOVERY MESSAGE");
1748 DEBUG_INFO (
" -------> DATA");
1750 #if DEBUG_LEVEL >= VERBOSE
1757 DEBUG_ERROR (
"Error saving data on RTC");
1765 if (!
data || !len) {
1766 DEBUG_WARN (
"Empty buffer");
1776 DEBUG_DBG (
"Get Sleep command received");
1786 DEBUG_DBG (
"Sleep time is %d seconds",
sleepTime);
1790 DEBUG_WARN (
"Error sending version response");
1799 DEBUG_DBG (
"Get Name command received");
1809 nameLen = strlen (name);
1811 DEBUG_WARN (
"Emprty name");
1820 DEBUG_DBG (
"Node name is %s", name ? name :
"NULL name");
1824 DEBUG_WARN (
"Error sending name response");
1835 struct __attribute__ ((packed, aligned (1))) {
1841 } nodeNameSetResponse_msg;
1845 const unsigned int NNSRMSG_LEN =
sizeof (nodeNameSetResponse_msg);
1847 if (len < NNSRMSG_LEN) {
1848 DEBUG_WARN (
"Message too short");
1851 memcpy (&nodeNameSetResponse_msg,
data, len);
1853 const uint8_t addDataLen = 1 +
IV_LENGTH;
1856 memcpy (aad, (uint8_t*)&nodeNameSetResponse_msg, addDataLen);
1864 aad, sizeof (aad), nodeNameSetResponse_msg.tag,
TAG_LENGTH)) {
1865 DEBUG_ERROR (
"Error during decryption");
1869 DEBUG_VERBOSE (
"Decrypted Node Name Set response message: %s",
printHexBuffer ((uint8_t*)&nodeNameSetResponse_msg, NNSRMSG_LEN -
TAG_LENGTH));
1871 memcpy (&counter, &(nodeNameSetResponse_msg.counter), sizeof (uint16_t));
1872 DEBUG_INFO (
"Downlink msg #%d", counter);
1875 DEBUG_INFO (
"Accepted");
1879 DEBUG_WARN (
"Downlink msg rejected");
1884 if (nodeNameSetResponse_msg.errorCode !=
NAME_OK) {
1885 DEBUG_WARN (
"Name error: %d", nodeNameSetResponse_msg.errorCode);
1887 DEBUG_DBG (
"Name set correctly");
1892 DEBUG_ERROR (
"Error saving data on RTC");
1903 DEBUG_DBG (
"Set Name command received");
1931 DEBUG_WARN (
"Error sending name response");
1940 size_t nameLength = strlen (name);
1942 DEBUG_INFO (
"Setting node name to %s. Size: %d", name, nameLength);
1960 uint8_t nodeId_idx = iv_idx +
IV_LENGTH;
1961 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1962 uint8_t nodeName_idx = counter_idx +
sizeof (int16_t);
1963 uint8_t tag_idx = nodeName_idx + nameLength;
1965 size_t packet_length = 1 +
IV_LENGTH +
sizeof (int16_t) +
sizeof (int16_t) + nameLength;
1982 DEBUG_INFO (
"Control message #%d", counter);
1984 memcpy (buf + counter_idx, &counter,
sizeof (uint16_t));
1986 memcpy (buf + nodeId_idx, &nodeId,
sizeof (uint16_t));
1988 memcpy (buf + nodeName_idx, name, nameLength);
1990 DEBUG_VERBOSE (
"Set node name message: %s",
printHexBuffer (buf, packet_length));
1992 uint8_t* crypt_buf = buf + nodeId_idx;
1994 size_t cryptLen = packet_length - 1 -
IV_LENGTH;
1999 memcpy (aad, buf, addDataLen);
2007 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
2008 DEBUG_ERROR (
"Error during encryption");
2014 #if DEBUG_LEVEL >= VERBOSE
2021 DEBUG_INFO (
"-------> NODE NAME SEND");
2025 DEBUG_ERROR (
"Error saving data on RTC");
2037 DEBUG_DBG (
"Set Identify command received");
2040 DEBUG_WARN (
"IDENTIFY");
2054 DEBUG_WARN (
"Restart due to command");
2063 DEBUG_DBG (
"Reset Config command received");
2074 DEBUG_DBG (
"Reset Config about to be executed",
sleepTime);
2077 DEBUG_WARN (
"Error sending Reset Config response");
2080 DEBUG_WARN (
"Send restart command before deleting config");
2097 DEBUG_WARN (
"Cannot write to RTC memory");
2106 memset (&rtcmem_data_storage, 0,
sizeof (
rtcmem_data));
2109 #if USE_FLASH_INSTEAD_RTC
2110 FILESYSTEM.begin ();
2111 FILESYSTEM.remove (RTC_DATA_FILE);
2115 DEBUG_DBG (
"RTC Cleared");
2122 DEBUG_DBG (
"Set Sleep command received");
2124 if (!FILESYSTEM.begin ()) {
2125 DEBUG_ERROR (
"Error mounting flash");
2129 DEBUG_WARN (
"Error loading configuration");
2136 DEBUG_DBG (
"Sleep time requested: %d",
sleepTime);
2142 DEBUG_DBG (
"Saved config data after set sleep time command");
2144 DEBUG_WARN (
"Error saving data after set sleep time command");
2153 DEBUG_DBG (
"Sleep time is %d seconds",
sleepTime);
2157 DEBUG_WARN (
"Error sending version response");
2170 DEBUG_DBG (
"Version command received");
2176 DEBUG_WARN (
"Error sending version response");
2182 const uint8_t MAX_OTA_RESPONSE_LENGTH = 4;
2184 uint8_t responseBuffer[MAX_OTA_RESPONSE_LENGTH];
2188 static char md5buffer[33];
2190 static uint16_t numMsgs;
2191 static uint32_t otaSize;
2192 static uint16_t oldIdx;
2193 static bool otaRecoverRequested =
false;
2194 static MD5Builder _md5;
2195 uint8_t* dataPtr = (uint8_t*)(
data + 1);
2196 uint8_t dataLen = len - 1;
2199 DEBUG_ERROR (
"OTA message is too short: %u bytes", dataLen + 1);
2203 memcpy (&msgIdx, dataPtr,
sizeof (uint16_t));
2204 dataPtr +=
sizeof (uint16_t);
2205 dataLen -=
sizeof (uint16_t);
2206 DEBUG_INFO (
"OTA message #%u", msgIdx);
2208 if (msgIdx != (oldIdx + 1)) {
2209 if (!otaRecoverRequested) {
2210 otaRecoverRequested =
true;
2213 memcpy (responseBuffer + 2, (uint8_t*)&oldIdx,
sizeof (oldIdx));
2215 DEBUG_ERROR (
"%u OTA messages missing before %u", msgIdx - oldIdx - 1, msgIdx);
2222 otaRecoverRequested =
false;
2229 DEBUG_ERROR (
"OTA message #0 is too short: %u bytes", dataLen + 3);
2232 memcpy (&otaSize, dataPtr,
sizeof (uint32_t));
2233 DEBUG_INFO (
"OTA size: %u bytes", otaSize);
2234 dataPtr +=
sizeof (uint32_t);
2235 dataLen -=
sizeof (uint32_t);
2236 memcpy (&numMsgs, dataPtr,
sizeof (uint16_t));
2237 DEBUG_INFO (
"Number of OTA messages: %u", numMsgs);
2238 dataPtr +=
sizeof (uint16_t);
2239 dataLen -=
sizeof (uint16_t);
2240 memcpy (md5buffer, dataPtr, 32);
2241 md5buffer[32] =
'\0';
2242 DEBUG_VERBOSE (
"MD5: %s",
printHexBuffer ((uint8_t*)md5buffer, 32));
2249 DEBUG_WARN (
"OTA STARTED");
2252 if (!Update.begin (otaSize)) {
2253 DEBUG_ERROR (
"Error begginning OTA. OTA size: %u", otaSize);
2257 Update.runAsync (
true);
2259 if (!Update.setMD5 (md5buffer)) {
2260 DEBUG_ERROR (
"Error setting MD5");
2266 static size_t totalBytes = 0;
2268 _md5.add (dataPtr, dataLen);
2271 #if DEBUG_LEVEL >= INFO
2274 Update.write (dataPtr, dataLen);
2276 totalBytes += dataLen;
2277 DEBUG_INFO (
"%u bytes written. Total %u", numBytes, totalBytes);
2284 DEBUG_ERROR (
"OTA error. Message 0 not received");
2290 StreamString otaErrorStr;
2292 DEBUG_INFO (
"OTA end");
2294 DEBUG_DBG (
"OTA MD5 %s", _md5.toString ().c_str ());
2295 _md5.getChars (md5calc);
2296 if (!memcmp (md5calc, md5buffer, 32)) {
2300 DEBUG_WARN (
"OTA MD5 check OK");
2305 DEBUG_ERROR (
"OTA MD5 check failed");
2308 while (!Update.isFinished ()) {
2314 if (Update.end ()) {
2319 DEBUG_WARN (
"OTA Finished OK");
2320 DEBUG_WARN (
"OTA eror code: %d", Update.getError ());
2333 Update.printError (otaErrorStr);
2334 otaErrorStr.trim ();
2335 DEBUG_ERROR (
"OTA Failed");
2336 DEBUG_WARN (
"OTA eror code: %s", otaErrorStr.c_str ());
2337 Serial.println (
"OTA failed");
2344 DEBUG_WARN (
"Restart after OTA");
2355 DEBUG_ERROR (
"Error saving data on RTC");
2357 DEBUG_WARN (
"Reset configuration data in RTC memory");
2369 DEBUG_DBG (
"%s control command", broadcast ?
"Broadcast" :
"Unicast");
2399 DEBUG_ERROR (
"Error processing OTA");
2410 DEBUG_WARN (
"Invalid broadcast key message. Incorrect length %d", count);
2414 int broadcastKey_idx = 1;
2433 uint8_t length_idx = iv_idx +
IV_LENGTH;
2434 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
2435 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
2436 uint8_t encoding_idx;
2439 encoding_idx = counter_idx +
sizeof (int16_t);
2440 data_idx = encoding_idx +
sizeof (int8_t);
2442 data_idx = counter_idx +
sizeof (int16_t);
2448 bool broadcast = (buf[0] & 0x80);
2454 const uint8_t addDataLen = 1 +
IV_LENGTH;
2457 memcpy (aad, buf, addDataLen);
2466 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
2467 DEBUG_ERROR (
"Error during decryption of broadcast message");
2475 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
2476 DEBUG_ERROR (
"Error during decryption");
2483 memcpy (&nodeId, &(buf[nodeId_idx]),
sizeof (uint16_t));
2485 memcpy (&counter, &(buf[counter_idx]),
sizeof (uint16_t));
2486 DEBUG_INFO (
"Downlink msg #%d", counter);
2499 DEBUG_WARN (
"Downlink msg rejected");
2507 DEBUG_ERROR (
"Error saving data on RTC");
2512 DEBUG_INFO (
"Control command");
2513 DEBUG_VERBOSE (
"Data: %s",
printHexBuffer (&buf[data_idx], tag_idx - data_idx));
2517 DEBUG_VERBOSE (
"Sending data notification. Payload length: %d", tag_idx - data_idx);
2541 DEBUG_WARN (
"Invalidate key request. Reason: %u", buf[1]);
2542 uint8_t reason = buf[1];
2552 DEBUG_INFO (
"Reveived message. Origin MAC: %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
2553 DEBUG_VERBOSE (
"Received data: %s",
printHexBuffer (
const_cast<uint8_t*
>(buf), count));
2557 DEBUG_ERROR (
"Empty message received");
2563 DEBUG_ERROR (
"Message doesn't come from gateway");
2569 DEBUG_INFO (
" <------- SERVER HELLO");
2587 DEBUG_INFO (
"Reset counters");
2589 DEBUG_ERROR (
"Error saving data on RTC");
2596 #if DEBUG_LEVEL >= INFO
2609 if (invalidateReason < KEY_EXPIRED && dataMessageSentLength > 0) {
2633 DEBUG_INFO (
" <------- INVALIDATE KEY");
2653 DEBUG_INFO (
" <------- DOWNSTREAM DATA SET");
2655 DEBUG_INFO (
"Downstream Data set OK");
2664 DEBUG_INFO (
" <------- DOWNSTREAM DATA GET");
2666 DEBUG_INFO (
"Downstream Data set OK");
2675 DEBUG_INFO (
" <------- DOWNSTREAM CONTROL DATA");
2677 DEBUG_INFO (
"Downstream Data OK");
2682 DEBUG_INFO (
" <------- CLOCK RESPONSE");
2685 DEBUG_INFO (
"Clock Response OK");
2690 DEBUG_INFO (
" <------- SET NODE NAME RESULT");
2692 DEBUG_INFO (
"Set Node Name OK");
2696 DEBUG_INFO (
" <------- BROADCAST KEY MESSAGE");
2698 DEBUG_INFO (
"Broadcast Key OK");
2707 DEBUG_DBG (
"SENDStatus OK");
2712 DEBUG_ERROR (
"Error saving data on RTC");