Skip to content

Commit

Permalink
replaces semaphore with queue in AWSIoTMQTTClient
Browse files Browse the repository at this point in the history
  • Loading branch information
Brennan Stehling committed Jul 8, 2022
1 parent fdf9023 commit c357ca3
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions AWSIoT/Internal/AWSIoTMQTTClient.m
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ @interface AWSIoTMQTTClient() <AWSSRWebSocketDelegate, NSStreamDelegate, AWSMQTT
@property (atomic, assign) BOOL runLoopShouldContinue;

@property (strong,atomic) dispatch_semaphore_t timerSemaphore;
@property (strong,atomic) dispatch_queue_t timerQueue;

@end

Expand Down Expand Up @@ -107,6 +108,7 @@ - (instancetype)init {
_userDidIssueConnect = NO;
_userDidIssueDisconnect = NO;
_timerSemaphore = dispatch_semaphore_create(1);
_timerQueue = dispatch_queue_create("com.amazon.aws.iot.timer-queue", DISPATCH_QUEUE_SERIAL);
_streamsThread = nil;
}
return self;
Expand Down Expand Up @@ -721,18 +723,10 @@ - (void)initiateReconnectTimer: (id) sender
//Set the timeout to 1800 seconds, which is 1.5x of the max keep-alive 1200 seconds.
//The unit of measure for the dispatch_time function is nano seconds.

dispatch_semaphore_wait(_timerSemaphore, dispatch_time(DISPATCH_TIME_NOW, 1800 * NSEC_PER_SEC));
BOOL isConnectingOrConnected = self.mqttStatus == AWSIoTMQTTStatusConnected || self.mqttStatus == AWSIoTMQTTStatusConnecting;
if (!self.reconnectTimer && !isConnectingOrConnected) {
self.reconnectTimer = [NSTimer timerWithTimeInterval:self.currentReconnectTime
target:self
selector: @selector(reconnectToSession)
userInfo:nil
repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:self.reconnectTimer forMode:NSRunLoopCommonModes];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
dispatch_semaphore_signal(_timerSemaphore);
dispatch_assert_queue_not(self.timerQueue);
dispatch_async(self.timerQueue, ^{
[self scheduleReconnection];
});
}

- (void)openStreams:(id)sender
Expand Down Expand Up @@ -1315,4 +1309,22 @@ - (void)webSocket:(AWSSRWebSocket *)webSocket didReceivePong:(NSData *)pongPaylo
AWSDDLogVerbose(@"Websocket received pong");
}


# pragma mark - private/serial functions -

- (void)scheduleReconnection {
dispatch_assert_queue(self.timerQueue);

BOOL isConnectingOrConnected = self.mqttStatus == AWSIoTMQTTStatusConnected || self.mqttStatus == AWSIoTMQTTStatusConnecting;
if (!self.reconnectTimer && !isConnectingOrConnected) {
self.reconnectTimer = [NSTimer timerWithTimeInterval:self.currentReconnectTime
target:self
selector: @selector(reconnectToSession)
userInfo:nil
repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:self.reconnectTimer forMode:NSRunLoopCommonModes];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}

@end

0 comments on commit c357ca3

Please sign in to comment.