【iOS与EV3混合机器人编程系列之五】iOS_WiFi_EV3_Library 剖析之连接EV3
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,,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。