我正在使用一个名为 WiFly 的设备,其 IP 地址为:169.254.1.1 和端口 2000。我正在尝试通过 iOS 应用程序连接到该设备。我使用以下代码进行连接:
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
UInt32 port = 2000;
CFStringRef host = CFSTR("169.254.1.1");
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
// set the delegates to this view controller
[inputStream setDelegate:self];
[outputStream setDelegate:self];
// Set run loops to continuous receive information
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// Finally, open the connection
[inputStream open];
[outputStream open];
然后我使用以下内容来处理流事件:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(@"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"server said: %@", output);
[self messageReceived:output];
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can't connect to server");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
break;
default:
NSLog(@"Unknown event");
}
因此,我可以看到前两个流已正确打开。然后紧随其后的是流事件 4,据我了解,这是可以预料的。但是,然后我尝试调用一个函数:
- (IBAction)moveForward
{
NSLog(@"move forward called");
NSString *response = [NSString stringWithFormat:@"2"];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
哪个应该通过wifly从arduino uno返回“前进”。但是,当我单击时,由于某种原因,我得到了另一个 NSStreamEvent 4。我还通过终端远程登录到设备:
远程登录 169.254.1.1 2000
然后键入“2”...这立即返回了所需的“转发”。从 iPad 的角度来看,我做错了什么?
此外,这段代码在几周前就开始工作了。但是一旦我更新了模拟器,它就停止了工作......连接正常打开,但 arduino 设备似乎没有从 iOS 获得输出。
非常感谢您的帮助!