Simple RGB LED controller for Mac OS X
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Serial.m 8.6KB

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