add locks in presence detection for _device dictionary

This commit is contained in:
technyon
2024-06-15 08:33:08 +02:00
parent 705e0971d7
commit 3177752c3b
2 changed files with 41 additions and 21 deletions

View File

@@ -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<std::mutex> 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<std::mutex> 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> pdDevice = std::make_shared<PdDevice>();
@@ -166,7 +186,10 @@ void PresenceDetection::onResult(NimBLEAdvertisedDevice *device)
pdDevice->timestamp = millis();
_devices[addr] = pdDevice;
{
std::lock_guard<std::mutex> 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<std::mutex> 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())
// {

View File

@@ -4,6 +4,7 @@
#include "BleScanner.h"
#include "BleInterfaces.h"
#include <memory>
#include <mutex>
struct PdDevice
{
@@ -29,6 +30,8 @@ public:
private:
void buildCsv(const std::shared_ptr<PdDevice>& device);
std::mutex mtx;
Preferences* _preferences;
BleScanner::Scanner* _bleScanner;
char* _csv = {0};