Skip to content

Commit

Permalink
- Add locking around all places where Peripherals list is modified or…
Browse files Browse the repository at this point in the history
… enumerated

- Fix issue where observers of the Peripherals INotifyReadOnlyCollection would handle the CollectionChanged event before added Peripherals' properties were fully initialized
  • Loading branch information
Matt Sullivan committed Feb 5, 2025
1 parent 006ed5c commit 6f056b2
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions src/Shiny.BluetoothLE/Managed/ManagedScan.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,15 @@ public ManagedScan(IBleManager bleManager)
=> this.bleManager = bleManager;


public IEnumerable<IPeripheral> GetConnectedPeripherals() => this.list
.ToList()
.Where(x => x.Peripheral.Status == ConnectionState.Connected)
.Select(x => x.Peripheral);
public IEnumerable<IPeripheral> GetConnectedPeripherals()
{
lock (this.syncLock)
{
return this.list.ToList()
.Where(x => x.Peripheral.Status == ConnectionState.Connected)
.Select(x => x.Peripheral);
}
}


public IObservable<(ManagedScanListAction Action, ManagedScanResult? ScanResult)> WhenScan() => this.actionSubj;
Expand Down Expand Up @@ -80,7 +85,9 @@ public async Task Start(
if (show)
{
var action = ManagedScanListAction.Update;
var result = this.Peripherals.FirstOrDefault(x => x.Peripheral.Equals(scanResult.Peripheral));
ManagedScanResult? result;
lock (this.syncLock)
result = this.Peripherals.FirstOrDefault(x => x.Peripheral.Equals(scanResult.Peripheral));
if (result == null)
{
action = ManagedScanListAction.Add;
Expand All @@ -89,8 +96,6 @@ public async Task Start(
ServiceUuids = scanResult.AdvertisementData?.ServiceUuids,
ServiceData = scanResult.AdvertisementData?.ServiceData
};
lock (this.syncLock)
this.list.Add(result);
}
result.IsConnectable = scanResult.AdvertisementData?.IsConnectable;
result.ManufacturerData = scanResult.AdvertisementData?.ManufacturerData;
Expand All @@ -99,6 +104,11 @@ public async Task Start(
result.Rssi = scanResult.Rssi;
result.TxPower = scanResult.AdvertisementData?.TxPower;
result.LastSeen = DateTimeOffset.UtcNow;
if (action == ManagedScanListAction.Add)
{
lock (this.syncLock)
this.list.Add(result);
}
this.actionSubj.OnNext((action, result));
}
}
Expand All @@ -119,7 +129,9 @@ public async Task Start(
_ =>
{
var maxAge = DateTimeOffset.UtcNow.Subtract(clearTime.Value);
var tmp = this.Peripherals.Where(x => x.LastSeen < maxAge).ToList();
List<ManagedScanResult> tmp;
lock (this.syncLock)
tmp = this.Peripherals.Where(x => x.LastSeen < maxAge).ToList();

foreach (var p in tmp)
{
Expand Down

0 comments on commit 6f056b2

Please sign in to comment.