Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support of NSStream-based communication to Bonjour services via USB #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 20 additions & 23 deletions Peertalk Example/PTAppDelegate.m
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,13 @@ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

// Configure the output NSTextView we use for UI feedback
outputTextView_.textContainerInset = NSMakeSize(15.0, 10.0);
consoleTextAttributes_ = [NSDictionary dictionaryWithObjectsAndKeys:
[NSFont fontWithName:@"helvetica" size:16.0], NSFontAttributeName,
[NSColor lightGrayColor], NSForegroundColorAttributeName,
nil];
consoleStatusTextAttributes_ = [NSDictionary dictionaryWithObjectsAndKeys:
[NSFont fontWithName:@"menlo" size:11.0], NSFontAttributeName,
[NSColor darkGrayColor], NSForegroundColorAttributeName,
nil];
consoleTextAttributes_ = @{NSFontAttributeName: [NSFont fontWithName:@"helvetica" size:16.0],
NSForegroundColorAttributeName: [NSColor lightGrayColor]};
consoleStatusTextAttributes_ = @{NSFontAttributeName: [NSFont fontWithName:@"menlo" size:11.0],
NSForegroundColorAttributeName: [NSColor darkGrayColor]};

// Configure the input NSTextField we use for UI input
[inputTextField_ setFont:[NSFont fontWithDescriptor:[[consoleTextAttributes_ objectForKey:NSFontAttributeName] fontDescriptor] size:14.0]];
inputTextField_.font = [NSFont fontWithDescriptor:[consoleTextAttributes_[NSFontAttributeName] fontDescriptor] size:14.0];
[self.window makeFirstResponder:inputTextField_];

// Start listening for device attached/detached notifications
Expand All @@ -72,7 +68,7 @@ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self presentMessage:@"Ready for action — connecting at will." isStatus:YES];

// Start pinging
[self ping];
//[self ping];
}


Expand Down Expand Up @@ -103,7 +99,7 @@ - (void)presentMessage:(NSString*)message isStatus:(BOOL)isStatus {
[NSAnimationContext beginGrouping];
[NSAnimationContext currentContext].duration = 0.15;
[NSAnimationContext currentContext].timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
NSClipView* clipView = [[self.outputTextView enclosingScrollView] contentView];
NSClipView* clipView = (self.outputTextView).enclosingScrollView.contentView;
NSPoint newOrigin = clipView.bounds.origin;
newOrigin.y += 5.0; // hack A 1/2
[clipView setBoundsOrigin:newOrigin]; // hack A 2/2
Expand Down Expand Up @@ -143,13 +139,13 @@ - (void)setConnectedChannel:(PTChannel*)connectedChannel {


- (void)pongWithTag:(uint32_t)tagno error:(NSError*)error {
NSNumber *tag = [NSNumber numberWithUnsignedInt:tagno];
NSMutableDictionary *pingInfo = [pings_ objectForKey:tag];
NSNumber *tag = @(tagno);
NSMutableDictionary *pingInfo = pings_[tag];
if (pingInfo) {
NSDate *now = [NSDate date];
[pingInfo setObject:now forKey:@"date ended"];
pingInfo[@"date ended"] = now;
[pings_ removeObjectForKey:tag];
NSLog(@"Ping total roundtrip time: %.3f ms", [now timeIntervalSinceDate:[pingInfo objectForKey:@"date created"]]*1000.0);
NSLog(@"Ping total roundtrip time: %.3f ms", [now timeIntervalSinceDate:pingInfo[@"date created"]]*1000.0);
}
}

Expand All @@ -160,12 +156,12 @@ - (void)ping {
pings_ = [NSMutableDictionary dictionary];
}
uint32_t tagno = [connectedChannel_.protocol newTag];
NSNumber *tag = [NSNumber numberWithUnsignedInt:tagno];
NSNumber *tag = @(tagno);
NSMutableDictionary *pingInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSDate date], @"date created", nil];
[pings_ setObject:pingInfo forKey:tag];
pings_[tag] = pingInfo;
[connectedChannel_ sendFrameOfType:PTExampleFrameTypePing tag:tagno withPayload:nil callback:^(NSError *error) {
[self performSelector:@selector(ping) withObject:nil afterDelay:1.0];
[pingInfo setObject:[NSDate date] forKey:@"date sent"];
pingInfo[@"date sent"] = [NSDate date];
if (error) {
[pings_ removeObjectForKey:tag];
}
Expand Down Expand Up @@ -227,22 +223,21 @@ - (void)startListeningForDevices {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

[nc addObserverForName:PTUSBDeviceDidAttachNotification object:PTUSBHub.sharedHub queue:nil usingBlock:^(NSNotification *note) {
NSNumber *deviceID = [note.userInfo objectForKey:@"DeviceID"];
NSNumber *deviceID = (note.userInfo)[@"DeviceID"];
//NSLog(@"PTUSBDeviceDidAttachNotification: %@", note.userInfo);
NSLog(@"PTUSBDeviceDidAttachNotification: %@", deviceID);

dispatch_async(notConnectedQueue_, ^{
if (!connectingToDeviceID_ || ![deviceID isEqualToNumber:connectingToDeviceID_]) {
[self disconnectFromCurrentChannel];
connectingToDeviceID_ = deviceID;
connectedDeviceProperties_ = [note.userInfo objectForKey:@"Properties"];
connectingToDeviceID_ = deviceID; connectedDeviceProperties_ = (note.userInfo)[@"Properties"];
[self enqueueConnectToUSBDevice];
}
});
}];

[nc addObserverForName:PTUSBDeviceDidDetachNotification object:PTUSBHub.sharedHub queue:nil usingBlock:^(NSNotification *note) {
NSNumber *deviceID = [note.userInfo objectForKey:@"DeviceID"];
NSNumber *deviceID = (note.userInfo)[@"DeviceID"];
//NSLog(@"PTUSBDeviceDidDetachNotification: %@", note.userInfo);
NSLog(@"PTUSBDeviceDidDetachNotification: %@", deviceID);

Expand Down Expand Up @@ -308,7 +303,9 @@ - (void)connectToLocalIPv4Port {
- (void)enqueueConnectToUSBDevice {
dispatch_async(notConnectedQueue_, ^{
dispatch_async(dispatch_get_main_queue(), ^{
[self connectToUSBDevice];
if (connectingToDeviceID_) {
[self connectToUSBDevice];
}
});
});
}
Expand Down
70 changes: 70 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ PeerTalk is an iOS and Mac Cocoa library for communicating over USB.

4. Tested and designed for libdispatch (aka Grand Central Dispatch).

5. Now compatible with Bonjour® services and NSStream-based programs

Grab the goods from [https://github.com/rsms/peertalk](https://github.com/rsms/peertalk)


Expand Down Expand Up @@ -62,3 +64,71 @@ It _should_ work.
Demo video: [http://www.youtube.com/watch?v=kQPWy8N0mBg](http://www.youtube.com/watch?v=kQPWy8N0mBg)

<iframe width="880" height="530" src="http://www.youtube.com/embed/kQPWy8N0mBg?hd=1&amp;rel=0" frameborder="0" allowfullscreen></iframe>

## Using peertalk with Bonjour

Peertalk can now be used to connect from a macOS application to a Bonjour service running on a USB-attached iOS device. It only involves a small modification of your existing Bonjour code.

When you want to connect to a Bonjour service, you generally use a `NSNetService` object associated with a class implementing the `NSNetServiceDelegate`protocol. Then you *resolve* the Bonjour service:

````
// self implements the NSNetServiceDelegate protocol
NSString *serviceName = ...;
NSString *serviceType = @"_music._tcp"; // or any custom service type prided by your iOS app
NSNetService *service;

service = [[NSNetService alloc] initWithDomain:@"local." type: serviceType name:serviceName];
service.delegate = self;
[service resolveWithTimeout:5.0];
````

Then you implement the delegate method `netServiceDidResolveAddress`:

````
- (void)netServiceDidResolveAddress:(NSNetService *)netService
{
// netService has been succesfuly resolved, its hostname and port are now set

// First try to connect to the service using a USB link
[PTUSBHub.sharedHub connectToDeviceWithHostName: netService.hostName port:(int)netService.port
onStart:^(NSError *error, NSInputStream *inStream, NSOutputStream *outStream) {

if ((inStream == nil) || (outStream == nil)) {
// USB connection did not succeed or was not supported: connect to the resolved service via standard Bonjour mechanism
[netService getInputStream:&inStream outputStream:&outStream];
}

if ((inStream != nil) && (outStream != nil)) {
// ... Use the NSStreams for communicating with the service
}
}];

}
````

### In the iOS app providing the Bonjour service

For this mechanism to work, **peertalk** needs a way to know the Bonjour hostname of the USB-connected iOS device providing the Bonjour service.

This is achieved by running a `PTHostNameProvider` in your iOS application, typically in the AppDelegate:

````
#import "AppDelegate.h"
#import "PTHostnameProvider.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[PTHostNameProvider start];

// Other inits ...
return YES;
}

// ...

@end

````

25 changes: 24 additions & 1 deletion peertalk.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@
EE158A911CBD412900A3E3F0 /* PTChannel.m in Sources */ = {isa = PBXBuildFile; fileRef = 6ACFD2D5151D36220081ACF5 /* PTChannel.m */; };
EE158A921CBD412900A3E3F0 /* PTProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 6A88FA5D150D61DE00FC3647 /* PTProtocol.m */; };
EE158A931CBD412900A3E3F0 /* PTUSBHub.m in Sources */ = {isa = PBXBuildFile; fileRef = 6A88FA5F150D61DE00FC3647 /* PTUSBHub.m */; };
FD3344791EC3042C00FD641D /* PTHostnameProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = FD3344771EC3042C00FD641D /* PTHostnameProvider.h */; };
FD33447C1EC305D000FD641D /* PTHostnameProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = FD3344781EC3042C00FD641D /* PTHostnameProvider.m */; };
FD33447D1EC305E700FD641D /* PTHostnameProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = FD3344781EC3042C00FD641D /* PTHostnameProvider.m */; };
FD33447E1EC3073A00FD641D /* PTHostnameProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = FD3344781EC3042C00FD641D /* PTHostnameProvider.m */; };
FD33447F1EC3074400FD641D /* PTHostnameProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = FD3344781EC3042C00FD641D /* PTHostnameProvider.m */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -104,7 +109,7 @@
6A64AAEF1526050D0065BF86 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
6A64AAF11526050D0065BF86 /* Peertalk iOS Example-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Peertalk iOS Example-Prefix.pch"; sourceTree = "<group>"; };
6A64AAF21526050D0065BF86 /* PTAppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PTAppDelegate.h; sourceTree = "<group>"; };
6A64AAF31526050D0065BF86 /* PTAppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PTAppDelegate.m; sourceTree = "<group>"; };
6A64AAF31526050D0065BF86 /* PTAppDelegate.m */ = {isa = PBXFileReference; indentWidth = 2; lastKnownFileType = sourcecode.c.objc; path = PTAppDelegate.m; sourceTree = "<group>"; };
6A64AAF61526050D0065BF86 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = en; path = en.lproj/MainStoryboard_iPhone.storyboard; sourceTree = "<group>"; };
6A64AAF91526050D0065BF86 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = en; path = en.lproj/MainStoryboard_iPad.storyboard; sourceTree = "<group>"; };
6A64AAFB1526050D0065BF86 /* PTViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PTViewController.h; sourceTree = "<group>"; };
Expand All @@ -130,6 +135,8 @@
EE158A5B1CBD3EB600A3E3F0 /* Peertalk.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Peertalk.framework; sourceTree = BUILT_PRODUCTS_DIR; };
EE158A681CBD3ED700A3E3F0 /* Peertalk.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Peertalk.framework; sourceTree = BUILT_PRODUCTS_DIR; };
EE158A7C1CBD402600A3E3F0 /* Peertalk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Peertalk.h; sourceTree = "<group>"; };
FD3344771EC3042C00FD641D /* PTHostnameProvider.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PTHostnameProvider.h; sourceTree = "<group>"; };
FD3344781EC3042C00FD641D /* PTHostnameProvider.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PTHostnameProvider.m; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -302,6 +309,8 @@
6A88FA5D150D61DE00FC3647 /* PTProtocol.m */,
6A88FA5E150D61DE00FC3647 /* PTUSBHub.h */,
6A88FA5F150D61DE00FC3647 /* PTUSBHub.m */,
FD3344771EC3042C00FD641D /* PTHostnameProvider.h */,
FD3344781EC3042C00FD641D /* PTHostnameProvider.m */,
);
path = peertalk;
sourceTree = "<group>";
Expand Down Expand Up @@ -335,6 +344,7 @@
files = (
6A88FA60150D61DE00FC3647 /* PTProtocol.h in Headers */,
6A88FA62150D61DE00FC3647 /* PTUSBHub.h in Headers */,
FD3344791EC3042C00FD641D /* PTHostnameProvider.h in Headers */,
6ACFD2D6151D36220081ACF5 /* PTChannel.h in Headers */,
5E2C5024171F46A6008A9752 /* PTPrivate.h in Headers */,
EE158A7D1CBD402600A3E3F0 /* Peertalk.h in Headers */,
Expand Down Expand Up @@ -480,6 +490,10 @@
attributes = {
LastUpgradeCheck = 0800;
TargetAttributes = {
6A64AAE11526050D0065BF86 = {
DevelopmentTeam = 7V6VCE4Z4V;
ProvisioningStyle = Manual;
};
EE158A5A1CBD3EB600A3E3F0 = {
CreatedOnToolsVersion = 7.3;
};
Expand Down Expand Up @@ -579,6 +593,7 @@
6A64AAFD1526050D0065BF86 /* PTViewController.m in Sources */,
6A64AB0815260E5C0065BF86 /* PTChannel.m in Sources */,
6A64AB0915260E600065BF86 /* PTProtocol.m in Sources */,
FD33447C1EC305D000FD641D /* PTHostnameProvider.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand All @@ -587,6 +602,7 @@
buildActionMask = 2147483647;
files = (
6A88FA61150D61DE00FC3647 /* PTProtocol.m in Sources */,
FD33447E1EC3073A00FD641D /* PTHostnameProvider.m in Sources */,
6A88FA63150D61DE00FC3647 /* PTUSBHub.m in Sources */,
6ACFD2D7151D36220081ACF5 /* PTChannel.m in Sources */,
);
Expand All @@ -605,6 +621,7 @@
buildActionMask = 2147483647;
files = (
EE158A8E1CBD412900A3E3F0 /* PTChannel.m in Sources */,
FD33447F1EC3074400FD641D /* PTHostnameProvider.m in Sources */,
EE158A901CBD412900A3E3F0 /* PTUSBHub.m in Sources */,
EE158A8F1CBD412900A3E3F0 /* PTProtocol.m in Sources */,
);
Expand All @@ -615,6 +632,7 @@
buildActionMask = 2147483647;
files = (
EE158A911CBD412900A3E3F0 /* PTChannel.m in Sources */,
FD33447D1EC305E700FD641D /* PTHostnameProvider.m in Sources */,
EE158A931CBD412900A3E3F0 /* PTUSBHub.m in Sources */,
EE158A921CBD412900A3E3F0 /* PTProtocol.m in Sources */,
);
Expand Down Expand Up @@ -727,6 +745,7 @@
isa = XCBuildConfiguration;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
DEVELOPMENT_TEAM = 7V6VCE4Z4V;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"\"$(SYSTEM_APPS_DIR)/Xcode.app/Contents/Developer/Library/Frameworks\"",
Expand All @@ -738,6 +757,8 @@
MACOSX_DEPLOYMENT_TARGET = "";
PRODUCT_BUNDLE_IDENTIFIER = "me.rsms.peertalk.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE = "d94a7d2e-a9d8-4123-8d0d-e2dc2e060926";
PROVISIONING_PROFILE_SPECIFIER = "iOS Dev Provisioning Profile";
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
WRAPPER_EXTENSION = app;
Expand All @@ -748,6 +769,7 @@
isa = XCBuildConfiguration;
buildSettings = {
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
DEVELOPMENT_TEAM = "";
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"\"$(SYSTEM_APPS_DIR)/Xcode.app/Contents/Developer/Library/Frameworks\"",
Expand All @@ -760,6 +782,7 @@
OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1";
PRODUCT_BUNDLE_IDENTIFIER = "me.rsms.peertalk.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
Expand Down
41 changes: 41 additions & 0 deletions peertalk/PTHostnameProvider.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//
// PTHostnameProvider.h
//
// Copyright (c) 2017 Jean-Luc Jumpertz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#define kPTHostnameProviderPort 22101

// Hostname response protocol
// Bytes 0-1: message length in network order (big-endian)
// Bytes 2-7: magic string "Host: "
// Bytes 8-...: null-terminated dns/bonjour hostname, like "My-iPhone.local."

#define kPTHostnameProviderResponseMagicString "Host: "

#define kPTHostnameProviderResponseOffsetMagicString 2
#define kPTHostnameProviderResponseOffsetHostname 8

@interface PTHostNameProvider: NSObject

+ (void) start;

@end

Loading