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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. #ifdef DEBUG
  126. NSLog(@"Sending string \"%s\"...\n", data);
  127. #endif
  128. ssize_t sent = 0;
  129. while (sent < length) {
  130. ssize_t ret = write(fd, data + sent, length - sent);
  131. if (ret < 0) {
  132. NSLog(@"Error writing to serial port: %s (%d)!\n", strerror(errno), errno);
  133. } else {
  134. sent += ret;
  135. }
  136. }
  137. }
  138. + (NSArray *)listSerialPorts {
  139. // Get Iterator with all serial ports
  140. io_iterator_t serialPortIterator;
  141. kern_return_t kernResult = [Serial findSerialPorts:&serialPortIterator];
  142. // Create 2D array
  143. char **portList;
  144. portList = malloc(100 * sizeof(char *));
  145. for (int i = 0; i < 100; i++) portList[i] = malloc(200 * sizeof(char));
  146. // Copy device name into C-String array
  147. kernResult = [Serial getSerialPortPath:serialPortIterator to:portList with:100 and:200];
  148. IOObjectRelease(serialPortIterator);
  149. // Copy contents into NSString Array
  150. NSString *stringList[100];
  151. NSUInteger realCount = 0;
  152. while (portList[realCount] != NULL) {
  153. stringList[realCount] = [NSString stringWithCString:portList[realCount] encoding:NSUTF8StringEncoding];
  154. realCount++;
  155. }
  156. // Destroy 2D array
  157. for (int i = 0; i < 100; i++) free(portList[i]);
  158. free(portList);
  159. // And return them as NSArray
  160. return [[NSArray alloc] initWithObjects:stringList count:realCount];
  161. }
  162. + (kern_return_t)findSerialPorts:(io_iterator_t *)matches {
  163. kern_return_t kernResult;
  164. mach_port_t masterPort;
  165. CFMutableDictionaryRef classesToMatch;
  166. kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
  167. if (KERN_SUCCESS != kernResult) {
  168. NSLog(@"IOMasterPort returned %d\n", kernResult);
  169. return kernResult;
  170. }
  171. // Serial devices are instances of class IOSerialBSDClient.
  172. classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
  173. if (classesToMatch == NULL) {
  174. NSLog(@"IOServiceMatching returned a NULL dictionary.\n");
  175. } else {
  176. CFDictionarySetValue(classesToMatch,
  177. CFSTR(kIOSerialBSDTypeKey),
  178. CFSTR(kIOSerialBSDRS232Type));
  179. // Each serial device object has a property with key
  180. // kIOSerialBSDTypeKey and a value that is one of
  181. // kIOSerialBSDAllTypes, kIOSerialBSDModemType,
  182. // or kIOSerialBSDRS232Type. You can change the
  183. // matching dictionary to find other types of serial
  184. // devices by changing the last parameter in the above call
  185. // to CFDictionarySetValue.
  186. }
  187. kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, matches);
  188. if (KERN_SUCCESS != kernResult) {
  189. NSLog(@"IOServiceGetMatchingServices returned %d\n", kernResult);
  190. return kernResult;
  191. }
  192. return kernResult;
  193. }
  194. + (kern_return_t)getSerialPortPath:(io_iterator_t)serialPortIterator to:(char **)deviceFilePath with:(CFIndex)maxPathCount and:(CFIndex)maxPathSize {
  195. io_object_t modemService;
  196. kern_return_t kernResult = KERN_FAILURE;
  197. CFIndex i = 0;
  198. while ((modemService = IOIteratorNext(serialPortIterator)) && (i < (maxPathCount - 1))) {
  199. CFTypeRef deviceFilePathAsCFString;
  200. // Get the callout device's path (/dev/cu.xxxxx).
  201. // The callout device should almost always be
  202. // used. You would use the dialin device (/dev/tty.xxxxx) when
  203. // monitoring a serial port for
  204. // incoming calls, for example, a fax listener.
  205. deviceFilePathAsCFString = IORegistryEntryCreateCFProperty(modemService,
  206. CFSTR(kIODialinDeviceKey),
  207. kCFAllocatorDefault,
  208. 0);
  209. if (deviceFilePathAsCFString) {
  210. Boolean result;
  211. deviceFilePath[i][0] = '\0';
  212. // Convert the path from a CFString to a NULL-terminated C string
  213. // for use with the POSIX open() call.
  214. result = CFStringGetCString(deviceFilePathAsCFString,
  215. deviceFilePath[i],
  216. maxPathSize,
  217. kCFStringEncodingASCII);
  218. CFRelease(deviceFilePathAsCFString);
  219. if (result) {
  220. //NSLog(@"BSD path: %s\n", deviceFilePath[i]);
  221. i++;
  222. kernResult = KERN_SUCCESS;
  223. }
  224. }
  225. // Release the io_service_t now that we are done with it.
  226. (void) IOObjectRelease(modemService);
  227. }
  228. deviceFilePath[i] = NULL;
  229. return kernResult;
  230. }
  231. @end