Mac OS X ambilight
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.8KB

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