Simple RGB LED controller for Mac OS X
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Serial.m 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // Serial.m
  3. // CaseLights
  4. //
  5. // For more informations refer to this document:
  6. // https://developer.apple.com/library/mac/documentation/DeviceDrivers/Conceptual/WorkingWSerial/WWSerial_SerialDevs/SerialDevices.html
  7. //
  8. // Created by Thomas Buck on 14.12.15.
  9. // Copyright © 2015 xythobuz. All rights reserved.
  10. //
  11. #import <Cocoa/Cocoa.h>
  12. #import <IOKit/IOKitLib.h>
  13. #import <IOKit/serial/IOSerialKeys.h>
  14. #import <termios.h>
  15. #import <fcntl.h>
  16. #import <unistd.h>
  17. #import <poll.h>
  18. #import <sys/ioctl.h>
  19. #import "Serial.h"
  20. @interface Serial ()
  21. @property (assign) int fd;
  22. + (kern_return_t)findSerialPorts:(io_iterator_t *)matches;
  23. + (kern_return_t)getSerialPortPath:(io_iterator_t)serialPortIterator to:(char **)deviceFilePath with:(CFIndex)maxPathCount and:(CFIndex)maxPathSize;
  24. @end
  25. @implementation Serial
  26. @synthesize fd, portName;
  27. - (id)init {
  28. self = [super init];
  29. if (self != nil) {
  30. fd = -1;
  31. portName = nil;
  32. }
  33. return self;
  34. }
  35. - (NSInteger)openPort {
  36. // We need a port name
  37. if (portName == nil) {
  38. NSLog(@"Can't open serial port without name!\n");
  39. return 1;
  40. }
  41. // Check if there was already a port opened
  42. if (fd > -1) {
  43. NSLog(@"Closing previously opened serial port \"%@\"!\n", portName);
  44. close(fd);
  45. }
  46. #ifdef DEBUG
  47. NSLog(@"Opening serial port \"%@\"...\n", portName);
  48. #endif
  49. // Open port read-only, without controlling terminal, non-blocking
  50. fd = open([portName UTF8String], O_RDONLY | O_NOCTTY | O_NONBLOCK);
  51. if (fd == -1) {
  52. NSLog(@"Error opening serial port \"%@\": %s (%d)!\n", portName, strerror(errno), errno);
  53. return 1;
  54. }
  55. // Prevent additional opens except by root-owned processes
  56. if (ioctl(fd, TIOCEXCL) == -1) {
  57. NSLog(@"Error enabling exclusive access on \"%@\": %s (%d)!\n", portName, strerror(errno), errno);
  58. return 1;
  59. }
  60. fcntl(fd, F_SETFL, 0); // Enable blocking I/O
  61. // Read current settings
  62. struct termios options;
  63. tcgetattr(fd, &options);
  64. // Clear all settings
  65. options.c_lflag = 0;
  66. options.c_oflag = 0;
  67. options.c_iflag = 0;
  68. options.c_cflag = 0;
  69. options.c_cflag |= CS8; // 8 data bits
  70. options.c_cflag |= CREAD; // Enable receiver
  71. options.c_cflag |= CLOCAL; // Ignore modem status lines
  72. // Set Baudrate
  73. cfsetispeed(&options, B115200);
  74. cfsetospeed(&options, B115200);
  75. options.c_cc[VMIN] = 0; // Return even with zero bytes...
  76. options.c_cc[VTIME] = 1; // ...but only after .1 seconds
  77. // Set new settings
  78. tcsetattr(fd, TCSANOW, &options);
  79. tcflush(fd, TCIOFLUSH);
  80. return 0;
  81. }
  82. - (void)closePort {
  83. #ifdef DEBUG
  84. NSLog(@"Closing serial port \"%@\"...\n", portName);
  85. #endif
  86. if (fd > -1) {
  87. close(fd);
  88. } else {
  89. NSLog(@"Trying to close already closed port!\n");
  90. }
  91. fd = -1;
  92. }
  93. - (BOOL)isOpen {
  94. if (fd > -1) {
  95. return YES;
  96. } else {
  97. return NO;
  98. }
  99. }
  100. - (BOOL)hasData {
  101. if (fd < 0) {
  102. NSLog(@"Error trying to poll a closed port!\n");
  103. return NO;
  104. }
  105. struct pollfd fds;
  106. fds.fd = fd;
  107. fds.events = (POLLIN | POLLPRI); // Data may be read
  108. int val = poll(&fds, 1, 0);
  109. if (val > 0) {
  110. return YES;
  111. } else if (val == 0) {
  112. return NO;
  113. } else {
  114. NSLog(@"Error polling serial port: %s (%d)!\n", strerror(errno), errno);
  115. return NO;
  116. }
  117. }
  118. - (void)sendString:(NSString *)string {
  119. if (fd < 0) {
  120. NSLog(@"Error trying to send to a closed port!\n");
  121. return;
  122. }
  123. const char *data = [string UTF8String];
  124. size_t length = strlen(data);
  125. ssize_t sent = 0;
  126. while (sent < length) {
  127. ssize_t ret = write(fd, data + sent, length - sent);
  128. if (ret < 0) {
  129. NSLog(@"Error writing to serial port: %s (%d)!\n", strerror(errno), errno);
  130. } else {
  131. sent += ret;
  132. }
  133. }
  134. }
  135. + (NSArray *)listSerialPorts {
  136. // Get Iterator with all serial ports
  137. io_iterator_t serialPortIterator;
  138. kern_return_t kernResult = [Serial findSerialPorts:&serialPortIterator];
  139. // Create 2D array
  140. char **portList;
  141. portList = malloc(100 * sizeof(char *));
  142. for (int i = 0; i < 100; i++) portList[i] = malloc(200 * sizeof(char));
  143. // Copy device name into C-String array
  144. kernResult = [Serial getSerialPortPath:serialPortIterator to:portList with:100 and:200];
  145. IOObjectRelease(serialPortIterator);
  146. // Copy contents into NSString Array
  147. NSString *stringList[100];
  148. NSUInteger realCount = 0;
  149. while (portList[realCount] != NULL) {
  150. stringList[realCount] = [NSString stringWithCString:portList[realCount] encoding:NSUTF8StringEncoding];
  151. realCount++;
  152. }
  153. // Destroy 2D array
  154. for (int i = 0; i < 100; i++) free(portList[i]);
  155. free(portList);
  156. // And return them as NSArray
  157. return [[NSArray alloc] initWithObjects:stringList count:realCount];
  158. }
  159. + (kern_return_t)findSerialPorts:(io_iterator_t *)matches {
  160. kern_return_t kernResult;
  161. mach_port_t masterPort;
  162. CFMutableDictionaryRef classesToMatch;
  163. kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
  164. if (KERN_SUCCESS != kernResult) {
  165. NSLog(@"IOMasterPort returned %d\n", kernResult);
  166. return kernResult;
  167. }
  168. // Serial devices are instances of class IOSerialBSDClient.
  169. classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
  170. if (classesToMatch == NULL) {
  171. NSLog(@"IOServiceMatching returned a NULL dictionary.\n");
  172. } else {
  173. CFDictionarySetValue(classesToMatch,
  174. CFSTR(kIOSerialBSDTypeKey),
  175. CFSTR(kIOSerialBSDRS232Type));
  176. // Each serial device object has a property with key
  177. // kIOSerialBSDTypeKey and a value that is one of
  178. // kIOSerialBSDAllTypes, kIOSerialBSDModemType,
  179. // or kIOSerialBSDRS232Type. You can change the
  180. // matching dictionary to find other types of serial
  181. // devices by changing the last parameter in the above call
  182. // to CFDictionarySetValue.
  183. }
  184. kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, matches);
  185. if (KERN_SUCCESS != kernResult) {
  186. NSLog(@"IOServiceGetMatchingServices returned %d\n", kernResult);
  187. return kernResult;
  188. }
  189. return kernResult;
  190. }
  191. + (kern_return_t)getSerialPortPath:(io_iterator_t)serialPortIterator to:(char **)deviceFilePath with:(CFIndex)maxPathCount and:(CFIndex)maxPathSize {
  192. io_object_t modemService;
  193. kern_return_t kernResult = KERN_FAILURE;
  194. CFIndex i = 0;
  195. while ((modemService = IOIteratorNext(serialPortIterator)) && (i < (maxPathCount - 1))) {
  196. CFTypeRef deviceFilePathAsCFString;
  197. // Get the callout device's path (/dev/cu.xxxxx).
  198. // The callout device should almost always be
  199. // used. You would use the dialin device (/dev/tty.xxxxx) when
  200. // monitoring a serial port for
  201. // incoming calls, for example, a fax listener.
  202. deviceFilePathAsCFString = IORegistryEntryCreateCFProperty(modemService,
  203. CFSTR(kIODialinDeviceKey),
  204. kCFAllocatorDefault,
  205. 0);
  206. if (deviceFilePathAsCFString) {
  207. Boolean result;
  208. deviceFilePath[i][0] = '\0';
  209. // Convert the path from a CFString to a NULL-terminated C string
  210. // for use with the POSIX open() call.
  211. result = CFStringGetCString(deviceFilePathAsCFString,
  212. deviceFilePath[i],
  213. maxPathSize,
  214. kCFStringEncodingASCII);
  215. CFRelease(deviceFilePathAsCFString);
  216. if (result) {
  217. //NSLog(@"BSD path: %s\n", deviceFilePath[i]);
  218. i++;
  219. kernResult = KERN_SUCCESS;
  220. }
  221. }
  222. // Release the io_service_t now that we are done with it.
  223. (void) IOObjectRelease(modemService);
  224. }
  225. deviceFilePath[i] = NULL;
  226. return kernResult;
  227. }
  228. @end