diff --git a/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino b/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino index 3a03b8416..fcb608c29 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino @@ -233,13 +233,6 @@ void setup() { WiFi.persistent(false); Serial.begin(115200); - delay(50); // Wait for Serial. - - //yield(); // Use this if you don't want to wait for Serial, but not with the ESP-NOW backend (yield() causes crashes with ESP-NOW). - - // The WiFi.disconnect() ensures that the WiFi is working correctly. If this is not done before receiving WiFi connections, - // those WiFi connections will take a long time to make or sometimes will not work at all. - WiFi.disconnect(); Serial.println(); Serial.println(); diff --git a/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino b/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino index 5855604b3..fdb129d3a 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloMesh/HelloMesh.ino @@ -122,13 +122,6 @@ void setup() { WiFi.persistent(false); Serial.begin(115200); - delay(50); // Wait for Serial. - - //yield(); // Use this if you don't want to wait for Serial, but not with the ESP-NOW backend (yield() causes crashes with ESP-NOW). - - // The WiFi.disconnect() ensures that the WiFi is working correctly. If this is not done before receiving WiFi connections, - // those WiFi connections will take a long time to make or sometimes will not work at all. - WiFi.disconnect(); Serial.println(); Serial.println(); diff --git a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino index 3fad54aa1..325450da3 100644 --- a/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino +++ b/libraries/ESP8266WiFiMesh/examples/HelloTcpIp/HelloTcpIp.ino @@ -160,13 +160,6 @@ void setup() { WiFi.persistent(false); Serial.begin(115200); - delay(50); // Wait for Serial. - - //yield(); // Use this if you don't want to wait for Serial. - - // The WiFi.disconnect() ensures that the WiFi is working correctly. If this is not done before receiving WiFi connections, - // those WiFi connections will take a long time to make or sometimes will not work at all. - WiFi.disconnect(); Serial.println(); Serial.println(); diff --git a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.cpp b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.cpp index 9f5cc45d3..c26d1fbe0 100644 --- a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.cpp +++ b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.cpp @@ -31,7 +31,7 @@ using EspnowProtocolInterpreter::espnowHashKeyLength; namespace TypeCast = MeshTypeConversionFunctions; -EncryptedConnectionData::EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, const uint8_t hashKey[espnowHashKeyLength]) +EncryptedConnectionData::EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint8_t hashKey[espnowHashKeyLength]) : _peerSessionKey(peerSessionKey), _ownSessionKey(ownSessionKey) { std::copy_n(peerStaMac, 6, _peerStaMac); @@ -39,7 +39,7 @@ EncryptedConnectionData::EncryptedConnectionData(const uint8_t peerStaMac[6], co std::copy_n(hashKey, espnowHashKeyLength, _hashKey); } -EncryptedConnectionData::EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, uint32_t duration, const uint8_t hashKey[espnowHashKeyLength]) +EncryptedConnectionData::EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint32_t duration, const uint8_t hashKey[espnowHashKeyLength]) : EncryptedConnectionData(peerStaMac, peerApMac, peerSessionKey, ownSessionKey, hashKey) { setRemainingDuration(duration); @@ -119,13 +119,13 @@ uint8_t *EncryptedConnectionData::getHashKey(uint8_t *resultArray) const return resultArray; } -void EncryptedConnectionData::setPeerSessionKey(uint64_t sessionKey) { _peerSessionKey = sessionKey; } +void EncryptedConnectionData::setPeerSessionKey(const uint64_t sessionKey) { _peerSessionKey = sessionKey; } uint64_t EncryptedConnectionData::getPeerSessionKey() const { return _peerSessionKey; } -void EncryptedConnectionData::setOwnSessionKey(uint64_t sessionKey) { _ownSessionKey = sessionKey; } +void EncryptedConnectionData::setOwnSessionKey(const uint64_t sessionKey) { _ownSessionKey = sessionKey; } uint64_t EncryptedConnectionData::getOwnSessionKey() const { return _ownSessionKey; } -uint64_t EncryptedConnectionData::incrementSessionKey(uint64_t sessionKey, const uint8_t *hashKey, uint8_t hashKeyLength) +uint64_t EncryptedConnectionData::incrementSessionKey(const uint64_t sessionKey, const uint8_t *hashKey, const uint8_t hashKeyLength) { uint8_t inputArray[8] {0}; uint8_t hmacArray[CryptoInterface::SHA256_NATURAL_LENGTH] {0}; @@ -149,7 +149,7 @@ void EncryptedConnectionData::incrementOwnSessionKey() setOwnSessionKey(incrementSessionKey(getOwnSessionKey(), _hashKey, EspnowProtocolInterpreter::espnowHashKeyLength)); } -void EncryptedConnectionData::setDesync(bool desync) { _desync = desync; } +void EncryptedConnectionData::setDesync(const bool desync) { _desync = desync; } bool EncryptedConnectionData::desync() const { return _desync; } String EncryptedConnectionData::serialize() const @@ -171,7 +171,7 @@ const ExpiringTimeTracker *EncryptedConnectionData::temporary() const return _timeTracker.get(); } -void EncryptedConnectionData::setRemainingDuration(uint32_t remainingDuration) +void EncryptedConnectionData::setRemainingDuration(const uint32_t remainingDuration) { if(!_timeTracker) { diff --git a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.h b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.h index be0d19171..871f8c10c 100644 --- a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.h +++ b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionData.h @@ -36,10 +36,10 @@ public: virtual ~EncryptedConnectionData() = default; - EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, + EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint8_t hashKey[EspnowProtocolInterpreter::espnowHashKeyLength]); - EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, - uint32_t duration, const uint8_t hashKey[EspnowProtocolInterpreter::espnowHashKeyLength]); + EncryptedConnectionData(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, + const uint32_t duration, const uint8_t hashKey[EspnowProtocolInterpreter::espnowHashKeyLength]); EncryptedConnectionData(const EncryptedConnectionData &other); @@ -65,15 +65,15 @@ public: // @param resultArray At least size espnowHashKeyLength. uint8_t *getHashKey(uint8_t *resultArray) const; - void setPeerSessionKey(uint64_t sessionKey); + void setPeerSessionKey(const uint64_t sessionKey); uint64_t getPeerSessionKey() const; - void setOwnSessionKey(uint64_t sessionKey); + void setOwnSessionKey(const uint64_t sessionKey); uint64_t getOwnSessionKey() const; - static uint64_t incrementSessionKey(uint64_t sessionKey, const uint8_t *hashKey, uint8_t hashKeyLength); + static uint64_t incrementSessionKey(const uint64_t sessionKey, const uint8_t *hashKey, const uint8_t hashKeyLength); void incrementOwnSessionKey(); - void setDesync(bool desync); + void setDesync(const bool desync); bool desync() const; // Note that the espnowEncryptedConnectionKey, espnowEncryptionKok, espnowHashKey and espnowMessageEncryptionKey are not serialized. @@ -81,7 +81,7 @@ public: String serialize() const; const ExpiringTimeTracker *temporary() const; - virtual void setRemainingDuration(uint32_t remainingDuration); + virtual void setRemainingDuration(const uint32_t remainingDuration); virtual void removeDuration(); private: diff --git a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.cpp b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.cpp index 12ce4dd3d..ae87f188b 100644 --- a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.cpp +++ b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.cpp @@ -26,11 +26,11 @@ using EspnowProtocolInterpreter::espnowHashKeyLength; -EncryptedConnectionLog::EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, const uint8_t hashKey[espnowHashKeyLength]) +EncryptedConnectionLog::EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint8_t hashKey[espnowHashKeyLength]) : EncryptedConnectionData(peerStaMac, peerApMac, peerSessionKey, ownSessionKey, hashKey) { } -EncryptedConnectionLog::EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, uint32_t duration, const uint8_t hashKey[espnowHashKeyLength]) +EncryptedConnectionLog::EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint32_t duration, const uint8_t hashKey[espnowHashKeyLength]) : EncryptedConnectionData(peerStaMac, peerApMac, peerSessionKey, ownSessionKey, duration, hashKey) { } @@ -38,7 +38,7 @@ std::unique_ptr EncryptedConnectionLog::_soonestExpiringCon bool EncryptedConnectionLog::_newRemovalsScheduled = false; -void EncryptedConnectionLog::setRemainingDuration(uint32_t remainingDuration) +void EncryptedConnectionLog::setRemainingDuration(const uint32_t remainingDuration) { EncryptedConnectionData::setRemainingDuration(remainingDuration); @@ -61,7 +61,7 @@ void EncryptedConnectionLog::scheduleForRemoval() setScheduledForRemoval(true); } -void EncryptedConnectionLog::setScheduledForRemoval(bool scheduledForRemoval) +void EncryptedConnectionLog::setScheduledForRemoval(const bool scheduledForRemoval) { _scheduledForRemoval = scheduledForRemoval; @@ -70,15 +70,15 @@ void EncryptedConnectionLog::setScheduledForRemoval(bool scheduledForRemoval) } bool EncryptedConnectionLog::removalScheduled() const { return _scheduledForRemoval; } -void EncryptedConnectionLog::setNewRemovalsScheduled(bool newRemovalsScheduled) { _newRemovalsScheduled = newRemovalsScheduled; } -bool EncryptedConnectionLog::newRemovalsScheduled( ){ return _newRemovalsScheduled; } +void EncryptedConnectionLog::setNewRemovalsScheduled(const bool newRemovalsScheduled) { _newRemovalsScheduled = newRemovalsScheduled; } +bool EncryptedConnectionLog::newRemovalsScheduled( ) { return _newRemovalsScheduled; } const ExpiringTimeTracker *EncryptedConnectionLog::getSoonestExpiringConnectionTracker() { return _soonestExpiringConnectionTracker.get(); } -void EncryptedConnectionLog::updateSoonestExpiringConnectionTracker(uint32_t remainingDuration) +void EncryptedConnectionLog::updateSoonestExpiringConnectionTracker(const uint32_t remainingDuration) { if(!getSoonestExpiringConnectionTracker() || remainingDuration < getSoonestExpiringConnectionTracker()->remainingDuration()) { diff --git a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.h b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.h index 2c1a99154..7909961fa 100644 --- a/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.h +++ b/libraries/ESP8266WiFiMesh/src/EncryptedConnectionLog.h @@ -32,10 +32,10 @@ class EncryptedConnectionLog : public EncryptedConnectionData { public: - EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, + EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint8_t hashKey[EspnowProtocolInterpreter::espnowHashKeyLength]); - EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], uint64_t peerSessionKey, uint64_t ownSessionKey, - uint32_t duration, const uint8_t hashKey[EspnowProtocolInterpreter::espnowHashKeyLength]); + EncryptedConnectionLog(const uint8_t peerStaMac[6], const uint8_t peerApMac[6], const uint64_t peerSessionKey, const uint64_t ownSessionKey, + const uint32_t duration, const uint8_t hashKey[EspnowProtocolInterpreter::espnowHashKeyLength]); // Only guaranteed to expire at the latest when the soonestExpiringConnection does. Can expire before the soonestExpiringConnection since it is not updated on connection removal. // Needs to be a copy to avoid invalidation during operations on temporaryEncryptedConnections. @@ -46,23 +46,23 @@ public: static bool _newRemovalsScheduled; // Can be used to set a duration both for temporary and permanent encrypted connections (transforming the latter into a temporary connection in the process). - void setRemainingDuration(uint32_t remainingDuration) override; + void setRemainingDuration(const uint32_t remainingDuration) override; void removeDuration() override; void scheduleForRemoval(); bool removalScheduled() const; - static void setNewRemovalsScheduled(bool newRemovalsScheduled); + static void setNewRemovalsScheduled(const bool newRemovalsScheduled); static bool newRemovalsScheduled(); static const ExpiringTimeTracker *getSoonestExpiringConnectionTracker(); - static void updateSoonestExpiringConnectionTracker(uint32_t remainingDuration); + static void updateSoonestExpiringConnectionTracker(const uint32_t remainingDuration); static void clearSoonestExpiringConnectionTracker(); private: bool _scheduledForRemoval = false; - void setScheduledForRemoval(bool scheduledForRemoval); + void setScheduledForRemoval(const bool scheduledForRemoval); }; #endif diff --git a/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.cpp b/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.cpp index ceb458cd8..95777f53c 100644 --- a/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.cpp +++ b/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.cpp @@ -112,9 +112,9 @@ void espnowDelay(uint32_t durationMs) while(!timeout); } -EspnowMeshBackend::EspnowMeshBackend(requestHandlerType requestHandler, responseHandlerType responseHandler, networkFilterType networkFilter, - broadcastFilterType broadcastFilter, const String &meshPassword, const String &ssidPrefix, const String &ssidSuffix, bool verboseMode, - uint8 meshWiFiChannel) +EspnowMeshBackend::EspnowMeshBackend(const requestHandlerType requestHandler, const responseHandlerType responseHandler, const networkFilterType networkFilter, + const broadcastFilterType broadcastFilter, const String &meshPassword, const String &ssidPrefix, const String &ssidSuffix, const bool verboseMode, + const uint8 meshWiFiChannel) : MeshBackendBase(requestHandler, responseHandler, networkFilter, MeshBackendType::ESP_NOW) { // Reserve the maximum possible usage early on to prevent heap fragmentation later. @@ -127,20 +127,20 @@ EspnowMeshBackend::EspnowMeshBackend(requestHandlerType requestHandler, response setWiFiChannel(meshWiFiChannel); } -EspnowMeshBackend::EspnowMeshBackend(requestHandlerType requestHandler, responseHandlerType responseHandler, networkFilterType networkFilter, - broadcastFilterType broadcastFilter, const String &meshPassword, const uint8_t espnowEncryptedConnectionKey[espnowEncryptedConnectionKeyLength], - const uint8_t espnowHashKey[espnowHashKeyLength], const String &ssidPrefix, const String &ssidSuffix, bool verboseMode, - uint8 meshWiFiChannel) +EspnowMeshBackend::EspnowMeshBackend(const requestHandlerType requestHandler, const responseHandlerType responseHandler, const networkFilterType networkFilter, + const broadcastFilterType broadcastFilter, const String &meshPassword, const uint8_t espnowEncryptedConnectionKey[espnowEncryptedConnectionKeyLength], + const uint8_t espnowHashKey[espnowHashKeyLength], const String &ssidPrefix, const String &ssidSuffix, const bool verboseMode, + const uint8 meshWiFiChannel) : EspnowMeshBackend(requestHandler, responseHandler, networkFilter, broadcastFilter, meshPassword, ssidPrefix, ssidSuffix, verboseMode, meshWiFiChannel) { setEspnowEncryptedConnectionKey(espnowEncryptedConnectionKey); setEspnowHashKey(espnowHashKey); } -EspnowMeshBackend::EspnowMeshBackend(requestHandlerType requestHandler, responseHandlerType responseHandler, networkFilterType networkFilter, - broadcastFilterType broadcastFilter, const String &meshPassword, const String &espnowEncryptedConnectionKeySeed, - const String &espnowHashKeySeed, const String &ssidPrefix, const String &ssidSuffix, bool verboseMode, - uint8 meshWiFiChannel) +EspnowMeshBackend::EspnowMeshBackend(const requestHandlerType requestHandler, const responseHandlerType responseHandler, const networkFilterType networkFilter, + const broadcastFilterType broadcastFilter, const String &meshPassword, const String &espnowEncryptedConnectionKeySeed, + const String &espnowHashKeySeed, const String &ssidPrefix, const String &ssidSuffix, const bool verboseMode, + const uint8 meshWiFiChannel) : EspnowMeshBackend(requestHandler, responseHandler, networkFilter, broadcastFilter, meshPassword, ssidPrefix, ssidSuffix, verboseMode, meshWiFiChannel) { setEspnowEncryptedConnectionKey(espnowEncryptedConnectionKeySeed); @@ -250,7 +250,7 @@ bool EspnowMeshBackend::latestTransmissionSuccessful() return latestTransmissionSuccessfulBase(latestTransmissionOutcomes()); } -void EspnowMeshBackend::performEspnowMaintenance(uint32_t estimatedMaxDuration) +void EspnowMeshBackend::performEspnowMaintenance(const uint32_t estimatedMaxDuration) { ExpiringTimeTracker estimatedMaxDurationTracker = ExpiringTimeTracker(estimatedMaxDuration); @@ -284,7 +284,7 @@ void EspnowMeshBackend::performEspnowMaintenance(uint32_t estimatedMaxDuration) } } -void EspnowMeshBackend::updateTemporaryEncryptedConnections(bool scheduledRemovalOnly) +void EspnowMeshBackend::updateTemporaryEncryptedConnections(const bool scheduledRemovalOnly) { EncryptedConnectionLog::clearSoonestExpiringConnectionTracker(); @@ -312,7 +312,7 @@ void EspnowMeshBackend::updateTemporaryEncryptedConnections(bool scheduledRemova } template -void EspnowMeshBackend::deleteExpiredLogEntries(std::map, T> &logEntries, uint32_t maxEntryLifetimeMs) +void EspnowMeshBackend::deleteExpiredLogEntries(std::map, T> &logEntries, const uint32_t maxEntryLifetimeMs) { for(typename std::map, T>::iterator entryIterator = logEntries.begin(); entryIterator != logEntries.end(); ) @@ -327,7 +327,7 @@ void EspnowMeshBackend::deleteExpiredLogEntries(std::map, } template -void EspnowMeshBackend::deleteExpiredLogEntries(std::map, TimeTracker> &logEntries, uint32_t maxEntryLifetimeMs) +void EspnowMeshBackend::deleteExpiredLogEntries(std::map, TimeTracker> &logEntries, const uint32_t maxEntryLifetimeMs) { for(typename std::map, TimeTracker>::iterator entryIterator = logEntries.begin(); entryIterator != logEntries.end(); ) @@ -341,7 +341,7 @@ void EspnowMeshBackend::deleteExpiredLogEntries(std::map, } } -void EspnowMeshBackend::deleteExpiredLogEntries(std::map, RequestData> &logEntries, uint32_t requestLifetimeMs, uint32_t broadcastLifetimeMs) +void EspnowMeshBackend::deleteExpiredLogEntries(std::map, RequestData> &logEntries, const uint32_t requestLifetimeMs, const uint32_t broadcastLifetimeMs) { for(typename std::map, RequestData>::iterator entryIterator = logEntries.begin(); entryIterator != logEntries.end(); ) @@ -360,7 +360,7 @@ void EspnowMeshBackend::deleteExpiredLogEntries(std::map -void EspnowMeshBackend::deleteExpiredLogEntries(std::list &logEntries, uint32_t maxEntryLifetimeMs) +void EspnowMeshBackend::deleteExpiredLogEntries(std::list &logEntries, const uint32_t maxEntryLifetimeMs) { for(typename std::list::iterator entryIterator = logEntries.begin(); entryIterator != logEntries.end(); ) @@ -375,7 +375,7 @@ void EspnowMeshBackend::deleteExpiredLogEntries(std::list &logEntries, uint32 } template <> -void EspnowMeshBackend::deleteExpiredLogEntries(std::list &logEntries, uint32_t maxEntryLifetimeMs) +void EspnowMeshBackend::deleteExpiredLogEntries(std::list &logEntries, const uint32_t maxEntryLifetimeMs) { for(typename std::list::iterator entryIterator = logEntries.begin(); entryIterator != logEntries.end(); ) @@ -391,7 +391,7 @@ void EspnowMeshBackend::deleteExpiredLogEntries(std::list -void EspnowMeshBackend::deleteExpiredLogEntries(std::list &logEntries, uint32_t maxEntryLifetimeMs) +void EspnowMeshBackend::deleteExpiredLogEntries(std::list &logEntries, const uint32_t maxEntryLifetimeMs) { for(typename std::list::iterator entryIterator = logEntries.begin(); entryIterator != logEntries.end(); ) @@ -421,7 +421,7 @@ void EspnowMeshBackend::clearOldLogEntries() deleteExpiredLogEntries(peerRequestConfirmationsToSend, getEncryptionRequestTimeout()); } -void EspnowMeshBackend::espnowReceiveCallbackWrapper(uint8_t *macaddr, uint8_t *dataArray, uint8_t len) +void EspnowMeshBackend::espnowReceiveCallbackWrapper(uint8_t *macaddr, uint8_t *dataArray, const uint8_t len) { using namespace EspnowProtocolInterpreter; @@ -557,7 +557,7 @@ void EspnowMeshBackend::espnowReceiveCallbackWrapper(uint8_t *macaddr, uint8_t * } } -void EspnowMeshBackend::handlePeerRequest(uint8_t *macaddr, uint8_t *dataArray, uint8_t len, uint64_t uint64StationMac, uint64_t receivedMessageID) +void EspnowMeshBackend::handlePeerRequest(const uint8_t *macaddr, uint8_t *dataArray, const uint8_t len, const uint64_t uint64StationMac, const uint64_t receivedMessageID) { // Pairing process ends when encryptedConnectionVerificationHeader is received, maxConnectionsReachedHeader is sent or timeout is reached. // Pairing process stages for request receiver: @@ -657,7 +657,7 @@ void EspnowMeshBackend::handlePeerRequest(uint8_t *macaddr, uint8_t *dataArray, } } -void EspnowMeshBackend::handlePeerRequestConfirmation(uint8_t *macaddr, uint8_t *dataArray, uint8_t len) +void EspnowMeshBackend::handlePeerRequestConfirmation(uint8_t *macaddr, uint8_t *dataArray, const uint8_t len) { // Pairing process ends when _ongoingPeerRequestNonce == "" or timeout is reached. // Pairing process stages for request sender: @@ -764,7 +764,7 @@ void EspnowMeshBackend::handlePeerRequestConfirmation(uint8_t *macaddr, uint8_t } } -void EspnowMeshBackend::espnowReceiveCallback(uint8_t *macaddr, uint8_t *dataArray, uint8_t len) +void EspnowMeshBackend::espnowReceiveCallback(const uint8_t *macaddr, uint8_t *dataArray, const uint8_t len) { using namespace EspnowProtocolInterpreter; @@ -924,29 +924,29 @@ void EspnowMeshBackend::setEspnowRequestManager(EspnowMeshBackend *espnowMeshIns EspnowMeshBackend *EspnowMeshBackend::getEspnowRequestManager() {return _espnowRequestManager;} -bool EspnowMeshBackend::isEspnowRequestManager() +bool EspnowMeshBackend::isEspnowRequestManager() const { return (this == getEspnowRequestManager()); } -bool EspnowMeshBackend::encryptedConnectionEstablished(EncryptedConnectionStatus connectionStatus) +bool EspnowMeshBackend::encryptedConnectionEstablished(const EncryptedConnectionStatus connectionStatus) { return static_cast(connectionStatus) > 0; } -void EspnowMeshBackend::setLogEntryLifetimeMs(uint32_t logEntryLifetimeMs) +void EspnowMeshBackend::setLogEntryLifetimeMs(const uint32_t logEntryLifetimeMs) { _logEntryLifetimeMs = logEntryLifetimeMs; } uint32_t EspnowMeshBackend::logEntryLifetimeMs() { return _logEntryLifetimeMs; } -void EspnowMeshBackend::setBroadcastResponseTimeoutMs(uint32_t broadcastResponseTimeoutMs) +void EspnowMeshBackend::setBroadcastResponseTimeoutMs(const uint32_t broadcastResponseTimeoutMs) { _broadcastResponseTimeoutMs = broadcastResponseTimeoutMs; } uint32_t EspnowMeshBackend::broadcastResponseTimeoutMs() { return _broadcastResponseTimeoutMs; } -void EspnowMeshBackend::setCriticalHeapLevelBuffer(uint32_t bufferInBytes) +void EspnowMeshBackend::setCriticalHeapLevelBuffer(const uint32_t bufferInBytes) { _criticalHeapLevelBuffer = bufferInBytes; } @@ -957,7 +957,7 @@ uint32_t EspnowMeshBackend::criticalHeapLevelBuffer() } template -T *EspnowMeshBackend::getMapValue(std::map &mapIn, uint64_t keyIn) +T *EspnowMeshBackend::getMapValue(std::map &mapIn, const uint64_t keyIn) { typename std::map::iterator mapIterator = mapIn.find(keyIn); @@ -979,7 +979,7 @@ void EspnowMeshBackend::storeReceivedRequest(const uint64_t senderBSSID, const u receivedRequests.insert(std::make_pair(std::make_pair(senderBSSID, messageID), timeTracker)); } -EspnowMeshBackend *EspnowMeshBackend::getOwnerOfSentRequest(uint64_t requestMac, uint64_t requestID) +EspnowMeshBackend *EspnowMeshBackend::getOwnerOfSentRequest(const uint64_t requestMac, const uint64_t requestID) { std::map, RequestData>::iterator sentRequest = sentRequests.find(std::make_pair(requestMac, requestID)); @@ -991,12 +991,12 @@ EspnowMeshBackend *EspnowMeshBackend::getOwnerOfSentRequest(uint64_t requestMac, return nullptr; } -size_t EspnowMeshBackend::deleteSentRequest(uint64_t requestMac, uint64_t requestID) +size_t EspnowMeshBackend::deleteSentRequest(const uint64_t requestMac, const uint64_t requestID) { return sentRequests.erase(std::make_pair(requestMac, requestID)); } -size_t EspnowMeshBackend::deleteSentRequestsByOwner(EspnowMeshBackend *instancePointer) +size_t EspnowMeshBackend::deleteSentRequestsByOwner(const EspnowMeshBackend *instancePointer) { size_t numberDeleted = 0; @@ -1015,7 +1015,7 @@ size_t EspnowMeshBackend::deleteSentRequestsByOwner(EspnowMeshBackend *instanceP return numberDeleted; } -bool EspnowMeshBackend::requestReceived(uint64_t requestMac, uint64_t requestID) +bool EspnowMeshBackend::requestReceived(const uint64_t requestMac, const uint64_t requestID) { return receivedRequests.count(std::make_pair(requestMac, requestID)); } @@ -1025,7 +1025,7 @@ uint32_t EspnowMeshBackend::criticalHeapLevel() return _criticalHeapLevel; } -uint64_t EspnowMeshBackend::generateMessageID(EncryptedConnectionLog *encryptedConnection) +uint64_t EspnowMeshBackend::generateMessageID(const EncryptedConnectionLog *encryptedConnection) { if(encryptedConnection) { @@ -1041,39 +1041,39 @@ uint64_t EspnowMeshBackend::createSessionKey() return EspnowProtocolInterpreter::usesEncryption(newSessionKey) ? newSessionKey : (newSessionKey | ((uint64_t)RANDOM_REG32) << 32 | uint64MSB); } -void EspnowMeshBackend::setEspnowTransmissionTimeout(uint32_t timeoutMs) +void EspnowMeshBackend::setEspnowTransmissionTimeout(const uint32_t timeoutMs) { _espnowTransmissionTimeoutMs = timeoutMs; } uint32_t EspnowMeshBackend::getEspnowTransmissionTimeout() {return _espnowTransmissionTimeoutMs;} -void EspnowMeshBackend::setEspnowRetransmissionInterval(uint32_t intervalMs) +void EspnowMeshBackend::setEspnowRetransmissionInterval(const uint32_t intervalMs) { _espnowRetransmissionIntervalMs = intervalMs; } uint32_t EspnowMeshBackend::getEspnowRetransmissionInterval() {return _espnowRetransmissionIntervalMs;} -void EspnowMeshBackend::setEncryptionRequestTimeout(uint32_t timeoutMs) +void EspnowMeshBackend::setEncryptionRequestTimeout(const uint32_t timeoutMs) { _encryptionRequestTimeoutMs = timeoutMs; } uint32_t EspnowMeshBackend::getEncryptionRequestTimeout() {return _encryptionRequestTimeoutMs;} -void EspnowMeshBackend::setAutoEncryptionDuration(uint32_t duration) +void EspnowMeshBackend::setAutoEncryptionDuration(const uint32_t duration) { _autoEncryptionDuration = duration; } -uint32_t EspnowMeshBackend::getAutoEncryptionDuration() {return _autoEncryptionDuration;} +uint32_t EspnowMeshBackend::getAutoEncryptionDuration() const {return _autoEncryptionDuration;} -void EspnowMeshBackend::setBroadcastFilter(broadcastFilterType broadcastFilter) {_broadcastFilter = broadcastFilter;} -EspnowMeshBackend::broadcastFilterType EspnowMeshBackend::getBroadcastFilter() {return _broadcastFilter;} +void EspnowMeshBackend::setBroadcastFilter(const broadcastFilterType broadcastFilter) {_broadcastFilter = broadcastFilter;} +EspnowMeshBackend::broadcastFilterType EspnowMeshBackend::getBroadcastFilter() const {return _broadcastFilter;} -bool EspnowMeshBackend::usesConstantSessionKey(char messageType) +bool EspnowMeshBackend::usesConstantSessionKey(const char messageType) { return messageType == 'A' || messageType == 'C'; } -TransmissionStatusType EspnowMeshBackend::espnowSendToNode(const String &message, const uint8_t *targetBSSID, char messageType, EspnowMeshBackend *espnowInstance) +TransmissionStatusType EspnowMeshBackend::espnowSendToNode(const String &message, const uint8_t *targetBSSID, const char messageType, EspnowMeshBackend *espnowInstance) { using EspnowProtocolInterpreter::synchronizationRequestHeader; @@ -1102,7 +1102,7 @@ TransmissionStatusType EspnowMeshBackend::espnowSendToNode(const String &message return espnowSendToNodeUnsynchronized(message, targetBSSID, messageType, generateMessageID(encryptedConnection), espnowInstance); } -TransmissionStatusType EspnowMeshBackend::espnowSendToNodeUnsynchronized(const String message, const uint8_t *targetBSSID, char messageType, uint64_t messageID, EspnowMeshBackend *espnowInstance) +TransmissionStatusType EspnowMeshBackend::espnowSendToNodeUnsynchronized(const String message, const uint8_t *targetBSSID, const char messageType, const uint64_t messageID, EspnowMeshBackend *espnowInstance) { using namespace EspnowProtocolInterpreter; @@ -1276,7 +1276,7 @@ TransmissionStatusType EspnowMeshBackend::sendRequest(const String &message, con return transmissionStatus; } -TransmissionStatusType EspnowMeshBackend::sendResponse(const String &message, uint64_t requestID, const uint8_t *targetBSSID) +TransmissionStatusType EspnowMeshBackend::sendResponse(const String &message, const uint64_t requestID, const uint8_t *targetBSSID) { EncryptedConnectionLog *encryptedConnection = getEncryptedConnection(targetBSSID); uint8_t encryptedMac[6] {0}; @@ -1292,7 +1292,7 @@ TransmissionStatusType EspnowMeshBackend::sendResponse(const String &message, ui bool EspnowMeshBackend::transmissionInProgress(){return *_espnowTransmissionMutex;} -EspnowMeshBackend::macAndType_td EspnowMeshBackend::createMacAndTypeValue(uint64_t uint64Mac, char messageType) +EspnowMeshBackend::macAndType_td EspnowMeshBackend::createMacAndTypeValue(const uint64_t uint64Mac, const char messageType) { return static_cast(uint64Mac << 8 | (uint64_t)messageType); } @@ -1317,12 +1317,12 @@ void EspnowMeshBackend::setEspnowEncryptedConnectionKey(const String &espnowEncr MeshCryptoInterface::initializeKey(_espnowEncryptedConnectionKey, espnowEncryptedConnectionKeyLength, espnowEncryptedConnectionKeySeed); } -const uint8_t *EspnowMeshBackend::getEspnowEncryptedConnectionKey() +const uint8_t *EspnowMeshBackend::getEspnowEncryptedConnectionKey() const { return _espnowEncryptedConnectionKey; } -uint8_t *EspnowMeshBackend::getEspnowEncryptedConnectionKey(uint8_t resultArray[espnowEncryptedConnectionKeyLength]) +uint8_t *EspnowMeshBackend::getEspnowEncryptedConnectionKey(uint8_t resultArray[espnowEncryptedConnectionKeyLength]) const { std::copy_n(_espnowEncryptedConnectionKey, espnowEncryptedConnectionKeyLength, resultArray); return resultArray; @@ -1374,12 +1374,12 @@ void EspnowMeshBackend::setEspnowHashKey(const String &espnowHashKeySeed) MeshCryptoInterface::initializeKey(_espnowHashKey, espnowHashKeyLength, espnowHashKeySeed); } -const uint8_t *EspnowMeshBackend::getEspnowHashKey() +const uint8_t *EspnowMeshBackend::getEspnowHashKey() const { return _espnowHashKey; } -void EspnowMeshBackend::setEspnowMessageEncryptionKey(uint8_t espnowMessageEncryptionKey[CryptoInterface::ENCRYPTION_KEY_LENGTH]) +void EspnowMeshBackend::setEspnowMessageEncryptionKey(const uint8_t espnowMessageEncryptionKey[CryptoInterface::ENCRYPTION_KEY_LENGTH]) { assert(espnowMessageEncryptionKey != nullptr); @@ -1399,7 +1399,7 @@ const uint8_t *EspnowMeshBackend::getEspnowMessageEncryptionKey() return _espnowMessageEncryptionKey; } -void EspnowMeshBackend::setUseEncryptedMessages(bool useEncryptedMessages) +void EspnowMeshBackend::setUseEncryptedMessages(const bool useEncryptedMessages) { MutexTracker mutexTracker(_espnowSendToNodeMutex); if(!mutexTracker.mutexCaptured()) @@ -1411,7 +1411,7 @@ void EspnowMeshBackend::setUseEncryptedMessages(bool useEncryptedMessages) } bool EspnowMeshBackend::useEncryptedMessages() { return _useEncryptedMessages; } -bool EspnowMeshBackend::verifyPeerSessionKey(uint64_t sessionKey, const uint8_t *peerMac, char messageType) +bool EspnowMeshBackend::verifyPeerSessionKey(const uint64_t sessionKey, const uint8_t *peerMac, const char messageType) { if(EncryptedConnectionLog *encryptedConnection = getEncryptedConnection(peerMac)) { @@ -1421,7 +1421,7 @@ bool EspnowMeshBackend::verifyPeerSessionKey(uint64_t sessionKey, const uint8_t return false; } -bool EspnowMeshBackend::verifyPeerSessionKey(uint64_t sessionKey, EncryptedConnectionLog &encryptedConnection, uint64_t uint64PeerMac, char messageType) +bool EspnowMeshBackend::verifyPeerSessionKey(const uint64_t sessionKey, const EncryptedConnectionLog &encryptedConnection, const uint64_t uint64PeerMac, const char messageType) { if(EspnowProtocolInterpreter::usesEncryption(sessionKey)) { @@ -1437,7 +1437,7 @@ bool EspnowMeshBackend::verifyPeerSessionKey(uint64_t sessionKey, EncryptedConne return false; } -bool EspnowMeshBackend::synchronizePeerSessionKey(uint64_t sessionKey, const uint8_t *peerMac) +bool EspnowMeshBackend::synchronizePeerSessionKey(const uint64_t sessionKey, const uint8_t *peerMac) { if(EncryptedConnectionLog *encryptedConnection = getEncryptedConnection(peerMac)) { @@ -1447,7 +1447,7 @@ bool EspnowMeshBackend::synchronizePeerSessionKey(uint64_t sessionKey, const uin return false; } -bool EspnowMeshBackend::synchronizePeerSessionKey(uint64_t sessionKey, EncryptedConnectionLog &encryptedConnection) +bool EspnowMeshBackend::synchronizePeerSessionKey(const uint64_t sessionKey, EncryptedConnectionLog &encryptedConnection) { if(EspnowProtocolInterpreter::usesEncryption(sessionKey)) { @@ -1462,7 +1462,7 @@ bool EspnowMeshBackend::synchronizePeerSessionKey(uint64_t sessionKey, Encrypted return false; } -std::list::const_iterator EspnowMeshBackend::getScheduledResponse(uint32_t responseIndex) +std::list::const_iterator EspnowMeshBackend::getScheduledResponse(const uint32_t responseIndex) { assert(responseIndex < numberOfScheduledResponses()); @@ -1479,12 +1479,12 @@ std::list::const_iterator EspnowMeshBackend::getScheduledResponse( return responseIterator; } -String EspnowMeshBackend::getScheduledResponseMessage(uint32_t responseIndex) +String EspnowMeshBackend::getScheduledResponseMessage(const uint32_t responseIndex) { return getScheduledResponse(responseIndex)->getMessage(); } -const uint8_t *EspnowMeshBackend::getScheduledResponseRecipient(uint32_t responseIndex) +const uint8_t *EspnowMeshBackend::getScheduledResponseRecipient(const uint32_t responseIndex) { return getScheduledResponse(responseIndex)->getRecipientMac(); } @@ -1502,7 +1502,7 @@ void EspnowMeshBackend::clearAllScheduledResponses() responsesToSend.clear(); } -void EspnowMeshBackend::deleteScheduledResponsesByRecipient(const uint8_t *recipientMac, bool encryptedOnly) +void EspnowMeshBackend::deleteScheduledResponsesByRecipient(const uint8_t *recipientMac, const bool encryptedOnly) { MutexTracker responsesToSendMutexTracker(_responsesToSendMutex); if(!responsesToSendMutexTracker.mutexCaptured()) @@ -1522,39 +1522,39 @@ void EspnowMeshBackend::deleteScheduledResponsesByRecipient(const uint8_t *recip } } -void EspnowMeshBackend::setSenderMac(uint8_t *macArray) +void EspnowMeshBackend::setSenderMac(const uint8_t *macArray) { std::copy_n(macArray, 6, _senderMac); } -String EspnowMeshBackend::getSenderMac() {return TypeCast::macToString(_senderMac);} -uint8_t *EspnowMeshBackend::getSenderMac(uint8_t *macArray) +String EspnowMeshBackend::getSenderMac() const {return TypeCast::macToString(_senderMac);} +uint8_t *EspnowMeshBackend::getSenderMac(uint8_t *macArray) const { std::copy_n(_senderMac, 6, macArray); return macArray; } -void EspnowMeshBackend::setSenderAPMac(uint8_t *macArray) +void EspnowMeshBackend::setSenderAPMac(const uint8_t *macArray) { std::copy_n(macArray, 6, _senderAPMac); } -String EspnowMeshBackend::getSenderAPMac() {return TypeCast::macToString(_senderAPMac);} -uint8_t *EspnowMeshBackend::getSenderAPMac(uint8_t *macArray) +String EspnowMeshBackend::getSenderAPMac() const {return TypeCast::macToString(_senderAPMac);} +uint8_t *EspnowMeshBackend::getSenderAPMac(uint8_t *macArray) const { std::copy_n(_senderAPMac, 6, macArray); return macArray; } -void EspnowMeshBackend::setReceivedEncryptedTransmission(bool receivedEncryptedTransmission) { _receivedEncryptedTransmission = receivedEncryptedTransmission; } -bool EspnowMeshBackend::receivedEncryptedTransmission() {return _receivedEncryptedTransmission;} +void EspnowMeshBackend::setReceivedEncryptedTransmission(const bool receivedEncryptedTransmission) { _receivedEncryptedTransmission = receivedEncryptedTransmission; } +bool EspnowMeshBackend::receivedEncryptedTransmission() const {return _receivedEncryptedTransmission;} bool EspnowMeshBackend::addUnencryptedConnection(const String &serializedConnectionState) { return JsonTranslator::getUnsynchronizedMessageID(serializedConnectionState, _unsynchronizedMessageID); } -EncryptedConnectionStatus EspnowMeshBackend::addEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, uint64_t peerSessionKey, uint64_t ownSessionKey) +EncryptedConnectionStatus EspnowMeshBackend::addEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, const uint64_t peerSessionKey, const uint64_t ownSessionKey) { assert(encryptedConnections.size() <= maxEncryptedConnections); // If this is not the case, ESP-NOW is no longer in sync with the library @@ -1590,7 +1590,7 @@ EncryptedConnectionStatus EspnowMeshBackend::addEncryptedConnection(uint8_t *pee } } -EncryptedConnectionStatus EspnowMeshBackend::addEncryptedConnection(const String &serializedConnectionState, bool ignoreDuration) +EncryptedConnectionStatus EspnowMeshBackend::addEncryptedConnection(const String &serializedConnectionState, const bool ignoreDuration) { uint32_t duration = 0; bool desync = false; @@ -1626,7 +1626,7 @@ EncryptedConnectionStatus EspnowMeshBackend::addEncryptedConnection(const String return EncryptedConnectionStatus::REQUEST_TRANSMISSION_FAILED; } -EncryptedConnectionStatus EspnowMeshBackend::addTemporaryEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, uint64_t peerSessionKey, uint64_t ownSessionKey, uint32_t duration) +EncryptedConnectionStatus EspnowMeshBackend::addTemporaryEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint32_t duration) { assert(encryptedConnections.size() <= maxEncryptedConnections); // If this is not the case, ESP-NOW is no longer in sync with the library @@ -1663,7 +1663,7 @@ EncryptedConnectionStatus EspnowMeshBackend::addTemporaryEncryptedConnection(uin return result; } -EncryptedConnectionStatus EspnowMeshBackend::addTemporaryEncryptedConnection(const String &serializedConnectionState, uint32_t duration) +EncryptedConnectionStatus EspnowMeshBackend::addTemporaryEncryptedConnection(const String &serializedConnectionState, const uint32_t duration) { bool desync = false; uint64_t ownSessionKey = 0; @@ -1704,7 +1704,7 @@ void EspnowMeshBackend::handlePostponedRemovals() } } -EncryptedConnectionStatus EspnowMeshBackend::requestEncryptedConnectionKernel(uint8_t *peerMac, const encryptionRequestBuilderType &encryptionRequestBuilder) +EncryptedConnectionStatus EspnowMeshBackend::requestEncryptedConnectionKernel(const uint8_t *peerMac, const encryptionRequestBuilderType &encryptionRequestBuilder) { using namespace EspnowProtocolInterpreter; @@ -1856,26 +1856,26 @@ String EspnowMeshBackend::flexibleEncryptionRequestBuilder(const uint32_t minDur return createEncryptionRequestHmacMessage(FPSTR(temporaryEncryptionRequestHeader), requestNonce, hashKey, espnowHashKeyLength, connectionDuration); } -EncryptedConnectionStatus EspnowMeshBackend::requestEncryptedConnection(uint8_t *peerMac) +EncryptedConnectionStatus EspnowMeshBackend::requestEncryptedConnection(const uint8_t *peerMac) { using namespace std::placeholders; return requestEncryptedConnectionKernel(peerMac, std::bind(defaultEncryptionRequestBuilder, FPSTR(EspnowProtocolInterpreter::encryptionRequestHeader), 0, getEspnowHashKey(), _1, _2)); } -EncryptedConnectionStatus EspnowMeshBackend::requestTemporaryEncryptedConnection(uint8_t *peerMac, uint32_t durationMs) +EncryptedConnectionStatus EspnowMeshBackend::requestTemporaryEncryptedConnection(const uint8_t *peerMac, const uint32_t durationMs) { using namespace std::placeholders; return requestEncryptedConnectionKernel(peerMac, std::bind(defaultEncryptionRequestBuilder, FPSTR(EspnowProtocolInterpreter::temporaryEncryptionRequestHeader), durationMs, getEspnowHashKey(), _1, _2)); } -EncryptedConnectionStatus EspnowMeshBackend::requestFlexibleTemporaryEncryptedConnection(uint8_t *peerMac, uint32_t minDurationMs) +EncryptedConnectionStatus EspnowMeshBackend::requestFlexibleTemporaryEncryptedConnection(const uint8_t *peerMac, const uint32_t minDurationMs) { using namespace std::placeholders; return requestEncryptedConnectionKernel(peerMac, std::bind(flexibleEncryptionRequestBuilder, minDurationMs, getEspnowHashKey(), _1, _2)); } -bool EspnowMeshBackend::temporaryEncryptedConnectionToPermanent(uint8_t *peerMac) +bool EspnowMeshBackend::temporaryEncryptedConnectionToPermanent(const uint8_t *peerMac) { if(EncryptedConnectionLog *temporaryConnection = getTemporaryEncryptedConnection(peerMac)) { @@ -1886,7 +1886,7 @@ bool EspnowMeshBackend::temporaryEncryptedConnectionToPermanent(uint8_t *peerMac return false; } -EncryptedConnectionRemovalOutcome EspnowMeshBackend::removeEncryptedConnection(uint8_t *peerMac) +EncryptedConnectionRemovalOutcome EspnowMeshBackend::removeEncryptedConnection(const uint8_t *peerMac) { auto connectionIterator = getEncryptedConnectionIterator(peerMac, encryptedConnections); if(connectionIterator != encryptedConnections.end()) @@ -1962,7 +1962,7 @@ EncryptedConnectionRemovalOutcome EspnowMeshBackend::removeEncryptedConnectionUn } template -void EspnowMeshBackend::deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, bool encryptedOnly) +void EspnowMeshBackend::deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, const bool encryptedOnly) { bool macFound = false; @@ -1990,7 +1990,7 @@ void EspnowMeshBackend::deleteEntriesByMac(std::map -void EspnowMeshBackend::deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, bool encryptedOnly) +void EspnowMeshBackend::deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, const bool encryptedOnly) { bool macFound = false; @@ -2017,7 +2017,7 @@ void EspnowMeshBackend::deleteEntriesByMac(std::map typename T::iterator EspnowMeshBackend::getEncryptedConnectionIterator(const uint8_t *peerMac, T &connectionContainer) @@ -2140,7 +2140,7 @@ uint8_t *EspnowMeshBackend::getEncryptedMac(const uint8_t *peerMac, uint8_t *res return nullptr; } -void EspnowMeshBackend::prepareForTransmission(const String &message, bool scan, bool scanAllWiFiChannels) +void EspnowMeshBackend::prepareForTransmission(const String &message, const bool scan, const bool scanAllWiFiChannels) { setMessage(message); @@ -2189,7 +2189,7 @@ TransmissionStatusType EspnowMeshBackend::initiateTransmissionKernel(const Strin return transmissionResult; } -void EspnowMeshBackend::printTransmissionStatistics() +void EspnowMeshBackend::printTransmissionStatistics() const { if(verboseMode() && successfulTransmissions_AT > 0) // Avoid calculations if not required { @@ -2202,7 +2202,7 @@ void EspnowMeshBackend::printTransmissionStatistics() } } -void EspnowMeshBackend::attemptTransmission(const String &message, bool scan, bool scanAllWiFiChannels) +void EspnowMeshBackend::attemptTransmission(const String &message, const bool scan, const bool scanAllWiFiChannels) { MutexTracker mutexTracker(_espnowTransmissionMutex, handlePostponedRemovals); if(!mutexTracker.mutexCaptured()) @@ -2246,7 +2246,7 @@ TransmissionStatusType EspnowMeshBackend::attemptTransmission(const String &mess return initiateTransmission(message, recipientInfo); } -EncryptedConnectionStatus EspnowMeshBackend::initiateAutoEncryptingConnection(const EspnowNetworkInfo &recipientInfo, bool requestPermanentConnection, uint8_t *targetBSSID, EncryptedConnectionLog **existingEncryptedConnection) +EncryptedConnectionStatus EspnowMeshBackend::initiateAutoEncryptingConnection(const EspnowNetworkInfo &recipientInfo, const bool requestPermanentConnection, uint8_t *targetBSSID, EncryptedConnectionLog **existingEncryptedConnection) { assert(recipientInfo.BSSID() != nullptr); // We need at least the BSSID to connect recipientInfo.getBSSID(targetBSSID); @@ -2268,7 +2268,7 @@ EncryptedConnectionStatus EspnowMeshBackend::initiateAutoEncryptingConnection(co return connectionStatus; } -TransmissionStatusType EspnowMeshBackend::initiateAutoEncryptingTransmission(const String &message, const uint8_t *targetBSSID, EncryptedConnectionStatus connectionStatus) +TransmissionStatusType EspnowMeshBackend::initiateAutoEncryptingTransmission(const String &message, uint8_t *targetBSSID, EncryptedConnectionStatus connectionStatus) { TransmissionStatusType transmissionResult = TransmissionStatusType::CONNECTION_FAILED; @@ -2282,7 +2282,7 @@ TransmissionStatusType EspnowMeshBackend::initiateAutoEncryptingTransmission(con return transmissionResult; } -void EspnowMeshBackend::finalizeAutoEncryptingConnection(const uint8_t *targetBSSID, const EncryptedConnectionLog *existingEncryptedConnection, bool requestPermanentConnection) +void EspnowMeshBackend::finalizeAutoEncryptingConnection(const uint8_t *targetBSSID, const EncryptedConnectionLog *existingEncryptedConnection, const bool requestPermanentConnection) { if(!existingEncryptedConnection && !requestPermanentConnection && !_reciprocalPeerRequestConfirmation) { @@ -2291,7 +2291,7 @@ void EspnowMeshBackend::finalizeAutoEncryptingConnection(const uint8_t *targetBS } } -void EspnowMeshBackend::attemptAutoEncryptingTransmission(const String &message, bool requestPermanentConnections, bool scan, bool scanAllWiFiChannels) +void EspnowMeshBackend::attemptAutoEncryptingTransmission(const String &message, const bool requestPermanentConnections, const bool scan, const bool scanAllWiFiChannels) { MutexTracker outerMutexTracker(_espnowTransmissionMutex, handlePostponedRemovals); if(!outerMutexTracker.mutexCaptured()) @@ -2338,7 +2338,7 @@ void EspnowMeshBackend::attemptAutoEncryptingTransmission(const String &message, printTransmissionStatistics(); } -TransmissionStatusType EspnowMeshBackend::attemptAutoEncryptingTransmission(const String &message, const EspnowNetworkInfo &recipientInfo, bool requestPermanentConnection) +TransmissionStatusType EspnowMeshBackend::attemptAutoEncryptingTransmission(const String &message, const EspnowNetworkInfo &recipientInfo, const bool requestPermanentConnection) { uint8_t targetBSSID[6] {0}; EncryptedConnectionLog *existingEncryptedConnection = nullptr; @@ -2370,11 +2370,11 @@ void EspnowMeshBackend::broadcast(const String &message) espnowSendToNode(message, broadcastMac, 'B', this); } -void EspnowMeshBackend::setBroadcastTransmissionRedundancy(uint8_t redundancy) { _broadcastTransmissionRedundancy = redundancy; } -uint8_t EspnowMeshBackend::getBroadcastTransmissionRedundancy() { return _broadcastTransmissionRedundancy; } +void EspnowMeshBackend::setBroadcastTransmissionRedundancy(const uint8_t redundancy) { _broadcastTransmissionRedundancy = redundancy; } +uint8_t EspnowMeshBackend::getBroadcastTransmissionRedundancy() const { return _broadcastTransmissionRedundancy; } -void EspnowMeshBackend::setResponseTransmittedHook(responseTransmittedHookType responseTransmittedHook) { _responseTransmittedHook = responseTransmittedHook; } -EspnowMeshBackend::responseTransmittedHookType EspnowMeshBackend::getResponseTransmittedHook() { return _responseTransmittedHook; } +void EspnowMeshBackend::setResponseTransmittedHook(const responseTransmittedHookType responseTransmittedHook) { _responseTransmittedHook = responseTransmittedHook; } +EspnowMeshBackend::responseTransmittedHookType EspnowMeshBackend::getResponseTransmittedHook() const { return _responseTransmittedHook; } void EspnowMeshBackend::sendStoredEspnowMessages(const ExpiringTimeTracker *estimatedMaxDurationTracker) { @@ -2587,7 +2587,7 @@ uint32_t EspnowMeshBackend::getMaxMessageBytesPerTransmission() return getMaxBytesPerTransmission() - espnowMetadataSize(); } -void EspnowMeshBackend::setMaxTransmissionsPerMessage(uint8_t maxTransmissionsPerMessage) +void EspnowMeshBackend::setMaxTransmissionsPerMessage(const uint8_t maxTransmissionsPerMessage) { assert(1 <= maxTransmissionsPerMessage && maxTransmissionsPerMessage <= 128); @@ -2646,7 +2646,7 @@ ConnectionType EspnowMeshBackend::getConnectionInfo(uint8_t *peerMac, uint32_t * return getConnectionInfoHelper(encryptedConnection, remainingDuration); } -ConnectionType EspnowMeshBackend::getConnectionInfo(uint32_t connectionIndex, uint32_t *remainingDuration, uint8_t *peerMac) +ConnectionType EspnowMeshBackend::getConnectionInfo(const uint32_t connectionIndex, uint32_t *remainingDuration, uint8_t *peerMac) { EncryptedConnectionLog *encryptedConnection = nullptr; @@ -2694,7 +2694,7 @@ String EspnowMeshBackend::serializeEncryptedConnection(const uint8_t *peerMac) return serializedConnection; } -String EspnowMeshBackend::serializeEncryptedConnection(uint32_t connectionIndex) +String EspnowMeshBackend::serializeEncryptedConnection(const uint32_t connectionIndex) { String serializedConnection(emptyString); diff --git a/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.h b/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.h index 908cf3620..641d5c52e 100644 --- a/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.h +++ b/libraries/ESP8266WiFiMesh/src/EspnowMeshBackend.h @@ -107,7 +107,7 @@ enum class EncryptedConnectionStatus MAX_CONNECTIONS_REACHED_PEER = -1, API_CALL_FAILED = 0, CONNECTION_ESTABLISHED = 1, - SOFT_LIMIT_CONNECTION_ESTABLISHED = 2 // Only used if _encryptedConnectionsSoftLimit is less than 6. + SOFT_LIMIT_CONNECTION_ESTABLISHED = 2 // Only used if _encryptedConnectionsSoftLimit is less than 6. See the setEncryptedConnectionsSoftLimit method documentation for details. }; enum class EncryptedConnectionRemovalOutcome @@ -128,7 +128,7 @@ enum class EncryptedConnectionRemovalOutcome * * @param durationMs The shortest allowed delay duration, in milliseconds. */ -void espnowDelay(uint32_t durationMs); +void espnowDelay(const uint32_t durationMs); class RequestData; @@ -166,10 +166,10 @@ public: * make it impossible for other stations to detect the APs whose WiFi channels have changed. * */ - EspnowMeshBackend(requestHandlerType requestHandler, responseHandlerType responseHandler, networkFilterType networkFilter, broadcastFilterType broadcastFilter, + EspnowMeshBackend(const requestHandlerType requestHandler, const responseHandlerType responseHandler, const networkFilterType networkFilter, const broadcastFilterType broadcastFilter, const String &meshPassword, const uint8_t espnowEncryptedConnectionKey[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength], const uint8_t espnowHashKey[EspnowProtocolInterpreter::espnowHashKeyLength], const String &ssidPrefix, - const String &ssidSuffix, bool verboseMode = false, uint8 meshWiFiChannel = 1); + const String &ssidSuffix, const bool verboseMode = false, const uint8 meshWiFiChannel = 1); /** * ESP-NOW constructor method. Creates an ESP-NOW node, ready to be initialised. @@ -194,9 +194,9 @@ public: * make it impossible for other stations to detect the APs whose WiFi channels have changed. * */ - EspnowMeshBackend(requestHandlerType requestHandler, responseHandlerType responseHandler, networkFilterType networkFilter, broadcastFilterType broadcastFilter, + EspnowMeshBackend(const requestHandlerType requestHandler, const responseHandlerType responseHandler, const networkFilterType networkFilter, const broadcastFilterType broadcastFilter, const String &meshPassword, const String &espnowEncryptedConnectionKeySeed, const String &espnowHashKeySeed, const String &ssidPrefix, - const String &ssidSuffix, bool verboseMode = false, uint8 meshWiFiChannel = 1); + const String &ssidSuffix, const bool verboseMode = false, const uint8 meshWiFiChannel = 1); ~EspnowMeshBackend() override; @@ -249,7 +249,7 @@ public: * Note that setting the estimatedMaxDuration too low may result in missed ESP-NOW transmissions because of too little time for maintenance. * Also note that although the method will try to respect the max duration limit, there is no guarantee. Overshoots by tens of milliseconds are possible. */ - static void performEspnowMaintenance(uint32_t estimatedMaxDuration = 0); + static void performEspnowMaintenance(const uint32_t estimatedMaxDuration = 0); /** * At critical heap level no more incoming requests are accepted. @@ -271,7 +271,7 @@ public: * If the buffer is set to 0 bytes a significant number of incoming requests are likely to be lost during intense transmission activity, * and there is a greater risk of heap space completely running out before log clearing occurs (which may cause crashes or empty transmissions). */ - static void setCriticalHeapLevelBuffer(uint32_t bufferInBytes); + static void setCriticalHeapLevelBuffer(const uint32_t bufferInBytes); static uint32_t criticalHeapLevelBuffer(); /** @@ -281,7 +281,7 @@ public: */ static bool deactivateEspnow(); - void attemptTransmission(const String &message, bool scan = true, bool scanAllWiFiChannels = false) override; + void attemptTransmission(const String &message, const bool scan = true, const bool scanAllWiFiChannels = false) override; /** * Transmit message to a single recipient without changing the local transmission state. @@ -315,13 +315,13 @@ public: * Note that if the ESP8266 has an active AP, that AP will switch WiFi channel to match that of any other AP the ESP8266 connects to. * This can make it impossible for other nodes to detect the AP if they are scanning the wrong WiFi channel. */ - void attemptAutoEncryptingTransmission(const String &message, bool requestPermanentConnections = false, bool scan = true, bool scanAllWiFiChannels = false); + void attemptAutoEncryptingTransmission(const String &message, const bool requestPermanentConnections = false, const bool scan = true, const bool scanAllWiFiChannels = false); /** * Transmit message to a single recipient without changing the local transmission state (apart from encrypted connections). * Will not change connectionQueue, latestTransmissionOutcomes or stored message. */ - TransmissionStatusType attemptAutoEncryptingTransmission(const String &message, const EspnowNetworkInfo &recipientInfo, bool requestPermanentConnection = false); + TransmissionStatusType attemptAutoEncryptingTransmission(const String &message, const EspnowNetworkInfo &recipientInfo, const bool requestPermanentConnection = false); /** * Send a message simultaneously to all nearby nodes which have ESP-NOW activated. @@ -340,8 +340,8 @@ public: * * @param redundancy The number of extra transmissions to make of each broadcast. Defaults to 1. */ - void setBroadcastTransmissionRedundancy(uint8_t redundancy); - uint8_t getBroadcastTransmissionRedundancy(); + void setBroadcastTransmissionRedundancy(const uint8_t redundancy); + uint8_t getBroadcastTransmissionRedundancy() const; /** * Set the EspnowMeshBackend instance responsible for handling incoming requests. The requestHandler of the instance will be called upon receiving ESP-NOW requests. @@ -358,7 +358,7 @@ public: * * @return True if this EspnowMeshBackend is the espnowRequestManager. False otherwise. */ - bool isEspnowRequestManager(); + bool isEspnowRequestManager() const; /** * Set the duration of most ESP-NOW log entries. Used for all ESP-NOW communication except for broadcasts and encrypted connection requests. @@ -369,7 +369,7 @@ public: * * @param logEntryLifetimeMs The duration to use for most ESP-NOW log entries, in milliseconds. */ - static void setLogEntryLifetimeMs(uint32_t logEntryLifetimeMs); + static void setLogEntryLifetimeMs(const uint32_t logEntryLifetimeMs); static uint32_t logEntryLifetimeMs(); /** @@ -383,7 +383,7 @@ public: * * @param broadcastResponseTimeoutMs The duration sent ESP-NOW broadcasts will be stored in the log, in milliseconds. */ - static void setBroadcastResponseTimeoutMs(uint32_t broadcastResponseTimeoutMs); + static void setBroadcastResponseTimeoutMs(const uint32_t broadcastResponseTimeoutMs); static uint32_t broadcastResponseTimeoutMs(); /** @@ -420,8 +420,8 @@ public: * * @return The current espnowEncryptedConnectionKey for this EspnowMeshBackend instance. */ - const uint8_t *getEspnowEncryptedConnectionKey(); - uint8_t *getEspnowEncryptedConnectionKey(uint8_t resultArray[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength]); + const uint8_t *getEspnowEncryptedConnectionKey() const; + uint8_t *getEspnowEncryptedConnectionKey(uint8_t resultArray[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength]) const; /** * Change the key used to encrypt/decrypt the encrypted connection key when creating encrypted ESP-NOW connections. (Kok = key of keys, perhaps) If no Kok is provided by the user, a default Kok is used. @@ -486,7 +486,7 @@ public: */ void setEspnowHashKey(const String &espnowHashKeySeed); - const uint8_t *getEspnowHashKey(); + const uint8_t *getEspnowHashKey() const; /** * Change the key used to encrypt/decrypt messages when using AEAD encryption. @@ -496,7 +496,7 @@ public: * * @param espnowMessageEncryptionKey An array containing the CryptoInterface::ENCRYPTION_KEY_LENGTH bytes that will be used as the message encryption key. */ - static void setEspnowMessageEncryptionKey(uint8_t espnowMessageEncryptionKey[CryptoInterface::ENCRYPTION_KEY_LENGTH]); + static void setEspnowMessageEncryptionKey(const uint8_t espnowMessageEncryptionKey[CryptoInterface::ENCRYPTION_KEY_LENGTH]); /** * Change the key used to encrypt/decrypt messages when using AEAD encryption. @@ -532,7 +532,7 @@ public: * * @param useEncryptedMessages If true, AEAD encryption/decryption is enabled. If false, AEAD encryption/decryption is disabled. */ - static void setUseEncryptedMessages(bool useEncryptedMessages); + static void setUseEncryptedMessages(const bool useEncryptedMessages); static bool useEncryptedMessages(); /** @@ -556,7 +556,7 @@ public: * * @param maxTransmissionsPerMessage The maximum acceptable message length, in terms of transmissions, when sending a message from this node. Valid values are 1 to 128. Defaults to 3. */ - static void setMaxTransmissionsPerMessage(uint8_t maxTransmissionsPerMessage); + static void setMaxTransmissionsPerMessage(const uint8_t maxTransmissionsPerMessage); static uint8_t getMaxTransmissionsPerMessage(); /** @@ -574,8 +574,8 @@ public: * * @param enabled If true, library Serial prints are activated. */ - void setVerboseModeState(bool enabled) override; - bool verboseMode() override; + void setVerboseModeState(const bool enabled) override; + bool verboseMode() const override; /** * Only print stringToPrint if verboseMode() returns true. @@ -583,7 +583,7 @@ public: * @param stringToPrint String to print. * @param newline If true, will end the print with a newline. True by default. */ - void verboseModePrint(const String &stringToPrint, bool newline = true) override; + void verboseModePrint(const String &stringToPrint, const bool newline = true) const override; /** * Same as verboseMode(), but used for printing from static functions. @@ -598,7 +598,7 @@ public: * @param stringToPrint String to print. * @param newline If true, will end the print with a newline. True by default. */ - static void staticVerboseModePrint(const String &stringToPrint, bool newline = true); + static void staticVerboseModePrint(const String &stringToPrint, const bool newline = true); /** * Get the message of the response at responseIndex among the responses that are scheduled for transmission from this node. @@ -606,7 +606,7 @@ public: * @param responseIndex The index of the response. Must be lower than numberOfScheduledResponses(). * @return A String containing the message of the response at responseIndex. */ - static String getScheduledResponseMessage(uint32_t responseIndex); + static String getScheduledResponseMessage(const uint32_t responseIndex); /** * Get the MAC address for the recipient of the response at responseIndex among the responses that are scheduled for transmission from this node. @@ -614,7 +614,7 @@ public: * @param responseIndex The index of the response. Must be lower than numberOfScheduledResponses(). * @return An array with six bytes containing the MAC address for the recipient of the response at responseIndex. */ - static const uint8_t *getScheduledResponseRecipient(uint32_t responseIndex); + static const uint8_t *getScheduledResponseRecipient(const uint32_t responseIndex); /** * Get the number of ESP-NOW responses that are scheduled for transmission from this node. @@ -637,7 +637,7 @@ public: * @param recipientMac The MAC address of the response recipient. * @param encryptedOnly If true, only responses to encrypted requests will be deleted. */ - static void deleteScheduledResponsesByRecipient(const uint8_t *recipientMac, bool encryptedOnly); + static void deleteScheduledResponsesByRecipient(const uint8_t *recipientMac, const bool encryptedOnly); /** * Set the timeout to use for each ESP-NOW transmission when transmitting. @@ -646,7 +646,7 @@ public: * * @param timeoutMs The timeout that should be used for each ESP-NOW transmission, in milliseconds. Defaults to 40 ms. */ - static void setEspnowTransmissionTimeout(uint32_t timeoutMs); + static void setEspnowTransmissionTimeout(const uint32_t timeoutMs); static uint32_t getEspnowTransmissionTimeout(); /** @@ -656,18 +656,18 @@ public: * * @param intervalMs The time to wait for an ack after having made an ESP-NOW transmission, in milliseconds. Defaults to 15 ms. */ - static void setEspnowRetransmissionInterval(uint32_t intervalMs); + static void setEspnowRetransmissionInterval(const uint32_t intervalMs); static uint32_t getEspnowRetransmissionInterval(); // The maximum amount of time each of the two stages in an encrypted connection request may take. - static void setEncryptionRequestTimeout(uint32_t timeoutMs); + static void setEncryptionRequestTimeout(const uint32_t timeoutMs); static uint32_t getEncryptionRequestTimeout(); - void setAutoEncryptionDuration(uint32_t duration); - uint32_t getAutoEncryptionDuration(); + void setAutoEncryptionDuration(const uint32_t duration); + uint32_t getAutoEncryptionDuration() const; - void setBroadcastFilter(broadcastFilterType broadcastFilter); - broadcastFilterType getBroadcastFilter(); + void setBroadcastFilter(const broadcastFilterType broadcastFilter); + broadcastFilterType getBroadcastFilter() const; /** * Set a function that should be called after each successful ESP-NOW response transmission, just before the response is removed from the waiting list. @@ -679,8 +679,8 @@ public: * If it is false, the response transmission process will stop after removing the just sent response from the waiting list. * The default responseTransmittedHook always returns true. */ - void setResponseTransmittedHook(responseTransmittedHookType responseTransmittedHook); - responseTransmittedHookType getResponseTransmittedHook(); + void setResponseTransmittedHook(const responseTransmittedHookType responseTransmittedHook); + responseTransmittedHookType getResponseTransmittedHook() const; /** * Get the MAC address of the sender of the most recently received ESP-NOW request, response or broadcast to this EspnowMeshBackend instance. @@ -690,7 +690,7 @@ public: * * @return A String filled with a hexadecimal representation of the MAC, without delimiters. */ - String getSenderMac(); + String getSenderMac() const; /** * Get the MAC address of the sender of the most recently received ESP-NOW request, response or broadcast to this EspnowMeshBackend instance. @@ -701,7 +701,7 @@ public: * @param macArray The array that should store the MAC address. Must be at least 6 bytes. * @return macArray filled with the sender MAC. */ - uint8_t *getSenderMac(uint8_t *macArray); + uint8_t *getSenderMac(uint8_t *macArray) const; /** * Get the AP MAC address of the sender of the most recently received ESP-NOW request, response or broadcast to this EspnowMeshBackend instance. @@ -709,7 +709,7 @@ public: * * @return A String filled with a hexadecimal representation of the AP MAC, without delimiters. */ - String getSenderAPMac(); + String getSenderAPMac() const; /** * Get the AP MAC address of the sender of the most recently received ESP-NOW request, response or broadcast to this EspnowMeshBackend instance. @@ -718,14 +718,14 @@ public: * @param macArray The array that should store the MAC address. Must be at least 6 bytes. * @return macArray filled with the sender AP MAC. */ - uint8_t *getSenderAPMac(uint8_t *macArray); + uint8_t *getSenderAPMac(uint8_t *macArray) const; /** * Get whether the ESP-NOW request, response or broadcast which was most recently received by this EspnowMeshBackend instance was sent over an encrypted connection or not. * * @return If true, the request, response or broadcast was sent over an encrypted connection. If false, the connection was unencrypted. */ - bool receivedEncryptedTransmission(); + bool receivedEncryptedTransmission() const; /** * Should be used together with serializeUnencryptedConnection() if the node sends unencrypted transmissions @@ -737,35 +737,135 @@ public: * @return True if connection was added. False otherwise (e.g. if there is faulty input). */ static bool addUnencryptedConnection(const String &serializedConnectionState); - - // Updates connection with current stored encrypted connection key. - // At least one of the leftmost 32 bits in each of the session keys should be 1, since the key otherwise indicates the connection is unencrypted. - EncryptedConnectionStatus addEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, uint64_t peerSessionKey, uint64_t ownSessionKey); - // Note that the espnowEncryptedConnectionKey, espnowEncryptionKok, espnowHashKey and espnowMessageEncryptionKey are not serialized. - // These will be set to the values of the EspnowMeshBackend instance that is adding the serialized encrypted connection. - // @param ignoreDuration Ignores any stored duration serializedConnectionState, guaranteeing that the created connection will be permanent. Returns: EncryptedConnectionStatus::REQUEST_TRANSMISSION_FAILED indicates malformed serializedConnectionState. - EncryptedConnectionStatus addEncryptedConnection(const String &serializedConnectionState, bool ignoreDuration = false); - - // Adds a new temporary encrypted connection, or changes the duration of an existing temporary connection (only updates keys, not duration, for existing permanent connections). - // As with all these methods, changes will only take effect once the requester proves it has the ability to decrypt the session key. - // At least one of the leftmost 32 bits in each of the session keys should be 1, since the key otherwise indicates the connection is unencrypted. - EncryptedConnectionStatus addTemporaryEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, uint64_t peerSessionKey, uint64_t ownSessionKey, uint32_t duration); - // Note that the espnowEncryptedConnectionKey, espnowEncryptionKok, espnowHashKey and espnowMessageEncryptionKey are not serialized. - // These will be set to the values of the EspnowMeshBackend instance that is adding the serialized encrypted connection. - // Uses duration argument instead of any stored duration in serializedConnectionState. Returns: EncryptedConnectionStatus::REQUEST_TRANSMISSION_FAILED indicates malformed serializedConnectionState. - EncryptedConnectionStatus addTemporaryEncryptedConnection(const String &serializedConnectionState, uint32_t duration); - // If an encrypted connection to peerMac already exists, only connection duration is updated. All other settings are kept as is. Use removeEncryptedConnection/requestEncryptedConnectionRemoval first if encryption keys should be updated. - // Makes sure both nodes have an encrypted connection to each other that's permanent. - EncryptedConnectionStatus requestEncryptedConnection(uint8_t *peerMac); - // Makes sure both nodes have an encrypted connection to each other that's either permanent or has the duration specified. - EncryptedConnectionStatus requestTemporaryEncryptedConnection(uint8_t *peerMac, uint32_t durationMs); - // Makes sure both nodes have an encrypted connection to each other that's either permanent or has at least the duration specified. - // Note that if a temporary encrypted connection already exists to a target node, this method will slightly extend the connection duration - // depending on the time it takes to verify the connection to the node. - EncryptedConnectionStatus requestFlexibleTemporaryEncryptedConnection(uint8_t *peerMac, uint32_t minDurationMs); - static EncryptedConnectionRemovalOutcome removeEncryptedConnection(uint8_t *peerMac); - EncryptedConnectionRemovalOutcome requestEncryptedConnectionRemoval(uint8_t *peerMac); + /** + * Adds a new permanent encrypted ESP-NOW connection, or makes the duration of an existing temporary connection permanent. + * Note that this will not add an encrypted ESP-NOW connection automatically to the other node. Thus the same method will need to be called on the other node as well to establish an encrypted connection. + * Methods such as requestEncryptedConnection creates an encrypted connection automatically in both nodes, but requires information exchange between the nodes before the connection is established (and is thus much slower). + * + * When called, the method will update an existing encrypted ESP-NOW connection with the current stored encrypted connection key. (in case it has changed since the connection was established) + * + * @param peerStaMac The station MAC of the other node. + * @param peerApMac The AP MAC of the other node. + * @param peerSessionKey The session key of the other node. At least one of the leftmost 32 bits should be 1, since the key otherwise indicates the connection is unencrypted. + * @param peerSessionKey The session key of this node. At least one of the leftmost 32 bits should be 1, since the key otherwise indicates the connection is unencrypted. + * + * @return EncryptedConnectionStatus::CONNECTION_ESTABLISHED if the connection was created. Otherwise another status code based on the outcome. + */ + EncryptedConnectionStatus addEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, const uint64_t peerSessionKey, const uint64_t ownSessionKey); + + /** + * Create an encrypted ESP-NOW connection on this node based on the information stored in serializedConnectionState. + * Note that this will not add an encrypted ESP-NOW connection automatically to the other node. Thus the same method will need to be called on the other node as well to establish an encrypted connection. + * Methods such as requestEncryptedConnection creates an encrypted connection automatically in both nodes, but requires information exchange between the nodes before the connection is established (and is thus much slower). + * + * When called, the method will update an existing encrypted ESP-NOW connection with the current stored encrypted connection key. (in case it has changed since the connection was established) + * + * Note that the espnowEncryptedConnectionKey, espnowEncryptionKok, espnowHashKey and espnowMessageEncryptionKey are not serialized. + * These will be set to the values of the EspnowMeshBackend instance that is adding the serialized encrypted connection. + * + * @param serializedConnectionState A String containing the serialized connection state. + * @param ignoreDuration Ignores any stored duration in serializedConnectionState, guaranteeing that the created connection will be permanent. + * + * @return EncryptedConnectionStatus::CONNECTION_ESTABLISHED if the connection was created. Otherwise another status code based on the outcome. EncryptedConnectionStatus::REQUEST_TRANSMISSION_FAILED indicates a malformed serializedConnectionState. + */ + EncryptedConnectionStatus addEncryptedConnection(const String &serializedConnectionState, const bool ignoreDuration = false); + + /** + * Adds a new temporary encrypted ESP-NOW connection, or changes the duration of an existing temporary connection (only updates keys, not duration, for existing permanent connections). + * Note that this will not add an encrypted ESP-NOW connection automatically to the other node. Thus the same method will need to be called on the other node as well to establish an encrypted connection. + * Methods such as requestEncryptedConnection creates an encrypted connection automatically in both nodes, but requires information exchange between the nodes before the connection is established (and is thus much slower). + * + * When called, the method will update an existing encrypted ESP-NOW connection with the current stored encrypted connection key. (in case it has changed since the connection was established) + * + * As with all these methods, changes will only take effect once the requester proves it has the ability to decrypt the session key. + * + * @param peerStaMac The station MAC of the other node. + * @param peerApMac The AP MAC of the other node. + * @param peerSessionKey The session key of the other node. At least one of the leftmost 32 bits should be 1, since the key otherwise indicates the connection is unencrypted. + * @param peerSessionKey The session key of this node. At least one of the leftmost 32 bits should be 1, since the key otherwise indicates the connection is unencrypted. + * @param duration The desired duration of the connection. + * + * @return EncryptedConnectionStatus::CONNECTION_ESTABLISHED if the connection was created. Otherwise another status code based on the outcome. + */ + EncryptedConnectionStatus addTemporaryEncryptedConnection(uint8_t *peerStaMac, uint8_t *peerApMac, const uint64_t peerSessionKey, const uint64_t ownSessionKey, const uint32_t duration); + + /** + * Create a temporary encrypted ESP-NOW connection on this node based on the information stored in serializedConnectionState. + * Note that this will not add an encrypted ESP-NOW connection automatically to the other node. Thus the same method will need to be called on the other node as well to establish an encrypted connection. + * Methods such as requestEncryptedConnection creates an encrypted connection automatically in both nodes, but requires information exchange between the nodes before the connection is established (and is thus much slower). + * + * When called, the method will update an existing encrypted ESP-NOW connection with the current stored encrypted connection key. (in case it has changed since the connection was established) + * + * Note that the espnowEncryptedConnectionKey, espnowEncryptionKok, espnowHashKey and espnowMessageEncryptionKey are not serialized. + * These will be set to the values of the EspnowMeshBackend instance that is adding the serialized encrypted connection. + * + * @param serializedConnectionState A String containing the serialized connection state. + * @param ignoreDuration Ignores any stored duration in serializedConnectionState, guaranteeing that the created connection will be permanent. + * @param duration The desired duration of the connection. Overrides any stored duration in the serializedConnectionState. + * + * @return EncryptedConnectionStatus::CONNECTION_ESTABLISHED if the connection was created. Otherwise another status code based on the outcome. EncryptedConnectionStatus::REQUEST_TRANSMISSION_FAILED indicates a malformed serializedConnectionState. + */ + EncryptedConnectionStatus addTemporaryEncryptedConnection(const String &serializedConnectionState, const uint32_t duration); + + /** + * Request a permanent encrypted ESP-NOW connection with the node that uses peerMac. + * If an encrypted connection to peerMac already exists, only connection duration is updated. All other settings are kept as is. Use removeEncryptedConnection/requestEncryptedConnectionRemoval first if encryption keys should be updated. + * The method makes sure both nodes have an encrypted connection to each other that's permanent. + * + * @param peerMac The MAC of the other node to which the request should be sent. + * + * @return EncryptedConnectionStatus::CONNECTION_ESTABLISHED if the permanent connection was created. EncryptedConnectionStatus::SOFT_LIMIT_CONNECTION_ESTABLISHED if only a temporary soft limit connection could be established (see the setEncryptedConnectionsSoftLimit method documentation for details). Otherwise another status code based on the outcome. + */ + EncryptedConnectionStatus requestEncryptedConnection(const uint8_t *peerMac); + + /** + * Request a temporary encrypted ESP-NOW connection with the node that uses peerMac. + * If a temporary encrypted connection to peerMac already exists, only connection duration is updated. All other settings are kept as is. Permanent connections are not modified. Use removeEncryptedConnection/requestEncryptedConnectionRemoval first if encryption keys should be updated. + * The method makes sure both nodes have an encrypted connection to each other that's either permanent or has exactly the duration specified. + * + * @param peerMac The MAC of the other node to which the request should be sent. + * @param durationMs The desired duration of the connection. + * + * @return EncryptedConnectionStatus::CONNECTION_ESTABLISHED if the request was succesful. EncryptedConnectionStatus::SOFT_LIMIT_CONNECTION_ESTABLISHED if only a temporary soft limit connection could be established (see the setEncryptedConnectionsSoftLimit method documentation for details). Otherwise another status code based on the outcome. + */ + EncryptedConnectionStatus requestTemporaryEncryptedConnection(const uint8_t *peerMac, const uint32_t durationMs); + + /** + * Request a flexible temporary encrypted ESP-NOW connection with the node that uses peerMac. + * If a temporary encrypted connection to peerMac with a shorter duration already exists, connection duration is updated. All other settings are kept as is. Permanent connections are not modified. Use removeEncryptedConnection/requestEncryptedConnectionRemoval first if encryption keys should be updated. + * The method makes sure both nodes have an encrypted connection to each other that's either permanent or has at least the duration specified. + * + * Note that if a temporary encrypted connection already exists to a target node, this method will slightly extend the connection duration + * depending on the time it takes to verify the connection to the node. + * + * @param peerMac The MAC of the other node to which the request should be sent. + * @param minDurationMs The desired minimum duration of the connection. + * + * @return EncryptedConnectionStatus::CONNECTION_ESTABLISHED if the request was succesful. EncryptedConnectionStatus::SOFT_LIMIT_CONNECTION_ESTABLISHED if only a temporary soft limit connection could be established (see the setEncryptedConnectionsSoftLimit method documentation for details). Otherwise another status code based on the outcome. + */ + EncryptedConnectionStatus requestFlexibleTemporaryEncryptedConnection(const uint8_t *peerMac, const uint32_t minDurationMs); + + /** + * Remove the encrypted ESP-NOW connection to peerMac from this node. + * Note that this will not remove the encrypted ESP-NOW connection automatically from the other node. Thus the same method will need to be called on the other node as well to complete the encrypted connection removal. + * The method requestEncryptedConnectionRemoval removes the encrypted connection automatically in both nodes, but requires extra information exchange between the nodes (and is thus much slower). + * + * @param peerMac The MAC of the other node. + * + * @return EncryptedConnectionRemovalOutcome::REMOVAL_SUCCEEDED if the removal succeeded. EncryptedConnectionRemovalOutcome::REMOVAL_SCHEDULED if the removal is scheduled to occur as soon as it is safe to do so (generally as soon as an ongoing transmission is complete, or at the latest during the next performEspnowMaintenance call). Otherwise another status code based on the outcome. + */ + static EncryptedConnectionRemovalOutcome removeEncryptedConnection(const uint8_t *peerMac); + + /** + * Request the removal of the encrypted ESP-NOW connection between this node and the node that uses peerMac. + * The method makes sure both nodes remove the encrypted connection to each other. + * + * @param peerMac The MAC of the other node to which the request should be sent. + * + * @return EncryptedConnectionRemovalOutcome::REMOVAL_SUCCEEDED if the removal succeeded. Otherwise another status code based on the outcome (never REMOVAL_SCHEDULED). + */ + EncryptedConnectionRemovalOutcome requestEncryptedConnectionRemoval(const uint8_t *peerMac); /** * Set whether this EspnowMeshBackend instance will accept ESP-NOW requests from unencrypted connections or not, when acting as EspnowRequestManager. @@ -777,8 +877,8 @@ public: * * @param acceptsUnverifiedRequests If and only if true, requests from unencrypted connections will be processed when this EspnowMeshBackend instance is acting as EspnowRequestManager. */ - void setAcceptsUnverifiedRequests(bool acceptsUnverifiedRequests); - bool acceptsUnverifiedRequests(); + void setAcceptsUnverifiedRequests(const bool acceptsUnverifiedRequests); + bool acceptsUnverifiedRequests() const; /** * Set a soft upper limit on the number of encrypted connections this node can have when receiving encrypted connection requests. @@ -795,15 +895,17 @@ public: * * @param softLimit The new soft limit. Valid values are 0 to 6. */ - void setEncryptedConnectionsSoftLimit(uint8_t softLimit); - uint8_t encryptedConnectionsSoftLimit(); + void setEncryptedConnectionsSoftLimit(const uint8_t softLimit); + uint8_t encryptedConnectionsSoftLimit() const; /** * @return The current number of encrypted ESP-NOW connections. */ static uint8_t numberOfEncryptedConnections(); - // @return resultArray filled with the MAC to the encrypted interface of the node, if an encrypted connection exists. nulltpr otherwise. + /** + * @return resultArray filled with the MAC to the encrypted interface of the node, if an encrypted connection exists. nulltpr otherwise. + */ static uint8_t *getEncryptedMac(const uint8_t *peerMac, uint8_t *resultArray); /** @@ -815,12 +917,14 @@ public: */ static String serializeUnencryptedConnection(); - // Create a string containing the current state of the encrypted connection for this node. The result can be used as input to addEncryptedConnection. - // Note that transferring the serialized state over an unencrypted connection will compromise the security of the stored connection. - // Also note that this saves the current state only, so if encrypted communication between the nodes happen after this, the stored state is invalid. - // @return A String containing the serialized encrypted connection, or an empty String if there is no matching encrypted connection. + /** + * Create a string containing the current state of the encrypted connection for this node. The result can be used as input to addEncryptedConnection. + * Note that transferring the serialized state over an unencrypted connection will compromise the security of the stored connection. + * Also note that this saves the current state only, so if encrypted communication between the nodes happen after this, the stored state is invalid. + * @return A String containing the serialized encrypted connection, or an empty String if there is no matching encrypted connection. + */ static String serializeEncryptedConnection(const uint8_t *peerMac); - static String serializeEncryptedConnection(uint32_t connectionIndex); + static String serializeEncryptedConnection(const uint32_t connectionIndex); /** * Get information about any current ESP-NOW connection with another node. @@ -845,7 +949,7 @@ public: * Otherwise the array is not modified. * @return The ConnectionType of the connection given by connectionIndex. */ - static ConnectionType getConnectionInfo(uint32_t connectionIndex, uint32_t *remainingDuration = nullptr, uint8_t *peerMac = nullptr); + static ConnectionType getConnectionInfo(const uint32_t connectionIndex, uint32_t *remainingDuration = nullptr, uint8_t *peerMac = nullptr); /** * @return The proportion of ESP-NOW requests made by this node that have failed, since power on or latest reset. @@ -870,7 +974,7 @@ protected: bool activateEspnow(); - static bool encryptedConnectionEstablished(EncryptedConnectionStatus connectionStatus); + static bool encryptedConnectionEstablished(const EncryptedConnectionStatus connectionStatus); /* * Note that ESP-NOW is not perfect and in rare cases messages may be dropped. @@ -902,7 +1006,7 @@ protected: static uint32_t getMaxBytesPerTransmission(); - static std::list::const_iterator getScheduledResponse(uint32_t responseIndex); + static std::list::const_iterator getScheduledResponse(const uint32_t responseIndex); // Note that removing an encrypted connection while there are encrypted responses scheduled for transmission to the encrypted peer will cause these encrypted responses to be removed without being sent. // Also note that removing an encrypted connection while there is encrypted data to be received will make the node unable to decrypt that data (although an ack will still be sent to confirm data reception). @@ -918,23 +1022,23 @@ protected: * * @param macArray An uint8_t array which contains the MAC address to store. The method will store the first 6 bytes of the array. */ - void setSenderMac(uint8_t *macArray); + void setSenderMac(const uint8_t *macArray); /** * Set the MAC address considered to be the AP MAC of the sender of the most recently received ESP-NOW request, response or broadcast. * * @param macArray An uint8_t array which contains the MAC address to store. The method will store the first 6 bytes of the array. */ - void setSenderAPMac(uint8_t *macArray); + void setSenderAPMac(const uint8_t *macArray); /** * Set whether the most recently received ESP-NOW request, response or broadcast is presented as having been sent over an encrypted connection or not * * @param receivedEncryptedTransmission If true, the request, response or broadcast is presented as having been sent over an encrypted connection. */ - void setReceivedEncryptedTransmission(bool receivedEncryptedTransmission); + void setReceivedEncryptedTransmission(const bool receivedEncryptedTransmission); - static bool temporaryEncryptedConnectionToPermanent(uint8_t *peerMac); + static bool temporaryEncryptedConnectionToPermanent(const uint8_t *peerMac); /** * Will be true if a transmission initiated by a public method is in progress. @@ -962,7 +1066,7 @@ protected: using messageID_td = uint64_t; using peerMac_td = uint64_t; - static macAndType_td createMacAndTypeValue(uint64_t uint64Mac, char messageType); + static macAndType_td createMacAndTypeValue(const uint64_t uint64Mac, const char messageType); static uint64_t macAndTypeToUint64Mac(const macAndType_td &macAndTypeValue); /** @@ -974,12 +1078,12 @@ protected: * @param encryptedOnly If true, only entries sent/received by encrypted transmissions will be deleted. */ template - static void deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, bool encryptedOnly); + static void deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, const bool encryptedOnly); template - static void deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, bool encryptedOnly); + static void deleteEntriesByMac(std::map, T> &logEntries, const uint8_t *peerMac, const bool encryptedOnly); - static bool requestReceived(uint64_t requestMac, uint64_t requestID); + static bool requestReceived(const uint64_t requestMac, const uint64_t requestID); /** * Send an ESP-NOW message to the ESP8266 that has the MAC address specified in targetBSSID. @@ -989,17 +1093,17 @@ protected: * @return The transmission status for the transmission. */ // Send a message to the node having targetBSSID as mac, changing targetBSSID to the mac of the encrypted connection if it exists and ensuring such an encrypted connection is synchronized. - static TransmissionStatusType espnowSendToNode(const String &message, const uint8_t *targetBSSID, char messageType, EspnowMeshBackend *espnowInstance = nullptr); + static TransmissionStatusType espnowSendToNode(const String &message, const uint8_t *targetBSSID, const char messageType, EspnowMeshBackend *espnowInstance = nullptr); // Send a message using exactly the arguments given, without consideration for any encrypted connections. - static TransmissionStatusType espnowSendToNodeUnsynchronized(const String message, const uint8_t *targetBSSID, char messageType, uint64_t messageID, EspnowMeshBackend *espnowInstance = nullptr); + static TransmissionStatusType espnowSendToNodeUnsynchronized(const String message, const uint8_t *targetBSSID, const char messageType, const uint64_t messageID, EspnowMeshBackend *espnowInstance = nullptr); TransmissionStatusType sendRequest(const String &message, const uint8_t *targetBSSID); - TransmissionStatusType sendResponse(const String &message, uint64_t requestID, const uint8_t *targetBSSID); + TransmissionStatusType sendResponse(const String &message, const uint64_t requestID, const uint8_t *targetBSSID); private: - EspnowMeshBackend(requestHandlerType requestHandler, responseHandlerType responseHandler, networkFilterType networkFilter, broadcastFilterType broadcastFilter, - const String &meshPassword, const String &ssidPrefix, const String &ssidSuffix, bool verboseMode, uint8 meshWiFiChannel); + EspnowMeshBackend(const requestHandlerType requestHandler, const responseHandlerType responseHandler, const networkFilterType networkFilter, const broadcastFilterType broadcastFilter, + const String &meshPassword, const String &ssidPrefix, const String &ssidSuffix, const bool verboseMode, const uint8 meshWiFiChannel); using encryptionRequestBuilderType = std::function; static String defaultEncryptionRequestBuilder(const String &requestHeader, const uint32_t durationMs, const uint8_t *hashKey, const String &requestNonce, const ExpiringTimeTracker &existingTimeTracker); @@ -1011,19 +1115,19 @@ private: * This method is very time critical so avoid Serial printing in it and in methods called from it (such as espnowReceiveCallback) as much as possible. * Otherwise transmission fail rate is likely to skyrocket. */ - static void espnowReceiveCallbackWrapper(uint8_t *macaddr, uint8_t *dataArray, uint8_t len); - void espnowReceiveCallback(uint8_t *macaddr, uint8_t *data, uint8_t len); + static void espnowReceiveCallbackWrapper(uint8_t *macaddr, uint8_t *dataArray, const uint8_t len); + void espnowReceiveCallback(const uint8_t *macaddr, uint8_t *data, const uint8_t len); - static void handlePeerRequest(uint8_t *macaddr, uint8_t *dataArray, uint8_t len, uint64_t uint64StationMac, uint64_t receivedMessageID); - static void handlePeerRequestConfirmation(uint8_t *macaddr, uint8_t *dataArray, uint8_t len); + static void handlePeerRequest(const uint8_t *macaddr, uint8_t *dataArray, const uint8_t len, const uint64_t uint64StationMac, const uint64_t receivedMessageID); + static void handlePeerRequestConfirmation(uint8_t *macaddr, uint8_t *dataArray, const uint8_t len); static void handlePostponedRemovals(); - static bool verifyPeerSessionKey(uint64_t sessionKey, const uint8_t *peerMac, char messageType); - static bool verifyPeerSessionKey(uint64_t sessionKey, EncryptedConnectionLog &encryptedConnection, uint64_t uint64PeerMac, char messageType); + static bool verifyPeerSessionKey(const uint64_t sessionKey, const uint8_t *peerMac, const char messageType); + static bool verifyPeerSessionKey(const uint64_t sessionKey, const EncryptedConnectionLog &encryptedConnection, const uint64_t uint64PeerMac, const char messageType); - static bool synchronizePeerSessionKey(uint64_t sessionKey, const uint8_t *peerMac); - static bool synchronizePeerSessionKey(uint64_t sessionKey, EncryptedConnectionLog &encryptedConnection); + static bool synchronizePeerSessionKey(const uint64_t sessionKey, const uint8_t *peerMac); + static bool synchronizePeerSessionKey(const uint64_t sessionKey, EncryptedConnectionLog &encryptedConnection); static const uint32_t _maxBytesPerTransmission = 250; static uint8_t _maxTransmissionsPerMessage; @@ -1071,18 +1175,18 @@ private: // Should only be used when there is no transmissions in progress, so it is safe to remove encrypted connections. In practice when _espnowTransmissionMutex is free. // @param scheduledRemovalOnly If true, only deletes encrypted connections where removalScheduled() is true. This means only connections which have been requested for removal will be deleted, // not other connections which have expired. - static void updateTemporaryEncryptedConnections(bool scheduledRemovalOnly = false); + static void updateTemporaryEncryptedConnections(const bool scheduledRemovalOnly = false); template - static void deleteExpiredLogEntries(std::map, T> &logEntries, uint32_t maxEntryLifetimeMs); + static void deleteExpiredLogEntries(std::map, T> &logEntries, const uint32_t maxEntryLifetimeMs); template - static void deleteExpiredLogEntries(std::map, TimeTracker> &logEntries, uint32_t maxEntryLifetimeMs); + static void deleteExpiredLogEntries(std::map, TimeTracker> &logEntries, const uint32_t maxEntryLifetimeMs); - static void deleteExpiredLogEntries(std::map, RequestData> &logEntries, uint32_t requestLifetimeMs, uint32_t broadcastLifetimeMs); + static void deleteExpiredLogEntries(std::map, RequestData> &logEntries, const uint32_t requestLifetimeMs, const uint32_t broadcastLifetimeMs); template - static void deleteExpiredLogEntries(std::list &logEntries, uint32_t maxEntryLifetimeMs); + static void deleteExpiredLogEntries(std::list &logEntries, const uint32_t maxEntryLifetimeMs); static uint32_t _logEntryLifetimeMs; static uint32_t _broadcastResponseTimeoutMs; @@ -1106,9 +1210,9 @@ private: static bool _reciprocalPeerRequestConfirmation; template - static T *getMapValue(std::map &mapIn, uint64_t keyIn); + static T *getMapValue(std::map &mapIn, const uint64_t keyIn); - static bool usesConstantSessionKey(char messageType); + static bool usesConstantSessionKey(const char messageType); bool _acceptsUnverifiedRequests = true; @@ -1135,16 +1239,16 @@ private: * * @return A valid EspnowMeshBackend pointer if a matching entry is found in the EspnowMeshBackend sentRequests container. nullptr otherwise. */ - static EspnowMeshBackend *getOwnerOfSentRequest(uint64_t requestMac, uint64_t requestID); + static EspnowMeshBackend *getOwnerOfSentRequest(const uint64_t requestMac, const uint64_t requestID); /** * Delete all entries in the sentRequests container where requestMac is noted as having received requestID. * * @return The number of entries deleted. */ - static size_t deleteSentRequest(uint64_t requestMac, uint64_t requestID); + static size_t deleteSentRequest(const uint64_t requestMac, const uint64_t requestID); - static size_t deleteSentRequestsByOwner(EspnowMeshBackend *instancePointer); + static size_t deleteSentRequestsByOwner(const EspnowMeshBackend *instancePointer); /** * Contains the core logic used for requesting an encrypted connection to a peerMac. @@ -1155,7 +1259,7 @@ private: * The request message should typically be of the form: JsonTranslator::createEncryptionRequestIntro() + JsonTranslator::createEncryptionRequestEnding(). * @return The ultimate status of the requested encrypted connection, as EncryptedConnectionStatus. */ - EncryptedConnectionStatus requestEncryptedConnectionKernel(uint8_t *peerMac, const encryptionRequestBuilderType &encryptionRequestBuilder); + EncryptedConnectionStatus requestEncryptedConnectionKernel(const uint8_t *peerMac, const encryptionRequestBuilderType &encryptionRequestBuilder); /** * Generate a new message ID to be used when making a data transmission. The generated ID will be different depending on whether an encrypted connection exists or not. @@ -1163,7 +1267,7 @@ private: * @param encryptedConnection A pointer to the EncryptedConnectionLog of the encrypted connection. Can be set to nullptr if the connection is unecrypted. * @return The generated message ID. */ - static uint64_t generateMessageID(EncryptedConnectionLog *encryptedConnection); + static uint64_t generateMessageID(const EncryptedConnectionLog *encryptedConnection); /** * Create a new session key for an encrypted connection using the built in RANDOM_REG32 of the ESP8266. @@ -1174,14 +1278,14 @@ private: */ static uint64_t createSessionKey(); - void prepareForTransmission(const String &message, bool scan, bool scanAllWiFiChannels); + void prepareForTransmission(const String &message, const bool scan, const bool scanAllWiFiChannels); TransmissionStatusType initiateTransmission(const String &message, const EspnowNetworkInfo &recipientInfo); TransmissionStatusType initiateTransmissionKernel(const String &message, const uint8_t *targetBSSID); - void printTransmissionStatistics(); + void printTransmissionStatistics() const; - EncryptedConnectionStatus initiateAutoEncryptingConnection(const EspnowNetworkInfo &recipientInfo, bool requestPermanentConnection, uint8_t *targetBSSID, EncryptedConnectionLog **existingEncryptedConnection); - TransmissionStatusType initiateAutoEncryptingTransmission(const String &message, const uint8_t *targetBSSID, EncryptedConnectionStatus connectionStatus); - void finalizeAutoEncryptingConnection(const uint8_t *targetBSSID, const EncryptedConnectionLog *existingEncryptedConnection, bool requestPermanentConnection); + EncryptedConnectionStatus initiateAutoEncryptingConnection(const EspnowNetworkInfo &recipientInfo, const bool requestPermanentConnection, uint8_t *targetBSSID, EncryptedConnectionLog **existingEncryptedConnection); + TransmissionStatusType initiateAutoEncryptingTransmission(const String &message, uint8_t *targetBSSID, const EncryptedConnectionStatus connectionStatus); + void finalizeAutoEncryptingConnection(const uint8_t *targetBSSID, const EncryptedConnectionLog *existingEncryptedConnection, const bool requestPermanentConnection); // Used for verboseMode printing in attemptTransmission, _AT suffix used to reduce namespace clutter uint32_t totalDurationWhenSuccessful_AT = 0; diff --git a/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.cpp b/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.cpp index d68f24156..6e52925e3 100644 --- a/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.cpp +++ b/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.cpp @@ -25,14 +25,14 @@ #include "EspnowNetworkInfo.h" #include -EspnowNetworkInfo::EspnowNetworkInfo(int networkIndex) : NetworkInfoBase(networkIndex) { }; +EspnowNetworkInfo::EspnowNetworkInfo(const int networkIndex) : NetworkInfoBase(networkIndex) { }; EspnowNetworkInfo::EspnowNetworkInfo(const NetworkInfoBase &originalNetworkInfo) : NetworkInfoBase(originalNetworkInfo) { assert(BSSID() != defaultBSSID); // We need at least BSSID to be able to connect. }; -EspnowNetworkInfo::EspnowNetworkInfo(const uint8_t BSSID[6], const String &SSID, int32_t wifiChannel, uint8_t encryptionType, int32_t RSSI , bool isHidden) +EspnowNetworkInfo::EspnowNetworkInfo(const uint8_t BSSID[6], const String &SSID, const int32_t wifiChannel, const uint8_t encryptionType, const int32_t RSSI , const bool isHidden) : NetworkInfoBase(SSID, wifiChannel, BSSID, encryptionType, RSSI, isHidden) { } diff --git a/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.h b/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.h index fecb7c5b3..06b39b987 100644 --- a/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.h +++ b/libraries/ESP8266WiFiMesh/src/EspnowNetworkInfo.h @@ -34,12 +34,12 @@ public: /** * Automatically fill in the rest of the network info using networkIndex and the WiFi scan results. */ - EspnowNetworkInfo(int networkIndex); + EspnowNetworkInfo(const int networkIndex); EspnowNetworkInfo(const NetworkInfoBase &originalNetworkInfo); - EspnowNetworkInfo(const uint8_t BSSID[6], const String &SSID = defaultSSID, int32_t wifiChannel = defaultWifiChannel, uint8_t encryptionType = defaultEncryptionType, - int32_t RSSI = defaultRSSI, bool isHidden = defaultIsHidden); + EspnowNetworkInfo(const uint8_t BSSID[6], const String &SSID = defaultSSID, const int32_t wifiChannel = defaultWifiChannel, const uint8_t encryptionType = defaultEncryptionType, + const int32_t RSSI = defaultRSSI, const bool isHidden = defaultIsHidden); }; #endif diff --git a/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.cpp b/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.cpp index cbbacd538..d50a6f33e 100644 --- a/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.cpp +++ b/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.cpp @@ -36,7 +36,7 @@ namespace EspnowProtocolInterpreter return espnowProtocolBytesSize + (EspnowMeshBackend::useEncryptedMessages() ? aeadMetadataSize : 0); } - String espnowGetMessageContent(uint8_t *transmissionDataArray, uint8_t transmissionLength) + String espnowGetMessageContent(uint8_t *transmissionDataArray, const uint8_t transmissionLength) { String messageContent = emptyString; @@ -81,12 +81,12 @@ namespace EspnowProtocolInterpreter return TypeCast::uint8ArrayToUint64(transmissionDataArray + espnowMessageIDIndex); } - uint8_t *espnowSetMessageID(uint8_t *transmissionDataArray, uint64_t messageID) + uint8_t *espnowSetMessageID(uint8_t *transmissionDataArray, const uint64_t messageID) { return TypeCast::uint64ToUint8Array(messageID, transmissionDataArray + espnowMessageIDIndex); } - bool usesEncryption(uint64_t messageID) + bool usesEncryption(const uint64_t messageID) { // At least one of the leftmost half of bits in messageID is 1 if the transmission is encrypted. return messageID & uint64LeftmostBits; diff --git a/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.h b/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.h index 8a227669c..20617193c 100644 --- a/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.h +++ b/libraries/ESP8266WiFiMesh/src/EspnowProtocolInterpreter.h @@ -63,7 +63,7 @@ namespace EspnowProtocolInterpreter constexpr uint64_t uint64LeftmostBits = 0xFFFFFFFF00000000; - String espnowGetMessageContent(uint8_t *transmissionDataArray, uint8_t transmissionLength); + String espnowGetMessageContent(uint8_t *transmissionDataArray, const uint8_t transmissionLength); char espnowGetMessageType(const uint8_t *transmissionDataArray); uint8_t espnowGetTransmissionsRemaining(const uint8_t *transmissionDataArray); bool espnowIsMessageStart(const uint8_t *transmissionDataArray); @@ -71,9 +71,9 @@ namespace EspnowProtocolInterpreter uint8_t *espnowGetTransmissionMac(const uint8_t *transmissionDataArray, uint8_t *resultArray); uint64_t espnowGetMessageID(const uint8_t *transmissionDataArray); // @return a pointer to transmissionDataArray - uint8_t *espnowSetMessageID(uint8_t *transmissionDataArray, uint64_t messageID); + uint8_t *espnowSetMessageID(uint8_t *transmissionDataArray, const uint64_t messageID); - bool usesEncryption(uint64_t messageID); + bool usesEncryption(const uint64_t messageID); } #endif diff --git a/libraries/ESP8266WiFiMesh/src/FloodingMesh.cpp b/libraries/ESP8266WiFiMesh/src/FloodingMesh.cpp index 1f88dadf5..bea1e2f28 100644 --- a/libraries/ESP8266WiFiMesh/src/FloodingMesh.cpp +++ b/libraries/ESP8266WiFiMesh/src/FloodingMesh.cpp @@ -38,7 +38,7 @@ std::set FloodingMesh::availableFloodingMeshes = {}; char FloodingMesh::_metadataDelimiter = 23; -void floodingMeshDelay(uint32_t durationMs) +void floodingMeshDelay(const uint32_t durationMs) { ExpiringTimeTracker timeout(durationMs); @@ -54,7 +54,7 @@ void floodingMeshDelay(uint32_t durationMs) FloodingMesh::FloodingMesh(messageHandlerType messageHandler, const String &meshPassword, const uint8_t espnowEncryptedConnectionKey[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength], const uint8_t espnowHashKey[EspnowProtocolInterpreter::espnowHashKeyLength], const String &ssidPrefix, - const String &ssidSuffix, bool verboseMode, uint8 meshWiFiChannel) + const String &ssidSuffix, const bool verboseMode, const uint8 meshWiFiChannel) : _espnowBackend( [this](const String &request, MeshBackendBase &meshInstance){ return _defaultRequestHandler(request, meshInstance); }, [this](const String &response, MeshBackendBase &meshInstance){ return _defaultResponseHandler(response, meshInstance); }, @@ -68,7 +68,7 @@ FloodingMesh::FloodingMesh(messageHandlerType messageHandler, const String &mesh } FloodingMesh::FloodingMesh(messageHandlerType messageHandler, const String &meshPassword, const String &espnowEncryptedConnectionKeySeed, const String &espnowHashKeySeed, - const String &ssidPrefix, const String &ssidSuffix, bool verboseMode, uint8 meshWiFiChannel) + const String &ssidPrefix, const String &ssidSuffix, const bool verboseMode, const uint8 meshWiFiChannel) : FloodingMesh(messageHandler, meshPassword, (const uint8_t[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength]){0}, (const uint8_t[EspnowProtocolInterpreter::espnowHashKeyLength]){0}, ssidPrefix, ssidSuffix, verboseMode, meshWiFiChannel) { @@ -79,7 +79,7 @@ FloodingMesh::FloodingMesh(messageHandlerType messageHandler, const String &mesh FloodingMesh::FloodingMesh(const String &serializedMeshState, messageHandlerType messageHandler, const String &meshPassword, const uint8_t espnowEncryptedConnectionKey[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength], const uint8_t espnowHashKey[EspnowProtocolInterpreter::espnowHashKeyLength], const String &ssidPrefix, - const String &ssidSuffix, bool verboseMode, uint8 meshWiFiChannel) + const String &ssidSuffix, const bool verboseMode, const uint8 meshWiFiChannel) : FloodingMesh(messageHandler, meshPassword, espnowEncryptedConnectionKey, espnowHashKey, ssidPrefix, ssidSuffix, verboseMode, meshWiFiChannel) { loadMeshState(serializedMeshState); @@ -87,7 +87,7 @@ FloodingMesh::FloodingMesh(const String &serializedMeshState, messageHandlerType FloodingMesh::FloodingMesh(const String &serializedMeshState, messageHandlerType messageHandler, const String &meshPassword, const String &espnowEncryptedConnectionKeySeed, const String &espnowHashKeySeed, const String &ssidPrefix, - const String &ssidSuffix, bool verboseMode, uint8 meshWiFiChannel) + const String &ssidSuffix, const bool verboseMode, const uint8 meshWiFiChannel) : FloodingMesh(messageHandler, meshPassword, espnowEncryptedConnectionKeySeed, espnowHashKeySeed, ssidPrefix, ssidSuffix, verboseMode, meshWiFiChannel) { loadMeshState(serializedMeshState); @@ -151,13 +151,13 @@ void FloodingMesh::performMeshInstanceMaintenance() } } -String FloodingMesh::serializeMeshState() +String FloodingMesh::serializeMeshState() const { using namespace JsonTranslator; // Returns: {"meshState":{"connectionState":{"unsyncMsgID":"123"},"meshMsgCount":"123"}} - String connectionState = getEspnowMeshBackend().serializeUnencryptedConnection(); + String connectionState = getEspnowMeshBackendConst().serializeUnencryptedConnection(); return String(F("{\"meshState\":{")) @@ -204,12 +204,12 @@ void FloodingMesh::broadcastKernel(const String &message) getEspnowMeshBackend().broadcast(message); } -void FloodingMesh::setBroadcastReceptionRedundancy(uint8_t redundancy) +void FloodingMesh::setBroadcastReceptionRedundancy(const uint8_t redundancy) { assert(redundancy < 255); _broadcastReceptionRedundancy = redundancy; } -uint8_t FloodingMesh::getBroadcastReceptionRedundancy() { return _broadcastReceptionRedundancy; } +uint8_t FloodingMesh::getBroadcastReceptionRedundancy() const { return _broadcastReceptionRedundancy; } void FloodingMesh::encryptedBroadcast(const String &message) { @@ -236,40 +236,40 @@ void FloodingMesh::clearForwardingBacklog() _forwardingBacklog.clear(); } -void FloodingMesh::setMessageHandler(messageHandlerType messageHandler) { _messageHandler = messageHandler; } -FloodingMesh::messageHandlerType FloodingMesh::getMessageHandler() { return _messageHandler; } +void FloodingMesh::setMessageHandler(const messageHandlerType messageHandler) { _messageHandler = messageHandler; } +FloodingMesh::messageHandlerType FloodingMesh::getMessageHandler() const { return _messageHandler; } -void FloodingMesh::setOriginMac(uint8_t *macArray) +void FloodingMesh::setOriginMac(const uint8_t *macArray) { std::copy_n(macArray, 6, _originMac); } -String FloodingMesh::getOriginMac() { return TypeCast::macToString(_originMac); } -uint8_t *FloodingMesh::getOriginMac(uint8_t *macArray) +String FloodingMesh::getOriginMac() const { return TypeCast::macToString(_originMac); } +uint8_t *FloodingMesh::getOriginMac(uint8_t *macArray) const { std::copy_n(_originMac, 6, macArray); return macArray; } -uint32_t FloodingMesh::maxUnencryptedMessageLength() +uint32_t FloodingMesh::maxUnencryptedMessageLength() const { - return getEspnowMeshBackend().getMaxMessageLength() - MESSAGE_ID_LENGTH - (getEspnowMeshBackend().getMeshName().length() + 1); // Need room for mesh name + delimiter + return getEspnowMeshBackendConst().getMaxMessageLength() - MESSAGE_ID_LENGTH - (getEspnowMeshBackendConst().getMeshName().length() + 1); // Need room for mesh name + delimiter } -uint32_t FloodingMesh::maxEncryptedMessageLength() +uint32_t FloodingMesh::maxEncryptedMessageLength() const { // Need 1 extra delimiter character for maximum metadata efficiency (makes it possible to store exactly 18 MACs in metadata by adding an extra transmission) - return getEspnowMeshBackend().getMaxMessageLength() - MESSAGE_ID_LENGTH - 1; + return getEspnowMeshBackendConst().getMaxMessageLength() - MESSAGE_ID_LENGTH - 1; } -void FloodingMesh::setMessageLogSize(uint16_t messageLogSize) +void FloodingMesh::setMessageLogSize(const uint16_t messageLogSize) { assert(messageLogSize >= 1); _messageLogSize = messageLogSize; } -uint16_t FloodingMesh::messageLogSize() { return _messageLogSize; } +uint16_t FloodingMesh::messageLogSize() const { return _messageLogSize; } -void FloodingMesh::setMetadataDelimiter(char metadataDelimiter) +void FloodingMesh::setMetadataDelimiter(const char metadataDelimiter) { // Using HEX number characters as a delimiter is a bad idea regardless of broadcast type, since they are always in the broadcast metadata. // We therefore check for those characters below. @@ -286,7 +286,12 @@ EspnowMeshBackend &FloodingMesh::getEspnowMeshBackend() return _espnowBackend; } -bool FloodingMesh::insertPreliminaryMessageID(uint64_t messageID) +const EspnowMeshBackend &FloodingMesh::getEspnowMeshBackendConst() const +{ + return _espnowBackend; +} + +bool FloodingMesh::insertPreliminaryMessageID(const uint64_t messageID) { uint8_t apMacArray[6] = { 0 }; if(messageID >> 16 == TypeCast::macToUint64(WiFi.softAPmacAddress(apMacArray))) @@ -304,7 +309,7 @@ bool FloodingMesh::insertPreliminaryMessageID(uint64_t messageID) return true; } -bool FloodingMesh::insertCompletedMessageID(uint64_t messageID) +bool FloodingMesh::insertCompletedMessageID(const uint64_t messageID) { uint8_t apMacArray[6] = { 0 }; if(messageID >> 16 == TypeCast::macToUint64(WiFi.softAPmacAddress(apMacArray))) @@ -322,7 +327,7 @@ bool FloodingMesh::insertCompletedMessageID(uint64_t messageID) return true; } -void FloodingMesh::updateMessageQueue(messageQueueElementType messageIterator) +void FloodingMesh::updateMessageQueue(const messageQueueElementType messageIterator) { _messageIdOrder.emplace(messageIterator); @@ -449,7 +454,7 @@ TransmissionStatusType FloodingMesh::_defaultResponseHandler(const String &respo * @param numberOfNetworks The number of networks found in the WiFi scan. * @param meshInstance The MeshBackendBase instance that called the function. */ -void FloodingMesh::_defaultNetworkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) +void FloodingMesh::_defaultNetworkFilter(const int numberOfNetworks, MeshBackendBase &meshInstance) { // Note that the network index of a given node may change whenever a new scan is done. for (int networkIndex = 0; networkIndex < numberOfNetworks; ++networkIndex) @@ -554,7 +559,7 @@ bool FloodingMesh::_defaultTransmissionOutcomesUpdateHook(MeshBackendBase &meshI * @return True if the response transmission process should continue with the next response in the waiting list. * False if the response transmission process should stop after removing the just sent response from the waiting list. */ -bool FloodingMesh::_defaultResponseTransmittedHook(const String &response, const uint8_t *recipientMac, uint32_t responseIndex, EspnowMeshBackend &meshInstance) +bool FloodingMesh::_defaultResponseTransmittedHook(const String &response, const uint8_t *recipientMac, const uint32_t responseIndex, EspnowMeshBackend &meshInstance) { (void)response; // This is useful to remove a "unused parameter" compiler warning. Does nothing else. (void)recipientMac; diff --git a/libraries/ESP8266WiFiMesh/src/FloodingMesh.h b/libraries/ESP8266WiFiMesh/src/FloodingMesh.h index 71c662178..fc69f3f9a 100644 --- a/libraries/ESP8266WiFiMesh/src/FloodingMesh.h +++ b/libraries/ESP8266WiFiMesh/src/FloodingMesh.h @@ -38,7 +38,7 @@ * * @param durationMs The shortest allowed delay duration, in milliseconds. */ -void floodingMeshDelay(uint32_t durationMs); +void floodingMeshDelay(const uint32_t durationMs); class FloodingMesh { @@ -69,7 +69,7 @@ public: */ FloodingMesh(messageHandlerType messageHandler, const String &meshPassword, const uint8_t espnowEncryptedConnectionKey[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength], const uint8_t espnowHashKey[EspnowProtocolInterpreter::espnowHashKeyLength], const String &ssidPrefix, - const String &ssidSuffix, bool verboseMode = false, uint8 meshWiFiChannel = 1); + const String &ssidSuffix, const bool verboseMode = false, const uint8 meshWiFiChannel = 1); /** * FloodingMesh constructor method. Creates a FloodingMesh node, ready to be initialised. @@ -90,7 +90,7 @@ public: * */ FloodingMesh(messageHandlerType messageHandler, const String &meshPassword, const String &espnowEncryptedConnectionKeySeed, const String &espnowHashKeySeed, - const String &ssidPrefix, const String &ssidSuffix, bool verboseMode = false, uint8 meshWiFiChannel = 1); + const String &ssidPrefix, const String &ssidSuffix, const bool verboseMode = false, const uint8 meshWiFiChannel = 1); /** * This constructor should be used in combination with serializeMeshState() when the node has gone to sleep while other nodes stayed awake. @@ -101,7 +101,7 @@ public: FloodingMesh(const String &serializedMeshState, messageHandlerType messageHandler, const String &meshPassword, const uint8_t espnowEncryptedConnectionKey[EspnowProtocolInterpreter::espnowEncryptedConnectionKeyLength], const uint8_t espnowHashKey[EspnowProtocolInterpreter::espnowHashKeyLength], const String &ssidPrefix, - const String &ssidSuffix, bool verboseMode = false, uint8 meshWiFiChannel = 1); + const String &ssidSuffix, const bool verboseMode = false, const uint8 meshWiFiChannel = 1); /** * This constructor should be used in combination with serializeMeshState() when the node has gone to sleep while other nodes stayed awake. @@ -110,7 +110,7 @@ public: * @param serializedMeshState A String with a serialized mesh node state that the node should use. */ FloodingMesh(const String &serializedMeshState, messageHandlerType messageHandler, const String &meshPassword, const String &espnowEncryptedConnectionKeySeed, - const String &espnowHashKeySeed, const String &ssidPrefix, const String &ssidSuffix, bool verboseMode = false, uint8 meshWiFiChannel = 1); + const String &espnowHashKeySeed, const String &ssidPrefix, const String &ssidSuffix, const bool verboseMode = false, const uint8 meshWiFiChannel = 1); virtual ~FloodingMesh(); @@ -155,7 +155,7 @@ public: * * @return A string with the serialized current mesh node state. */ - String serializeMeshState(); + String serializeMeshState() const; /** * Make an unencrypted broadcast to the entire mesh network. @@ -173,8 +173,8 @@ public: * * @param redundancy The maximum number of extra copies that will be accepted. Defaults to 2. Valid values are 0 to 254. */ - void setBroadcastReceptionRedundancy(uint8_t redundancy); - uint8_t getBroadcastReceptionRedundancy(); + void setBroadcastReceptionRedundancy(const uint8_t redundancy); + uint8_t getBroadcastReceptionRedundancy() const; /** * Make an encrypted broadcast to the entire mesh network. @@ -205,8 +205,8 @@ public: * * @param messageHandler The message handler callback function to use. */ - void setMessageHandler(messageHandlerType messageHandler); - messageHandlerType getMessageHandler(); + void setMessageHandler(const messageHandlerType messageHandler); + messageHandlerType getMessageHandler() const; /** * Get the origin AP MAC address of the most recently received mesh message. @@ -214,7 +214,7 @@ public: * * @return A String filled with a hexadecimal representation of the MAC, without delimiters. */ - String getOriginMac(); + String getOriginMac() const; /** * Get the origin AP MAC address of the most recently received mesh message. @@ -223,7 +223,7 @@ public: * @param macArray The array that should store the MAC address. Must be at least 6 bytes. * @return macArray filled with the origin MAC. */ - uint8_t *getOriginMac(uint8_t *macArray); + uint8_t *getOriginMac(uint8_t *macArray) const; /** * The number of received messageID:s that will be stored by the node. Used to remember which messages have been received. @@ -237,8 +237,8 @@ public: * If a value close to the maximum is chosen, there is a high risk the node will ignore transmissions on messageID rollover if they are sent only by one node * (especially if some transmissions are missed), since the messageID also uses uint16_t. */ - void setMessageLogSize(uint16_t messageLogSize); - uint16_t messageLogSize(); + void setMessageLogSize(const uint16_t messageLogSize); + uint16_t messageLogSize() const; /** * Hint: Use String.length() to get the ASCII length of a String. @@ -247,7 +247,7 @@ public: * Note that non-ASCII characters usually require at least two bytes each. * Also note that for unencrypted messages the maximum size will depend on getEspnowMeshBackend().getMeshName().length() */ - uint32_t maxUnencryptedMessageLength(); + uint32_t maxUnencryptedMessageLength() const; /** * Hint: Use String.length() to get the ASCII length of a String. @@ -255,7 +255,7 @@ public: * @return The maximum length in bytes an encrypted ASCII message is allowed to be when broadcasted by this node. * Note that non-ASCII characters usually require at least two bytes each. */ - uint32_t maxEncryptedMessageLength(); + uint32_t maxEncryptedMessageLength() const; /** * Set the delimiter character used for metadata by every FloodingMesh instance. @@ -264,7 +264,7 @@ public: * @param metadataDelimiter The metadata delimiter character to use. * Defaults to 23 = End-of-Transmission-Block (ETB) control character in ASCII */ - static void setMetadataDelimiter(char metadataDelimiter); + static void setMetadataDelimiter(const char metadataDelimiter); static char metadataDelimiter(); /* @@ -274,6 +274,7 @@ public: * and so are discouraged for those who prefer it when things just work. */ EspnowMeshBackend &getEspnowMeshBackend(); + const EspnowMeshBackend &getEspnowMeshBackendConst() const; void restoreDefaultRequestHandler(); void restoreDefaultResponseHandler(); @@ -292,9 +293,9 @@ protected: void encryptedBroadcastKernel(const String &message); - bool insertPreliminaryMessageID(uint64_t messageID); - bool insertCompletedMessageID(uint64_t messageID); - void updateMessageQueue(messageQueueElementType messageIterator); + bool insertPreliminaryMessageID(const uint64_t messageID); + bool insertCompletedMessageID(const uint64_t messageID); + void updateMessageQueue(const messageQueueElementType messageIterator); void loadMeshState(const String &serializedMeshState); @@ -303,7 +304,7 @@ protected: * * @param macArray An uint8_t array which contains the MAC address to store. The method will store the first 6 bytes of the array. */ - void setOriginMac(uint8_t *macArray); + void setOriginMac(const uint8_t *macArray); private: @@ -328,10 +329,10 @@ private: String _defaultRequestHandler(const String &request, MeshBackendBase &meshInstance); TransmissionStatusType _defaultResponseHandler(const String &response, MeshBackendBase &meshInstance); - void _defaultNetworkFilter(int numberOfNetworks, MeshBackendBase &meshInstance); + void _defaultNetworkFilter(const int numberOfNetworks, MeshBackendBase &meshInstance); bool _defaultBroadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance); bool _defaultTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance); - bool _defaultResponseTransmittedHook(const String &response, const uint8_t *recipientMac, uint32_t responseIndex, EspnowMeshBackend &meshInstance); + bool _defaultResponseTransmittedHook(const String &response, const uint8_t *recipientMac, const uint32_t responseIndex, EspnowMeshBackend &meshInstance); }; #endif diff --git a/libraries/ESP8266WiFiMesh/src/JsonTranslator.cpp b/libraries/ESP8266WiFiMesh/src/JsonTranslator.cpp index 89531ec5f..ea314145a 100644 --- a/libraries/ESP8266WiFiMesh/src/JsonTranslator.cpp +++ b/libraries/ESP8266WiFiMesh/src/JsonTranslator.cpp @@ -41,7 +41,7 @@ namespace JsonTranslator return valueIdentifier + '\"' + value + F("\"}}"); } - String createEncryptedConnectionInfo(const String &infoHeader, const String &requestNonce, const String &authenticationPassword, uint64_t ownSessionKey, uint64_t peerSessionKey) + String createEncryptedConnectionInfo(const String &infoHeader, const String &requestNonce, const String &authenticationPassword, const uint64_t ownSessionKey, const uint64_t peerSessionKey) { // Returns: Encrypted connection info:{"arguments":{"nonce":"1F2","password":"abc","ownSK":"3B4","peerSK":"1A2"}} @@ -53,7 +53,7 @@ namespace JsonTranslator + createJsonEndPair(FPSTR(jsonPeerSessionKey), TypeCast::uint64ToString(ownSessionKey)); } - String createEncryptionRequestIntro(const String &requestHeader, uint32_t duration) + String createEncryptionRequestIntro(const String &requestHeader, const uint32_t duration) { return requestHeader + String(F("{\"arguments\":{")) @@ -65,7 +65,7 @@ namespace JsonTranslator return createJsonEndPair(FPSTR(jsonNonce), requestNonce); } - String createEncryptionRequestHmacMessage(const String &requestHeader, const String &requestNonce, const uint8_t *hashKey, uint8_t hashKeyLength, uint32_t duration) + String createEncryptionRequestHmacMessage(const String &requestHeader, const String &requestNonce, const uint8_t *hashKey, const uint8_t hashKeyLength, const uint32_t duration) { String mainMessage = createEncryptionRequestIntro(requestHeader, duration) + createJsonPair(FPSTR(jsonNonce), requestNonce); uint8_t staMac[6] {0}; @@ -76,7 +76,7 @@ namespace JsonTranslator } bool verifyEncryptionRequestHmac(const String &encryptionRequestHmacMessage, const uint8_t *requesterStaMac, const uint8_t *requesterApMac, - const uint8_t *hashKey, uint8_t hashKeyLength) + const uint8_t *hashKey, const uint8_t hashKeyLength) { using MeshCryptoInterface::verifyMeshHmac; @@ -97,7 +97,7 @@ namespace JsonTranslator return false; } - int32_t getStartIndex(const String &jsonString, const String &valueIdentifier, int32_t searchStartIndex) + int32_t getStartIndex(const String &jsonString, const String &valueIdentifier, const int32_t searchStartIndex) { int32_t startIndex = jsonString.indexOf(valueIdentifier, searchStartIndex); if(startIndex < 0) @@ -107,7 +107,7 @@ namespace JsonTranslator return startIndex; } - int32_t getEndIndex(const String &jsonString, int32_t searchStartIndex) + int32_t getEndIndex(const String &jsonString, const int32_t searchStartIndex) { int32_t endIndex = jsonString.indexOf(',', searchStartIndex); if(endIndex < 0) diff --git a/libraries/ESP8266WiFiMesh/src/JsonTranslator.h b/libraries/ESP8266WiFiMesh/src/JsonTranslator.h index 3070e9a99..7576dcb53 100644 --- a/libraries/ESP8266WiFiMesh/src/JsonTranslator.h +++ b/libraries/ESP8266WiFiMesh/src/JsonTranslator.h @@ -45,12 +45,12 @@ namespace JsonTranslator String createJsonPair(const String &valueIdentifier, const String &value); String createJsonEndPair(const String &valueIdentifier, const String &value); - String createEncryptedConnectionInfo(const String &infoHeader, const String &requestNonce, const String &authenticationPassword, uint64_t ownSessionKey, uint64_t peerSessionKey); - String createEncryptionRequestIntro(const String &requestHeader, uint32_t duration = 0); + String createEncryptedConnectionInfo(const String &infoHeader, const String &requestNonce, const String &authenticationPassword, const uint64_t ownSessionKey, const uint64_t peerSessionKey); + String createEncryptionRequestIntro(const String &requestHeader, const uint32_t duration = 0); String createEncryptionRequestEnding(const String &requestNonce); - String createEncryptionRequestHmacMessage(const String &requestHeader, const String &requestNonce, const uint8_t *hashKey, uint8_t hashKeyLength, uint32_t duration = 0); + String createEncryptionRequestHmacMessage(const String &requestHeader, const String &requestNonce, const uint8_t *hashKey, const uint8_t hashKeyLength, const uint32_t duration = 0); - bool verifyEncryptionRequestHmac(const String &encryptionRequestHmacMessage, const uint8_t *requesterStaMac, const uint8_t *requesterApMac, const uint8_t *hashKey, uint8_t hashKeyLength); + bool verifyEncryptionRequestHmac(const String &encryptionRequestHmacMessage, const uint8_t *requesterStaMac, const uint8_t *requesterApMac, const uint8_t *hashKey, const uint8_t hashKeyLength); /** * Provides the index within jsonString where the value of valueIdentifier starts. @@ -61,7 +61,7 @@ namespace JsonTranslator * * @return An int32_t containing the index within jsonString where the value of valueIdentifier starts, or a negative value if valueIdentifier was not found. */ - int32_t getStartIndex(const String &jsonString, const String &valueIdentifier, int32_t searchStartIndex = 0); + int32_t getStartIndex(const String &jsonString, const String &valueIdentifier, const int32_t searchStartIndex = 0); /** * Provides the index within jsonString where the next JSON termination character (',' or '}') is found, starting from searchStartIndex. @@ -71,7 +71,7 @@ namespace JsonTranslator * * @return An int32_t containing the index within jsonString where the next JSON termination character is found, or a negative value if no such character was found. */ - int32_t getEndIndex(const String &jsonString, int32_t searchStartIndex); + int32_t getEndIndex(const String &jsonString, const int32_t searchStartIndex); bool getConnectionState(const String &jsonString, String &result); /** diff --git a/libraries/ESP8266WiFiMesh/src/MeshBackendBase.cpp b/libraries/ESP8266WiFiMesh/src/MeshBackendBase.cpp index 33ed8b565..25ae81d4b 100644 --- a/libraries/ESP8266WiFiMesh/src/MeshBackendBase.cpp +++ b/libraries/ESP8266WiFiMesh/src/MeshBackendBase.cpp @@ -30,7 +30,7 @@ std::shared_ptr MeshBackendBase::_scanMutex = std::make_shared(false bool MeshBackendBase::_printWarnings = true; -MeshBackendBase::MeshBackendBase(requestHandlerType requestHandler, responseHandlerType responseHandler, networkFilterType networkFilter, MeshBackendType classType) +MeshBackendBase::MeshBackendBase(const requestHandlerType requestHandler, const responseHandlerType responseHandler, const networkFilterType networkFilter, const MeshBackendType classType) { setRequestHandler(requestHandler); setResponseHandler(responseHandler); @@ -43,12 +43,12 @@ MeshBackendBase::~MeshBackendBase() deactivateControlledAP(); } -void MeshBackendBase::setClassType(MeshBackendType classType) +void MeshBackendBase::setClassType(const MeshBackendType classType) { _classType = classType; } -MeshBackendType MeshBackendBase::getClassType() {return _classType;} +MeshBackendType MeshBackendBase::getClassType() const {return _classType;} void MeshBackendBase::activateAP() { @@ -108,12 +108,12 @@ MeshBackendBase *MeshBackendBase::getAPController() return apController; } -bool MeshBackendBase::isAPController() +bool MeshBackendBase::isAPController() const { return (this == getAPController()); } -void MeshBackendBase::setWiFiChannel(uint8 newWiFiChannel) +void MeshBackendBase::setWiFiChannel(const uint8 newWiFiChannel) { wifi_country_t wifiCountry; wifi_get_country(&wifiCountry); // Note: Should return 0 on success and -1 on failure, but always seems to return 1. Possibly broken API. Channels 1 to 13 are the default limits. @@ -188,14 +188,14 @@ void MeshBackendBase::setMeshName(const String &newMeshName) setSSIDPrefix(newMeshName); } -String MeshBackendBase::getMeshName() {return getSSIDPrefix();} +String MeshBackendBase::getMeshName() const {return getSSIDPrefix();} void MeshBackendBase::setNodeID(const String &newNodeID) { setSSIDSuffix(newNodeID); } -String MeshBackendBase::getNodeID() {return getSSIDSuffix();} +String MeshBackendBase::getNodeID() const {return getSSIDSuffix();} void MeshBackendBase::setMeshPassword(const String &newMeshPassword) { @@ -213,26 +213,26 @@ String MeshBackendBase::getMeshPassword() const {return _meshPassword;} void MeshBackendBase::setMessage(const String &newMessage) {_message = newMessage;} String MeshBackendBase::getMessage() const {return _message;} -void MeshBackendBase::setRequestHandler(MeshBackendBase::requestHandlerType requestHandler) {_requestHandler = requestHandler;} -MeshBackendBase::requestHandlerType MeshBackendBase::getRequestHandler() {return _requestHandler;} +void MeshBackendBase::setRequestHandler(const MeshBackendBase::requestHandlerType requestHandler) {_requestHandler = requestHandler;} +MeshBackendBase::requestHandlerType MeshBackendBase::getRequestHandler() const {return _requestHandler;} -void MeshBackendBase::setResponseHandler(MeshBackendBase::responseHandlerType responseHandler) {_responseHandler = responseHandler;} -MeshBackendBase::responseHandlerType MeshBackendBase::getResponseHandler() {return _responseHandler;} +void MeshBackendBase::setResponseHandler(const MeshBackendBase::responseHandlerType responseHandler) {_responseHandler = responseHandler;} +MeshBackendBase::responseHandlerType MeshBackendBase::getResponseHandler() const {return _responseHandler;} -void MeshBackendBase::setNetworkFilter(MeshBackendBase::networkFilterType networkFilter) {_networkFilter = networkFilter;} -MeshBackendBase::networkFilterType MeshBackendBase::getNetworkFilter() {return _networkFilter;} +void MeshBackendBase::setNetworkFilter(const MeshBackendBase::networkFilterType networkFilter) {_networkFilter = networkFilter;} +MeshBackendBase::networkFilterType MeshBackendBase::getNetworkFilter() const {return _networkFilter;} -void MeshBackendBase::setTransmissionOutcomesUpdateHook(MeshBackendBase::transmissionOutcomesUpdateHookType transmissionOutcomesUpdateHook) {_transmissionOutcomesUpdateHook = transmissionOutcomesUpdateHook;} -MeshBackendBase::transmissionOutcomesUpdateHookType MeshBackendBase::getTransmissionOutcomesUpdateHook() {return _transmissionOutcomesUpdateHook;} +void MeshBackendBase::setTransmissionOutcomesUpdateHook(const MeshBackendBase::transmissionOutcomesUpdateHookType transmissionOutcomesUpdateHook) {_transmissionOutcomesUpdateHook = transmissionOutcomesUpdateHook;} +MeshBackendBase::transmissionOutcomesUpdateHookType MeshBackendBase::getTransmissionOutcomesUpdateHook() const {return _transmissionOutcomesUpdateHook;} -void MeshBackendBase::setScanHidden(bool scanHidden) +void MeshBackendBase::setScanHidden(const bool scanHidden) { _scanHidden = scanHidden; } bool MeshBackendBase::getScanHidden() const {return _scanHidden;} -void MeshBackendBase::setAPHidden(bool apHidden) +void MeshBackendBase::setAPHidden(const bool apHidden) { if(getAPHidden() != apHidden) { @@ -258,7 +258,7 @@ bool MeshBackendBase::latestTransmissionSuccessfulBase(const std::vector