标签:
Serial-Number: 0016533f0c1e
Port: 5555
Name: EV3
Protocol: EV3
恭喜你,你已经知道Secret了!
那么如今我们要通过详细的程序来实现它。
- (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
标签:
原文地址:http://www.cnblogs.com/hrhguanli/p/4875384.html