シリアル ポートから読み取るときに、Grand Central Dispatch Source イベントの使用に問題があります。
シリアル ポートに関連付けられている fileDescriptor から読み取るデータがある場合に、OS がコード ブロックを実行するように、dispatch_source_create を DISPATCH_SOURCE_TYPE_READ と共に使用します。これが私のコードです
- (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]
それ以上の文字がシリアル ポートに送信されると、コード ブロックは呼び出されません。シリアル ポートから引き続き文字を送信でき、文字が送信されていることを確認できますが、ブロックは 2 回目に実行されません。
Web 上のドキュメントと例から、シリアル バッファに文字がある限り、ブロックが繰り返し呼び出されることを期待しています。