11 #include "libb64/cdecode.h"
12 #include <ArduinoJson.h>
26 #if SUPPORT_HA_DISCOVERY
33 #endif // SUPPORT_HA_DISCOVERY
43 DEBUG_INFO (
"Configuration saving activated");
48 DEBUG_INFO (
"Configuration reset started");
50 DEBUG_WARN (
"Configuration file removed");
62 pinMode (
txled, OUTPUT);
69 pinMode (
rxled, OUTPUT);
73 const void*
memstr (
const void* str,
size_t str_size,
74 const char* target,
size_t target_size) {
75 const uint8_t* pointer = (
const uint8_t*)str;
76 for (
size_t i = 0; i != str_size - target_size; ++i) {
77 if (!memcmp (pointer + i, target, target_size)) {
86 DEBUG_DBG (
"Build 'Get Version' message from: %s",
printHexBuffer (inputData, inputLen));
95 bool buildGetSleep (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
96 DEBUG_VERBOSE (
"Build 'Get Sleep' message from: %s",
printHexBuffer (inputData, inputLen));
106 DEBUG_VERBOSE (
"Build 'Set Identify' message from: %s",
printHexBuffer (inputData, inputLen));
115 bool buildGetRSSI (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
116 DEBUG_VERBOSE (
"Build 'Get RSSI' message from: %s",
printHexBuffer (inputData, inputLen));
125 bool buildGetName (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
126 DEBUG_VERBOSE (
"Build 'Get Node Name and Address' message from: %s",
printHexBuffer (inputData, inputLen));
135 bool buildSetName (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
136 DEBUG_VERBOSE (
"Build 'Set Node Name' message from: %s",
printHexBuffer (inputData, inputLen));
138 DEBUG_ERROR (
"Not enough space to build message");
142 DEBUG_ERROR (
"Name too short");
146 memcpy (
data + 1, inputData, inputLen);
147 dataLen = 1 + inputLen;
152 DEBUG_VERBOSE (
"Build 'Reset Config' message from: %s",
printHexBuffer (inputData, inputLen));
162 DEBUG_VERBOSE (
"Build 'Restart Node' message from: %s",
printHexBuffer (inputData, inputLen));
172 DEBUG_VERBOSE (
"Build 'Send Broadcast Key' message from: %s",
printHexBuffer (key, keyLen));
175 memcpy (
data + 1, key, keyLen);
176 dataLen = keyLen + 1;
187 char* tempData =
data;
188 size_t tempLen = len;
190 for (
int i = 0; i < 10; i++) {
192 if (tempData[i] !=
',') {
193 if (tempData[i] >=
'0' && tempData[i] <=
'9') {
194 strNum[i] = tempData[i];
196 DEBUG_ERROR (
"OTA message format error. Message number not found");
200 DEBUG_ERROR (
"OTA message format error, separator not found");
205 DEBUG_ERROR (
"OTA message format error, cannot find a number");
215 if (tempData[0] ==
',' && tempLen > 0) {
219 DEBUG_WARN (
"OTA message format warning. separator not found");
221 number = atoi (strNum);
224 DEBUG_DBG (
"Extracted number %d", number);
225 DEBUG_DBG (
"Resulting data %s",
data);
233 (c >=
'0' && c <=
'9')
234 || (c >=
'a' && c <=
'f')
239 bool buildOtaMsg (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
243 uint8_t* tempData =
data;
245 DEBUG_VERBOSE (
"Build 'OTA' message from: %s", inputData);
247 payload = (
char*)inputData;
248 payloadLen = inputLen;
255 uint16_t msgIdx = number;
259 memcpy (tempData, &msgIdx,
sizeof (uint16_t));
260 size_t decodedLen =
sizeof (uint8_t) +
sizeof (uint16_t);
261 tempData +=
sizeof (uint16_t);
263 DEBUG_INFO (
"OTA message number %u", msgIdx);
268 decodedLen += base64_decode_chars (payload, payloadLen, (
char*)(
data + 1 +
sizeof (uint16_t)));
275 DEBUG_ERROR (
"OTA message format error. Message #0 too short to be a MD5 string");
284 uint32_t fileSize = number;
286 memcpy (tempData, &fileSize,
sizeof (uint32_t));
287 tempData +=
sizeof (uint32_t);
288 decodedLen +=
sizeof (uint32_t);
296 uint16_t msgNum = number;
298 memcpy (tempData, &msgNum,
sizeof (uint16_t));
299 tempData +=
sizeof (uint16_t);
300 decodedLen +=
sizeof (uint16_t);
302 DEBUG_WARN (
"Number of OTA chunks %u", msgNum);
303 DEBUG_WARN (
"OTA length = %u bytes", fileSize);
306 if (payloadLen < 32) {
307 DEBUG_ERROR (
"OTA message format error. MD5 is too short: %d", payloadLen);
311 for (
size_t i = 0; i < 32; i++) {
313 DEBUG_ERROR (
"OTA message format error. MD5 string has no valid format");
316 *tempData = (uint8_t)payload[i];
325 DEBUG_ERROR (
"OTA message too long. %u bytes.", decodedLen);
328 dataLen = decodedLen;
329 DEBUG_VERBOSE (
"Payload has %u bytes of data: %s", dataLen,
printHexBuffer (
data, dataLen));
333 bool buildSetSleep (uint8_t*
data,
size_t& dataLen,
const uint8_t* inputData,
size_t inputLen) {
334 DEBUG_VERBOSE (
"Build 'Set Sleep' message from: %s",
printHexBuffer (inputData, inputLen));
336 DEBUG_ERROR (
"Not enough space to build message");
341 DEBUG_ERROR (
"Set sleep time value is empty");
345 for (
unsigned int i = 0; i < (inputLen - 1); i++) {
346 if (inputData[i] < 30 || inputData[i] >
'9') {
347 DEBUG_ERROR (
"Set sleep time value is not a number on position %d: %d", i, inputData[i]);
351 if (inputData[inputLen - 1] != 0) {
352 DEBUG_ERROR (
"Set sleep time value does not end with \\0");
356 uint32_t sleepTime = atoi ((
char*)inputData);
359 memcpy (
data + 1, &sleepTime,
sizeof (uint32_t));
369 DEBUG_DBG (
"Message to node %s with address %s", nodeName,
mac2str (
node->getMacAddress ()));
381 DEBUG_DBG (
"Downstream message type 0x%02X", controlData);
385 switch (controlData) {
388 DEBUG_ERROR (
"Error building get Version message");
391 DEBUG_VERBOSE (
"Get Version. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
395 DEBUG_ERROR (
"Error building get Sleep message");
398 DEBUG_VERBOSE (
"Get Sleep. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
402 DEBUG_ERROR (
"Error building set Sleep message");
405 DEBUG_VERBOSE (
"Set Sleep. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
409 DEBUG_ERROR (
"Error building OTA message");
412 DEBUG_VERBOSE (
"OTA message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
416 DEBUG_ERROR (
"Error building Identify message");
419 DEBUG_VERBOSE (
"Identify message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
423 DEBUG_ERROR (
"Error building Reset message");
426 DEBUG_VERBOSE (
"Reset Config message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
430 DEBUG_ERROR (
"Error building get RSSI message");
433 DEBUG_VERBOSE (
"Get RSSI message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
437 DEBUG_ERROR (
"Error building get name message");
440 DEBUG_VERBOSE (
"Get name message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
444 DEBUG_ERROR (
"Error building set name message");
447 DEBUG_VERBOSE (
"Set name message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
451 DEBUG_ERROR (
"Error building restart node message");
454 DEBUG_VERBOSE (
"Restart node message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
458 DEBUG_ERROR (
"Error building broadcast key message");
461 DEBUG_VERBOSE (
"Broadcast key message. Len: %d Data %s", dataLen,
printHexBuffer (downstreamData, dataLen));
464 DEBUG_INFO (
"Data message GET");
467 DEBUG_INFO (
"Data message SET");
474 DEBUG_INFO (
"Send downstream");
480 if (
node->getSleepy ()) {
481 DEBUG_ERROR (
"Node must be in non sleepy mode to receive OTA messages");
489 DEBUG_ERROR (
"Downlink destination %s not found", nodeName ? nodeName :
mac2str (mac));
495 server =
new AsyncWebServer (80);
496 dns =
new DNSServer ();
499 char networkKey[33] =
"";
507 AsyncWiFiManagerParameter netKeyParam (
"netkey",
"NetworkKey", networkKey, 33,
"required type=\"password\" minlength=\"8\" maxlength=\"32\"");
508 AsyncWiFiManagerParameter channelParam (
"channel",
"WiFi Channel", channel, 4,
"required type=\"number\" min=\"0\" max=\"13\" step=\"1\"");
510 wifiManager->setCustomHeadElement (
"<style>input:invalid {border: 2px dashed red;input:valid{border: 2px solid black;}</style>");
514 wifiManager->addParameter (
new AsyncWiFiManagerParameter (
"<br>"));
521 #if CONNECT_TO_WIFI_AP != 1
523 #endif // CONNECT_TO_WIFI_AP
524 wifiManager->setTryConnectDuringConfigPortal (
false);
528 #if CONNECT_TO_WIFI_AP == 1
529 boolean result =
wifiManager->autoConnect (
"EnigmaIoTGateway", NULL, 3, 2000);
531 boolean result =
wifiManager->startConfigPortal (
"EnigmaIoTGateway", NULL);
533 #endif // CONNECT_TO_WIFI_AP
535 DEBUG_INFO (
"==== Config Portal result ====");
536 DEBUG_INFO (
"Network Name: %s", netNameParam.getValue ());
537 DEBUG_INFO (
"Network Key: %s", netKeyParam.getValue ());
538 DEBUG_INFO (
"Channel: %s", channelParam.getValue ());
539 DEBUG_INFO (
"Status: %s", result ?
"true" :
"false");
540 DEBUG_INFO (
"Save config: %s",
shouldSave ?
"yes" :
"no");
545 std::regex networkNameRegex (
"^[^/\\\\]+$");
546 regexResult = std::regex_match (netNameParam.getValue (), networkNameRegex);
554 DEBUG_WARN (
"Network name parameter error");
559 std::regex netKeyRegex (
"^.{8,32}$");
560 regexResult = std::regex_match (netKeyParam.getValue (), netKeyRegex);
563 uint8_t keySize = netKeyParam.getValueLength ();
566 const char* netKey = netKeyParam.getValue ();
567 if (netKey && (netKey[0] !=
'\0')) {
574 DEBUG_INFO (
"Network key password field empty. Keeping the old one");
577 DEBUG_WARN (
"Network key parameter error");
582 std::regex channelRegex (
"^([0-9]|[0-1][0-3])$");
583 regexResult = std::regex_match (channelParam.getValue (), channelRegex);
589 DEBUG_WARN (
"Network name parameter error");
593 DEBUG_DBG (
"Configuration does not need to be saved");
596 DEBUG_ERROR (
"WiFi connection unsuccessful. Restarting");
613 bool json_correct =
false;
618 File configFile = FILESYSTEM.open (
CONFIG_FILE,
"r");
621 DEBUG_DBG (
"%s opened. %u bytes",
CONFIG_FILE, configFile.size ());
623 const size_t capacity = JSON_OBJECT_SIZE (4) + 160;
624 DynamicJsonDocument doc (capacity);
626 DeserializationError error = deserializeJson (doc, configFile);
628 DEBUG_ERROR (
"Failed to parse file");
630 DEBUG_DBG (
"JSON file parsed");
635 if (doc.containsKey (
"type")) {
636 if (!strcmp (
"gw", doc[
"type"])) {
638 if (doc.containsKey (
"channel") && doc.containsKey (
"networkKey")
639 && doc.containsKey (
"networkName")) {
644 DEBUG_ERROR (
"Wrong configuration. Removing file %s",
CONFIG_FILE);
654 DEBUG_VERBOSE (
"Gateway configuration successfuly read");
656 DEBUG_DBG (
"==== EnigmaIOT Gateway Configuration ====");
664 #if DEBUG_LEVEL >= DBG
666 size_t json_len = measureJsonPretty (doc) + 1;
667 output = (
char*)malloc (json_len);
668 serializeJsonPretty (doc, output, json_len);
670 DEBUG_DBG (
"JSON file %s", output);
686 WiFi.begin (
"0",
"0");
687 DEBUG_WARN (
"Dummy STA config loaded");
693 File configFile = FILESYSTEM.open (
CONFIG_FILE,
"w");
695 DEBUG_WARN (
"failed to open config file %s for writing",
CONFIG_FILE);
699 const size_t capacity = JSON_OBJECT_SIZE (4) + 160;
700 DynamicJsonDocument doc (capacity);
707 if (serializeJson (doc, configFile) == 0) {
708 DEBUG_ERROR (
"Failed to write to file");
714 #if DEBUG_LEVEL >= DBG
716 size_t json_len = measureJsonPretty (doc) + 1;
717 output = (
char*)malloc (json_len);
718 serializeJsonPretty (doc, output, json_len);
720 DEBUG_DBG (
"\n%s", output);
732 DEBUG_DBG (
"Gateway configuration saved to flash. %u bytes", configFile.size ());
752 if (!FILESYSTEM.begin ()) {
753 DEBUG_ERROR (
"Error mounting flash");
754 FILESYSTEM.format ();
755 DEBUG_ERROR (
"Formatted");
762 DEBUG_DBG (
"Got configuration. Storing");
764 DEBUG_DBG (
"Network Key stored on flash");
766 DEBUG_ERROR (
"Error saving data on flash");
770 DEBUG_INFO (
"Configuration has not to be saved");
773 DEBUG_ERROR (
"Configuration error. Restarting");
777 DEBUG_INFO (
"Configuration loaded from flash");
786 DEBUG_INFO (
"GW API started");
796 memcpy (message.
data, msg, len);
800 portENTER_CRITICAL (&myMutex);
808 portEXIT_CRITICAL (&myMutex);
819 portENTER_CRITICAL (&myMutex);
825 DEBUG_DBG (
"EnigmaIOT message got from queue. Size: %d",
input_queue->
size ());
826 memcpy (buffer->
data, message->
data, message->
len);
828 buffer->
len = message->
len;
832 portEXIT_CRITICAL (&myMutex);
861 DEBUG_VERBOSE (
"SENDStatus %s. Peer %s",
status == 0 ?
"OK" :
"ERROR",
mac2str (mac_addr));
863 DEBUG_VERBOSE (
"SENDStatus %d. Peer %s",
status,
mac2str (mac_addr));
869 static unsigned long rxOntime;
870 static unsigned long txOntime;
873 DEBUG_DBG (
"EnigmaIOTGatewayClass::flashrx");
878 rxOntime = millis ();
891 txOntime = millis ();
913 time_t currentTime = millis ();
916 DEBUG_WARN (
"OTA ongoing = false");
917 DEBUG_WARN (
"millis() = %u, lastOTAmsg = %u, diff = %d", currentTime,
lastOTAmsg, currentTime -
lastOTAmsg);
929 DEBUG_DBG (
"EnigmaIOT input message from queue. MsgType: 0x%02X", message->
data[0]);
938 DEBUG_INFO (
"Reveived message. Origin MAC: %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
942 DEBUG_WARN (
"Empty message");
956 DEBUG_INFO (
" <------- CLIENT HELLO");
958 if (espNowError == 0) {
961 DEBUG_INFO (
"Server Hello sent");
963 node->setKeyValidFrom (millis ());
964 node->setLastMessageCounter (0);
965 node->setLastControlCounter (0);
966 node->setLastDownlinkMsgCounter (0);
967 node->setLastMessageTime ();
971 #if DEBUG_LEVEL >= INFO
974 if (
node->broadcastIsEnabled ()) {
976 DEBUG_WARN (
"Error sending broadcast key to node");
978 node->setBroadcastKeyRequested (
false);
979 DEBUG_INFO (
"Broadcast key sent to node");
984 DEBUG_INFO (
"Error sending Server Hello");
991 DEBUG_ERROR (
"Error processing client hello");
994 DEBUG_ERROR (
"Error adding peer %d", espNowError);
1001 DEBUG_INFO (
" <------- CONTROL MESSAGE");
1004 DEBUG_INFO (
"Control message OK");
1014 DEBUG_WARN (
"Control message not OK");
1022 #if SUPPORT_HA_DISCOVERY
1024 #endif // SUPPORT_HA_DISCOVERY
1026 bool encrypted =
false;
1028 DEBUG_INFO (
" <------- ENCRYPTED DATA");
1031 #if SUPPORT_HA_DISCOVERY
1033 DEBUG_INFO (
" <------- HA_DISCOVERY_MESSAGE");
1036 #endif // SUPPORT_HA_DISCOVERY
1038 DEBUG_INFO (
" <------- UNENCRYPTED DATA");
1043 float packetsHour = (float)1 / ((millis () -
node->getLastMessageTime ()) / (float)3600000);
1044 node->updatePacketsRate (packetsHour);
1046 node->setLastMessageTime ();
1047 DEBUG_INFO (
"Data OK");
1048 DEBUG_VERBOSE (
"Key valid from %lu ms", millis () -
node->getKeyValidFrom ());
1058 DEBUG_WARN (
"Data not OK");
1070 DEBUG_INFO (
" <------- CLOCK REQUEST");
1073 DEBUG_INFO (
"Clock request OK");
1081 DEBUG_WARN (
"Clock request not OK");
1089 DEBUG_INFO (
" <------- NODE NAME REQUEST");
1092 DEBUG_INFO (
"Node name for node %d set to %s",
node->getNodeId (),
node->getNodeName ());
1097 DEBUG_WARN (
"Error setting node name for node %d",
node->getNodeId ());
1102 DEBUG_INFO (
"Received unknown EnigmaIOT message 0x%02X");
1112 struct __attribute__ ((packed, aligned (1))) {
1118 } nodeNameSetResponse_msg;
1122 const unsigned int NNSRMSG_LEN =
sizeof (nodeNameSetResponse_msg);
1127 counter =
node->getLastDownlinkMsgCounter () + 1;
1128 node->setLastDownlinkMsgCounter (counter);
1132 DEBUG_INFO (
"Downlink message #%d", counter);
1134 memcpy (&(nodeNameSetResponse_msg.counter), &counter, sizeof (uint16_t));
1136 DEBUG_DBG (
"Set node name Response. Error code: %d", error);
1142 nodeNameSetResponse_msg.errorCode = error;
1144 const uint8_t addDataLen = 1 +
IV_LENGTH;
1147 memcpy (aad, (uint8_t*)&nodeNameSetResponse_msg, addDataLen);
1155 aad, sizeof (aad), nodeNameSetResponse_msg.tag,
TAG_LENGTH)) {
1156 DEBUG_ERROR (
"Error during encryption");
1160 DEBUG_VERBOSE (
"Encrypted set node name response message: %s",
printHexBuffer ((uint8_t*)&nodeNameSetResponse_msg, NNSRMSG_LEN));
1162 DEBUG_INFO (
" -------> SEND SET NODE NAME RESPONSE");
1163 uint8_t* addr =
node->getMacAddress ();
1165 if (
comm->
send (addr, (uint8_t*)&nodeNameSetResponse_msg, NNSRMSG_LEN) == 0) {
1166 DEBUG_INFO (
"Set Node Name Response message sent to %s",
mac2str (addr));
1170 DEBUG_ERROR (
"Error sending Set Node Name Response message to %s",
mac2str (addr));
1187 uint8_t nodeId_idx = iv_idx +
IV_LENGTH;
1188 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1189 uint8_t nodeName_idx = counter_idx +
sizeof (int16_t);
1194 const uint8_t addDataLen = 1 +
IV_LENGTH;
1197 memcpy (aad, buf, addDataLen);
1206 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1207 DEBUG_ERROR (
"Error during decryption");
1211 memcpy (&counter, &(buf[counter_idx]),
sizeof (uint16_t));
1212 DEBUG_INFO (
"Node Id %d. Control message #%d",
node->getNodeId (), counter);
1214 if (counter >
node->getLastControlCounter ()) {
1215 DEBUG_INFO (
"Accepted");
1216 node->setLastControlCounter (counter);
1218 DEBUG_WARN (
"Control message rejected");
1226 size_t nodeNameLen = tag_idx - nodeName_idx;
1228 DEBUG_DBG (
"Node name length: %d bytes", nodeNameLen);
1234 memcpy ((
void*)nodeName, (
void*)(buf + nodeName_idx), nodeNameLen);
1244 node->setNodeName (nodeName);
1245 DEBUG_INFO (
"Node name set to %s",
node->getNodeName ());
1258 uint8_t length_idx = iv_idx +
IV_LENGTH;
1259 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1260 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1261 uint8_t data_idx = counter_idx +
sizeof (int16_t);
1266 const uint8_t addDataLen = 1 +
IV_LENGTH;
1269 memcpy (aad, buf, addDataLen);
1279 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1280 DEBUG_ERROR (
"Error during decryption");
1286 memcpy (&counter, &(buf[counter_idx]),
sizeof (uint16_t));
1287 DEBUG_INFO (
"Node Id %d. Control message #%d",
node->getNodeId (), counter);
1289 if (counter >
node->getLastControlCounter ()) {
1290 DEBUG_INFO (
"Accepted");
1291 node->setLastControlCounter (counter);
1293 DEBUG_WARN (
"Control message rejected. Last counter: %u. Current counter",
node->getLastControlCounter (), counter);
1299 const uint8_t* payload = buf + data_idx;
1302 DEBUG_DBG (
"Check if sleepy mode has changed for node");
1303 memcpy (&sleepTime, payload + 1,
sizeof (uint32_t));
1304 if (sleepTime > 0) {
1305 DEBUG_DBG (
"Set node to sleepy mode");
1306 node->setSleepy (
true);
1308 DEBUG_DBG (
"Set node to non sleepy mode");
1309 node->setSleepy (
false);
1313 DEBUG_DBG (
"Payload length: %d bytes", tag_idx - data_idx);
1315 char* nodeName =
node->getNodeName ();
1318 notifyData (
const_cast<uint8_t*
>(mac), buf + data_idx, tag_idx - data_idx, 0,
true,
ENIGMAIOT, nodeName ? nodeName : NULL);
1331 uint8_t nodeId_idx = 1;
1332 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1333 uint8_t payloadType_idx = counter_idx +
sizeof (int16_t);
1334 uint8_t data_idx = payloadType_idx +
sizeof (int8_t);
1337 size_t lostMessages = 0;
1341 DEBUG_VERBOSE (
"Unencrypted data message: %s",
printHexBuffer (buf, count));
1343 node->packetNumber++;
1345 memcpy (&counter, &buf[counter_idx],
sizeof (uint16_t));
1347 if (counter >
node->getLastMessageCounter ()) {
1348 lostMessages = counter -
node->getLastMessageCounter () - 1;
1349 node->packetErrors += lostMessages;
1350 node->setLastMessageCounter (counter);
1352 DEBUG_WARN (
"Data counter error %d : %d", counter,
node->getLastMessageCounter ());
1357 char* nodeName =
node->getNodeName ();
1360 notifyData (
const_cast<uint8_t*
>(mac), &(buf[data_idx]), count - data_idx, lostMessages,
false,
RAW, nodeName ? nodeName : NULL);
1363 if (
node->getSleepy ()) {
1364 if (
node->qMessagePending) {
1365 DEBUG_INFO (
" -------> DOWNLINK QUEUED DATA");
1367 node->qMessagePending =
false;
1389 uint8_t length_idx = iv_idx +
IV_LENGTH;
1390 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1391 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1392 uint8_t encoding_idx = counter_idx +
sizeof (int16_t);
1393 uint8_t data_idx = encoding_idx +
sizeof (int8_t);
1397 size_t lostMessages = 0;
1399 const uint8_t addDataLen = 1 +
IV_LENGTH;
1402 memcpy (aad, buf, addDataLen);
1412 aad, sizeof (aad), buf + tag_idx,
TAG_LENGTH)) {
1413 DEBUG_ERROR (
"Error during decryption");
1417 DEBUG_DBG (
"Data payload encoding: 0x%02X", buf[encoding_idx]);
1418 node->packetNumber++;
1420 memcpy (&counter, &(buf[counter_idx]),
sizeof (uint16_t));
1421 DEBUG_INFO (
"Node Id %d. Data message #%d",
node->getNodeId (), counter);
1423 if (counter >
node->getLastMessageCounter ()) {
1424 DEBUG_INFO (
"Accepted");
1425 lostMessages = counter -
node->getLastMessageCounter () - 1;
1426 node->packetErrors += lostMessages;
1427 node->setLastMessageCounter (counter);
1429 DEBUG_WARN (
"Data message rejected");
1434 char* nodeName =
node->getNodeName ();
1435 #if SUPPORT_HA_DISCOVERY
1439 #endif // SUPPORT_HA_DISCOVERY
1442 notifyData (
const_cast<uint8_t*
>(mac), &(buf[data_idx]), tag_idx - data_idx, lostMessages,
false, (
gatewayPayloadEncoding_t)(buf[encoding_idx]), nodeName ? nodeName : NULL);
1444 DEBUG_WARN (
"Wrong message type. Possible memory corruption");
1447 if (
node->getSleepy ()) {
1448 if (
node->qMessagePending) {
1449 DEBUG_INFO (
" -------> DOWNLINK QUEUED DATA");
1451 node->qMessagePending =
false;
1463 if (
node->packetNumber > 0) {
1464 node->per = (double)
node->packetErrors / (
double)
node->packetNumber;
1479 return node->packetErrors;
1485 return node->packetsHour;
1497 uint16_t packet_length;
1498 bool broadcast =
false;
1500 if (!
node->isRegistered ()) {
1501 DEBUG_VERBOSE (
"Error sending downstream. Node is not registered");
1505 uint16_t nodeId =
node->getNodeId ();
1509 uint8_t length_idx = iv_idx +
IV_LENGTH;
1510 uint8_t nodeId_idx = length_idx +
sizeof (int16_t);
1511 uint8_t counter_idx = nodeId_idx +
sizeof (int16_t);
1513 uint8_t encoding_idx;
1515 encoding_idx = counter_idx +
sizeof (int16_t);
1516 data_idx = encoding_idx +
sizeof (int8_t);
1517 buffer[encoding_idx] = encoding;
1518 packet_length = 1 +
IV_LENGTH +
sizeof (int16_t) +
sizeof (int16_t) +
sizeof (int16_t) + 1 + len;
1520 data_idx = counter_idx +
sizeof (int16_t);
1521 packet_length = 1 +
IV_LENGTH +
sizeof (int16_t) +
sizeof (int16_t) +
sizeof (int16_t) + len;
1523 uint8_t tag_idx = data_idx + len;
1526 DEBUG_ERROR (
"Downlink message buffer empty");
1530 DEBUG_ERROR (
"Downlink message too long: %d bytes", len);
1535 DEBUG_DBG (
"Encoding broadcast message");
1548 buffer[0] = buffer[0] | 0x80;
1549 DEBUG_DBG (
"Broadcast message. Type: 0x%X", buffer[0]);
1556 memcpy (buffer + nodeId_idx, &nodeId,
sizeof (uint16_t));
1560 counter =
node->getLastDownlinkMsgCounter () + 1;
1561 node->setLastDownlinkMsgCounter (counter);
1569 DEBUG_INFO (
"Downlink message #%d", counter);
1571 memcpy (buffer + counter_idx, &counter,
sizeof (uint16_t));
1573 memcpy (buffer + data_idx,
data, len);
1575 DEBUG_VERBOSE (
"Data: %s",
printHexBuffer (buffer + data_idx, len));
1577 memcpy (buffer + length_idx, &packet_length,
sizeof (uint16_t));
1579 DEBUG_VERBOSE (
"Downlink message: %s",
printHexBuffer (buffer, packet_length));
1580 DEBUG_VERBOSE (
"Message length: %d bytes", packet_length);
1586 const uint8_t addDataLen = 1 +
IV_LENGTH;
1589 memcpy (aad, buffer, addDataLen);
1597 aad, sizeof (aad), buffer + tag_idx,
TAG_LENGTH)) {
1598 DEBUG_ERROR (
"Error during encryption");
1605 if (
node->getSleepy ()) {
1607 DEBUG_VERBOSE (
"Node is sleepy. Queing message");
1608 memcpy (
node->queuedMessage, buffer, packet_length +
TAG_LENGTH);
1611 node->qMessagePending =
true;
1614 DEBUG_ERROR (
"OTA is only possible with non sleepy nodes. Configure it accordingly first");
1618 DEBUG_INFO (
" -------> DOWNLINK DATA");
1638 struct __attribute__ ((packed, aligned (1))) {
1641 } invalidateKey_msg;
1643 #define IKMSG_LEN sizeof(invalidateKey_msg)
1647 invalidateKey_msg.reason = reason;
1650 DEBUG_INFO (
" -------> INVALIDATE_KEY");
1652 uint8_t* mac =
node->getMacAddress ();
1670 struct __attribute__ ((packed, aligned (1))) {
1678 #define CHMSG_LEN sizeof(clientHello_msg)
1681 DEBUG_WARN (
"Message too short");
1685 memcpy (&clientHello_msg, buf, count);
1690 memcpy (aad, (uint8_t*)&clientHello_msg, addDataLen);
1698 aad, sizeof (aad), clientHello_msg.tag,
TAG_LENGTH)) {
1699 DEBUG_ERROR (
"Error during decryption");
1707 node->setEncryptionKey (clientHello_msg.publicKey);
1715 node->setKeyValid (
true);
1721 mac2str ((uint8_t*)mac, macstr);
1722 DEBUG_ERROR (
"DH2 error with %s", macstr);
1726 sleepyNode = (clientHello_msg.random & 0x00000001U) == 1;
1729 DEBUG_VERBOSE (
"This is a %s node",
sleepyNode ?
"sleepy" :
"always awaken");
1731 broadcast = (clientHello_msg.random & 0x00000002U) == 2;
1732 node->enableBroadcast (broadcast);
1733 node->setBroadcastKeyRequested (broadcast);
1734 DEBUG_INFO (
"This node has broadcast mode %s", broadcast ?
"enabled" :
"disabled");
1748 struct __attribute__ ((packed, aligned (1))) {
1757 const unsigned int CRMSG_LEN =
sizeof (clockRequest_msg);
1759 if (count < CRMSG_LEN) {
1760 DEBUG_WARN (
"Message too short");
1764 node->setTimeSyncEnabled ();
1767 gettimeofday (&tv, NULL);
1768 int64_t t2 = tv.tv_sec;
1775 memcpy (&clockRequest_msg, buf, count);
1779 const uint8_t addDataLen = 1 +
IV_LENGTH;
1782 memcpy (aad, buf, addDataLen);
1792 aad, sizeof (aad), clockRequest_msg.tag,
TAG_LENGTH)) {
1793 DEBUG_ERROR (
"Error during decryption");
1797 DEBUG_VERBOSE (
"Decripted Clock Request message: %s",
printHexBuffer ((uint8_t*)&clockRequest_msg, count -
TAG_LENGTH));
1799 memcpy (&counter, &(clockRequest_msg.counter), sizeof (uint16_t));
1800 DEBUG_INFO (
"Node Id %d. Control message #%d",
node->getNodeId (), counter);
1802 if (counter >
node->getLastControlCounter ()) {
1803 DEBUG_INFO (
"Accepted");
1804 node->setLastControlCounter (counter);
1806 DEBUG_WARN (
"Control message rejected");
1815 DEBUG_DBG (
"T1: %llu", clockRequest_msg.t1);
1816 DEBUG_DBG (
"T2: %llu", t2);
1826 struct __attribute__ ((packed, aligned (1))) {
1834 } clockResponse_msg;
1838 const unsigned int CRSMSG_LEN =
sizeof (clockResponse_msg);
1843 counter =
node->getLastDownlinkMsgCounter () + 1;
1844 node->setLastDownlinkMsgCounter (counter);
1848 DEBUG_INFO (
"Downlink message #%d", counter);
1850 memcpy (&(clockResponse_msg.counter), &counter, sizeof (uint16_t));
1852 memcpy (&(clockResponse_msg.t1), &t1, sizeof (int64_t));
1854 memcpy (&(clockResponse_msg.t2), &t2, sizeof (int64_t));
1857 gettimeofday (&tv, NULL);
1858 int64_t t3 = tv.tv_sec;
1862 memcpy (&(clockResponse_msg.t3), &t3, sizeof (int64_t));
1864 DEBUG_VERBOSE (
"Clock Response message: %s",
printHexBuffer ((uint8_t*)&clockResponse_msg, CRSMSG_LEN -
TAG_LENGTH));
1866 #ifdef DEBUG_ESP_PORT
1870 DEBUG_DBG (
"T1: %llu", t1);
1871 DEBUG_DBG (
"T2: %llu", t2);
1872 DEBUG_DBG (
"T3: %llu", t3);
1874 const uint8_t addDataLen = 1 +
IV_LENGTH;
1877 memcpy (aad, (uint8_t*)&clockResponse_msg, addDataLen);
1885 aad, sizeof (aad), clockResponse_msg.tag,
TAG_LENGTH)) {
1886 DEBUG_ERROR (
"Error during encryption");
1890 DEBUG_VERBOSE (
"Encrypted Clock Response message: %s",
printHexBuffer ((uint8_t*)&clockResponse_msg, CRSMSG_LEN));
1892 DEBUG_INFO (
" -------> CLOCK RESPONSE");
1893 if (
comm->
send (
node->getMacAddress (), (uint8_t*)&clockResponse_msg, CRSMSG_LEN) == 0) {
1894 DEBUG_INFO (
"Clock Response message sent to %s", mac);
1898 DEBUG_ERROR (
"Error sending Clock Response message to %s", mac);
1905 DEBUG_DBG (
"Send broadcast key to " MACSTR, MAC2STR (
node->getMacAddress ()));
1917 struct __attribute__ ((packed, aligned (1))) {
1926 #define SHMSG_LEN sizeof(serverHello_msg)
1931 DEBUG_ERROR (
"NULL key");
1942 serverHello_msg.publicKey[i] = key[i];
1945 uint16_t nodeId =
node->getNodeId ();
1946 memcpy (&(serverHello_msg.nodeId), &nodeId, sizeof (uint16_t));
1956 memcpy (aad, (uint8_t*)&serverHello_msg, addDataLen);
1964 aad, sizeof (aad), serverHello_msg.tag,
TAG_LENGTH)) {
1965 DEBUG_ERROR (
"Error during encryption");
1973 #ifdef DEBUG_ESP_PORT
1977 DEBUG_INFO (
" -------> SERVER_HELLO");
1979 DEBUG_INFO (
"Server Hello message sent to %s", mac);
1983 DEBUG_ERROR (
"Error sending Server Hello message to %s", mac);
1988 #if SUPPORT_HA_DISCOVERY
1990 DynamicJsonDocument inputJSON (1024);
1991 const int jsonBufferSize = 1024;
1992 char jsonStringBuffer[jsonBufferSize];
1995 DeserializationError result = deserializeMsgPack (inputJSON,
data, len);
1997 if (result != DeserializationError::Ok) {
1998 DEBUG_WARN (
"Error decoding HA discovery message: %s", result.c_str ());
2002 DEBUG_DBG (
"Entity name: %s", nodeName ? nodeName :
mac2str (address));
2006 DEBUG_DBG (
"Device Type: %d", deviceType);
2008 DEBUG_WARN (
"Device type error");
2016 switch (deviceType) {
2033 jsonStringBuffer[0] = 0;
2035 DEBUG_WARN (
"Device is not supported for HomeAssistant discovery: %d", deviceType);
2040 DEBUG_INFO (
"%s : %s", topic.c_str (), jsonStringBuffer);
2048 #endif // SUPPORT_HA_DISCOVERY