Skip to content

Instantly share code, notes, and snippets.

@rsms
Created July 16, 2014 00:20
Show Gist options
  • Save rsms/0f853a0c8c7753639498 to your computer and use it in GitHub Desktop.
Save rsms/0f853a0c8c7753639498 to your computer and use it in GitHub Desktop.
Note that this is just an idea. This code might not even compile, and you'd want to observe PTChannel disconnects & errors to remove or reset the _devices dict.
@interface MyThing {
NSMutableDictionary* _devices;
// <NSNumber*deviceID>=<NSNull> while connecting
// <NSNumber*deviceID>=<PTChannel> while connected
}
- (void)startListeningForDevices {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserverForName:PTUSBDeviceDidAttachNotification object:PTUSBHub.sharedHub queue:nil usingBlock:^(NSNotification *note) {
NSNumber* deviceID = [note.userInfo objectForKey:@"DeviceID"];
NSLog(@"Device attached: %@", deviceID);
_devices[deviceID] = [NSNull null];
[self connectToDeviceWithDeviceID:deviceID];
}];
[nc addObserverForName:PTUSBDeviceDidDetachNotification object:PTUSBHub.sharedHub queue:nil usingBlock:^(NSNotification *note) {
NSNumber *deviceID = [note.userInfo objectForKey:@"DeviceID"];
NSLog(@"Device detached: %@", deviceID);
PTChannel* chan = _devices[deviceID];
[_devices removeObjectForKey:deviceID];
if (![chan isKindOfClass:[NSNull class]]) {
[chan close];
}
}];
}
- (void)connectToDeviceWithDeviceID:(NSNumber*)deviceID {
const NSTimeInterval kDeviceReconnectDelay = 0.5;
const int kMyThingTCPPortNumber = 1234;
PTChannel *channel = [PTChannel channelWithDelegate:self];
[channel connectToPort:kMyThingTCPPortNumber overUSBHub:PTUSBHub.sharedHub deviceID:deviceID callback:^(NSError *error) {
if (error) {
NSLog(@"Failed to connect to device #%@: %@", deviceID, error);
if (_devices[deviceID]) {
NSLog(@"Retrying connection to device #%@ in %f seconds", deviceID, kDeviceReconnectDelay);
[self performSelector:_cmd withObject:deviceID afterDelay:kDeviceReconnectDelay];
}
} else {
_devices[deviceID] = channel;
}
}];
}
- (void)forEachConnectedChannel:(void(^)(PTChannel* chan))fn {
for (PTChannel* chan : _devices) {
if (![chan isKindOfClass:[NSNull class]]) {
fn(chan);
}
}
}
- (void)sendMessageToAllDevices:(NSString*)message {
dispatch_data_t payload = PTExampleTextDispatchDataWithString(message);
[self forEachConnectedChannel:^(PTChannel* chan) {
[chan sendFrameOfType:PTExampleFrameTypeTextMessage tag:PTFrameNoTag withPayload:payload callback:^(NSError *error) {
if (error) NSLog(@"Failed to send message: %@", error);
}];
}];
}
@end // MyThing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment