From 3177752c3b076564d9c51ac968224c6a52504ec3 Mon Sep 17 00:00:00 2001 From: technyon Date: Sat, 15 Jun 2024 08:33:08 +0200 Subject: [PATCH] add locks in presence detection for _device dictionary --- src/PresenceDetection.cpp | 59 +++++++++++++++++++++++++-------------- src/PresenceDetection.h | 3 ++ 2 files changed, 41 insertions(+), 21 deletions(-) diff --git a/src/PresenceDetection.cpp b/src/PresenceDetection.cpp index de861b5..cab5d59 100644 --- a/src/PresenceDetection.cpp +++ b/src/PresenceDetection.cpp @@ -45,17 +45,21 @@ char* PresenceDetection::generateCsv() _csvIndex = 0; long ts = millis(); - for(auto it : _devices) { - if(ts - _timeout < it.second->timestamp) - { - buildCsv(it.second); - } + std::lock_guard lock(mtx); - // Prevent csv buffer overflow - if(_csvIndex > _bufferSize - (sizeof(it.second->name) + sizeof(it.second->address) + 10)) + for (auto it: _devices) { - break; + if (ts - _timeout < it.second->timestamp) + { + buildCsv(it.second); + } + + // Prevent csv buffer overflow + if (_csvIndex > _bufferSize - (sizeof(it.second->name) + sizeof(it.second->address) + 10)) + { + break; + } } } @@ -131,8 +135,24 @@ void PresenceDetection::onResult(NimBLEAdvertisedDevice *device) long long addr = strtoll(addrArrComp, nullptr, 16); - auto it = _devices.find(addr); - if(it == _devices.end()) + bool found; + { + std::lock_guard lock(mtx); + auto it = _devices.find(addr); + found = (it != _devices.end()); + + if(found) + { + it->second->timestamp = millis(); + if(device->haveRSSI()) + { + it->second->hasRssi = true; + it->second->rssi = device->getRSSI(); + } + } + } + + if(!found) { std::shared_ptr pdDevice = std::make_shared(); @@ -166,7 +186,10 @@ void PresenceDetection::onResult(NimBLEAdvertisedDevice *device) pdDevice->timestamp = millis(); - _devices[addr] = pdDevice; + { + std::lock_guard lock(mtx); + _devices[addr] = pdDevice; + } } else if (device->haveManufacturerData()) { @@ -184,20 +207,14 @@ void PresenceDetection::onResult(NimBLEAdvertisedDevice *device) { pdDevice->timestamp = millis(); strcpy(pdDevice->name, oBeacon.getProximityUUID().toString().c_str()); - _devices[addr] = pdDevice; + { + std::lock_guard lock(mtx); + _devices[addr] = pdDevice; + } } } } } - else - { - it->second->timestamp = millis(); - if(device->haveRSSI()) - { - it->second->hasRssi = true; - it->second->rssi = device->getRSSI(); - } - } // if(device->haveName()) // { diff --git a/src/PresenceDetection.h b/src/PresenceDetection.h index ce5adbe..5e5889b 100644 --- a/src/PresenceDetection.h +++ b/src/PresenceDetection.h @@ -4,6 +4,7 @@ #include "BleScanner.h" #include "BleInterfaces.h" #include +#include struct PdDevice { @@ -29,6 +30,8 @@ public: private: void buildCsv(const std::shared_ptr& device); + std::mutex mtx; + Preferences* _preferences; BleScanner::Scanner* _bleScanner; char* _csv = {0};