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.6KB

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