From 311386e7e02861ba8f11863182ebd340f1de566a Mon Sep 17 00:00:00 2001 From: Bliss Chapman Date: Wed, 6 Sep 2023 17:11:44 -0700 Subject: [PATCH] [MacOS] Add timeout to connect (#258) * [MacOS] Add timeout to connect * Made my suggested changes. --------- Co-authored-by: Bliss Chapman Co-authored-by: Kevin Dewald <5274600+kdewald@users.noreply.github.com> --- .../src/backends/macos/PeripheralBaseMacOS.mm | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/simpleble/src/backends/macos/PeripheralBaseMacOS.mm b/simpleble/src/backends/macos/PeripheralBaseMacOS.mm index 2d137b16..a4262fd7 100644 --- a/simpleble/src/backends/macos/PeripheralBaseMacOS.mm +++ b/simpleble/src/backends/macos/PeripheralBaseMacOS.mm @@ -19,6 +19,18 @@ } \ } while (0) +#define WAIT_UNTIL_FALSE_WITH_TIMEOUT(obj, var, timeout) \ + do { \ + BOOL _tmpVar = YES; \ + NSDate* endDate = [NSDate dateWithTimeInterval:timeout sinceDate:NSDate.now]; \ + while (_tmpVar && [NSDate.now compare:endDate] == NSOrderedAscending) { \ + [NSThread sleepForTimeInterval:0.01]; \ + @synchronized(obj) { \ + _tmpVar = (var); \ + } \ + } \ + } while (0) + // -------------------------------------------------- @interface BleTask : NSObject @@ -134,7 +146,7 @@ - (void)connect { [self.centralManager connectPeripheral:self.peripheral options:@{}]; // TODO: Do we need to pass any options? } - WAIT_UNTIL_FALSE(self, _task.pending); + WAIT_UNTIL_FALSE_WITH_TIMEOUT(self, _task.pending, 5.0); if (self.peripheral.state != CBPeripheralStateConnected || _task.error != nil) { [self throwBasedOnError:_task.error withFormat:@"Peripheral Connection"];