Serial-Number: 0016533f0c1e
Port: 5555
Name: EV3
Protocol: EV3
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
fromAddress:(NSData *)address
withFilterContext:(id)filterContext
{
// 1
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (msg)
{
// 2
NSString *serialNumber = [msg substringWithRange:NSMakeRange(14, 12)];
NSString *host = [GCDAsyncUdpSocket hostFromAddress:address];
EV3Device *device = [self.devices objectForKey:host];
if (!device && host.length < 20) {
// 3
EV3Device *aDevice = [[EV3Device alloc] initWithSerialNumber:serialNumber address:host tag:self.devices.count isConnected:NO];
// 4
dispatch_queue_t tcpSocketQueue = dispatch_queue_create("com.manmanlai.tcpSocketQueue", DISPATCH_QUEUE_CONCURRENT);
GCDAsyncSocket *tcpSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:tcpSocketQueue];
aDevice.tcpSocket = tcpSocket;
[self.devices setObject:aDevice forKey:aDevice.address];
if ([self.delegate respondsToSelector:@selector(updateView)]) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate updateView];
});
}
}
}
else
{
NSLog(@"Error converting received data into UTF-8 String");
}
// 5
[self.udpSocket sendData:data toAddress:address withTimeout:-1 tag:0];
}
- (void)connectTCPSocketWithDevice:(EV3Device *)device
{
GCDAsyncSocket *tcpSocket = device.tcpSocket;
// connnect
NSError *error = nil;
if (![tcpSocket connectToHost:device.address
onPort:5555
error:&error])
{
NSLog(@"Error connecting: %@", error);
} else {
NSLog(@"Connected");
// write data
NSLog(@"writing...");
NSString *unlockMsg = [NSString stringWithFormat:@"GET /target?sn=%@ VMTP1.0 Protocol: EV3",device.serialNumber];
NSData *unlockData = [unlockMsg dataUsingEncoding:NSUTF8StringEncoding];
[tcpSocket writeData:unlockData withTimeout:-1 tag:MESSAGE_UNLOCK];
[tcpSocket readDataWithTimeout:-1 tag:MESSAGE_UNLOCK];
}
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *host = sock.connectedHost;
EV3Device *device = [self.devices objectForKey:host];
[device handleReceivedData:data withTag:tag];
}
case MESSAGE_UNLOCK:
{
NSString *httpResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *response =[httpResponse substringToIndex:12];
if ([response isEqualToString:@"Accept:EV340"]) {
self.isConnected = YES;
NSLog(@"ev3 connected");
dispatch_async(dispatch_get_main_queue(), ^{
[self scanPorts];
[[NSNotificationCenter defaultCenter] postNotificationName:EV3DeviceConnectedNotification object:self];
});
}
break;
}
【iOS与EV3混合机器人编程系列之五】iOS_WiFi_EV3_Library 剖析之连接EV3,布布扣,bubuko.com
【iOS与EV3混合机器人编程系列之五】iOS_WiFi_EV3_Library 剖析之连接EV3
原文地址:http://blog.csdn.net/songrotek/article/details/37883133