我正在尝试编写一个命令行 Foundation Objective-C 程序,我需要与 RS232 串行设备通信。
关于如何做到这一点的任何想法?
编辑 - 这不适用于 iPhone!这是一个桌面应用程序。
我正在尝试编写一个命令行 Foundation Objective-C 程序,我需要与 RS232 串行设备通信。
关于如何做到这一点的任何想法?
编辑 - 这不适用于 iPhone!这是一个桌面应用程序。
我假设您使用的是 RS-232/USB 适配器。如果我这样做,我会弄清楚它显示在哪个设备上,然后使用 open("/dev/ttyS0", etc) 函数打开它。然后,您可以将文件描述符和访问函数包装在一个对象中。
这是在 POSIX 环境中使用串行端口的页面: http ://www.easysw.com/~mike/serial/serial.html
我使用了 moxa 的所谓“串行设备服务器”,它就像一个魅力。
优于 USB 串行转换器的优点:
设备服务器通常允许您使用LAN或WiFi等网络连接到串行设备。
软件方面,这将是非常简单的网络/套接字编程,例如:
(使用GCDAsyncSocket)
准备数据
static u_int8_t cmd1[] = { 0x1a, 0x73, 0x10 }; //defined by the serial device's protocol
static u_int8_t cmd2[] = { 0x1b, 0x51, 0x01 };
self.data = [NSMutableData dataWithBytes:&cmd1 length:sizeof(cmd1)];
[self.data appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
[self.data appendBytes:&cmd2 length:sizeof(cmd2)];
发送数据
-(IBAction)buttonAction:(id)sender
{
NSError *error = nil;
[self.socket connectToHost:@"192.168.1.9" onPort:1234 withTimeout:-1 error:&error];
if (error) {
NSLog(@"error: %@", error);
}
}
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
[self.socket writeData:self.data withTimeout:-1 tag:23];
}