在读取串口数据时,我使用Grand Central Dispatch Source事件遇到了问题。
我使用dispatch_source_create和DISPATCH_SOURCE_TYPE_READ,这样操作系统将在与串口相关联的fileDescriptor中有数据可读时运行我的代码块。以下是我的代码:
- (void) receiveThread
{
globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ,
[self fileDescriptor],
0,
globalQueue);
dispatch_source_set_event_handler(readSource, ^{
char buffer[512];
NSString *bar;
ssize_t numBytes;
int expected;
expected = dispatch_source_get_data(readSource);
printf("expected:%d\n",expected);
do {
numBytes = read([self fileDescriptor], buffer, 512);
buffer[numBytes] = '\x000'; //make sure that the string is terminated.
printf("bytes:%ld\n",numBytes);
if (numBytes != -1)
{
bar = [NSString stringWithCString:&buffer];
//printf("bytes:%ld\n",numBytes);
NSLog(@"String:%@\n",bar);
[[NSNotificationCenter defaultCenter] postNotificationName:EISerialTextDidArrive object:bar];
}
} while (numBytes > 0);
});
dispatch_resume(readSource);
}
当程序运行时,当串行数据被发送到端口时,该块将首次被调用。然后我会在控制台中收到一条消息。
[Switching to process 11969 thread 0x6603]
当发送更多字符到串口时,代码块不会被调用。我仍然可以通过串口发送字符,并确认有字符被发送进来,但是该代码块不会再次运行。
根据文档和网络上的示例,我期望只要串口缓冲区中有字符,该代码块就会被重复调用。