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 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. //
  2. // Serial.m
  3. // SerialGamepad / 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. kern_return_t findSerialPorts(io_iterator_t *matches);
  21. kern_return_t getSerialPortPath(io_iterator_t serialPortIterator, char **deviceFilePath, CFIndex maxPathCount, CFIndex maxPathSize);
  22. @implementation Serial
  23. @synthesize fd, portName;
  24. - (NSInteger)openPort {
  25. // We need a port name
  26. if (portName == nil) {
  27. NSLog(@"Can't open serial port without name!\n");
  28. return 1;
  29. }
  30. // Check if there was already a port opened
  31. if (fd != -1) {
  32. NSLog(@"Closing previously opened serial port \"%@\"!\n", portName);
  33. close(fd);
  34. }
  35. // Open port read-only, without controlling terminal, non-blocking
  36. fd = open([portName UTF8String], O_RDONLY | O_NOCTTY | O_NONBLOCK);
  37. if (fd == -1) {
  38. NSLog(@"Error opening serial port \"%@\": %s (%d)!\n", portName, strerror(errno), errno);
  39. return 1;
  40. }
  41. // Prevent additional opens except by root-owned processes
  42. if (ioctl(fd, TIOCEXCL) == -1) {
  43. NSLog(@"Error enabling exclusive access on \"%@\": %s (%d)!\n", portName, strerror(errno), errno);
  44. return 1;
  45. }
  46. fcntl(fd, F_SETFL, 0); // Enable blocking I/O
  47. // Read current settings
  48. struct termios options;
  49. tcgetattr(fd, &options);
  50. // Clear all settings
  51. options.c_lflag = 0;
  52. options.c_oflag = 0;
  53. options.c_iflag = 0;
  54. options.c_cflag = 0;
  55. options.c_cflag |= CS8; // 8 data bits
  56. options.c_cflag |= CREAD; // Enable receiver
  57. options.c_cflag |= CLOCAL; // Ignore modem status lines
  58. // Set Baudrate
  59. cfsetispeed(&options, B115200);
  60. cfsetospeed(&options, B115200);
  61. options.c_cc[VMIN] = 0; // Return even with zero bytes...
  62. options.c_cc[VTIME] = 1; // ...but only after .1 seconds
  63. // Set new settings
  64. tcsetattr(fd, TCSANOW, &options);
  65. tcflush(fd, TCIOFLUSH);
  66. return 0;
  67. }
  68. - (NSInteger)hasData {
  69. struct pollfd fds;
  70. fds.fd = fd;
  71. fds.events = (POLLIN | POLLPRI); // Data may be read
  72. if (poll(&fds, 1, 0) > 0) {
  73. return 1;
  74. } else {
  75. return 0;
  76. }
  77. }
  78. + (NSArray *)listSerialPorts {
  79. // Get Iterator with all serial ports
  80. io_iterator_t serialPortIterator;
  81. kern_return_t kernResult = findSerialPorts(&serialPortIterator);
  82. // Create 2D array
  83. char **portList;
  84. portList = malloc(100 * sizeof(char *));
  85. for (int i = 0; i < 100; i++) portList[i] = malloc(200 * sizeof(char));
  86. // Copy device name into C-String array
  87. kernResult = getSerialPortPath(serialPortIterator, portList, 100, 200);
  88. IOObjectRelease(serialPortIterator);
  89. // Copy contents into NSString Array
  90. NSString *stringList[100];
  91. NSUInteger realCount = 0;
  92. while (portList[realCount] != NULL) {
  93. stringList[realCount] = [NSString stringWithCString:portList[realCount] encoding:NSUTF8StringEncoding];
  94. realCount++;
  95. }
  96. // Destroy 2D array
  97. for (int i = 0; i < 100; i++) free(portList[i]);
  98. free(portList);
  99. // And return them as NSArray
  100. return [[NSArray alloc] initWithObjects:stringList count:realCount];
  101. }
  102. @end
  103. kern_return_t findSerialPorts(io_iterator_t *matches) {
  104. kern_return_t kernResult;
  105. mach_port_t masterPort;
  106. CFMutableDictionaryRef classesToMatch;
  107. kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
  108. if (KERN_SUCCESS != kernResult) {
  109. NSLog(@"IOMasterPort returned %d\n", kernResult);
  110. return kernResult;
  111. }
  112. // Serial devices are instances of class IOSerialBSDClient.
  113. classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
  114. if (classesToMatch == NULL) {
  115. NSLog(@"IOServiceMatching returned a NULL dictionary.\n");
  116. } else {
  117. CFDictionarySetValue(classesToMatch,
  118. CFSTR(kIOSerialBSDTypeKey),
  119. CFSTR(kIOSerialBSDRS232Type));
  120. // Each serial device object has a property with key
  121. // kIOSerialBSDTypeKey and a value that is one of
  122. // kIOSerialBSDAllTypes, kIOSerialBSDModemType,
  123. // or kIOSerialBSDRS232Type. You can change the
  124. // matching dictionary to find other types of serial
  125. // devices by changing the last parameter in the above call
  126. // to CFDictionarySetValue.
  127. }
  128. kernResult = IOServiceGetMatchingServices(masterPort, classesToMatch, matches);
  129. if (KERN_SUCCESS != kernResult) {
  130. NSLog(@"IOServiceGetMatchingServices returned %d\n", kernResult);
  131. return kernResult;
  132. }
  133. return kernResult;
  134. }
  135. kern_return_t getSerialPortPath(io_iterator_t serialPortIterator, char **deviceFilePath, CFIndex maxPathCount, CFIndex maxPathSize) {
  136. io_object_t modemService;
  137. kern_return_t kernResult = KERN_FAILURE;
  138. CFIndex i = 0;
  139. while ((modemService = IOIteratorNext(serialPortIterator)) && (i < (maxPathCount - 1))) {
  140. CFTypeRef deviceFilePathAsCFString;
  141. // Get the callout device's path (/dev/cu.xxxxx).
  142. // The callout device should almost always be
  143. // used. You would use the dialin device (/dev/tty.xxxxx) when
  144. // monitoring a serial port for
  145. // incoming calls, for example, a fax listener.
  146. deviceFilePathAsCFString = IORegistryEntryCreateCFProperty(modemService,
  147. CFSTR(kIODialinDeviceKey),
  148. kCFAllocatorDefault,
  149. 0);
  150. if (deviceFilePathAsCFString) {
  151. Boolean result;
  152. deviceFilePath[i][0] = '\0';
  153. // Convert the path from a CFString to a NULL-terminated C string
  154. // for use with the POSIX open() call.
  155. result = CFStringGetCString(deviceFilePathAsCFString,
  156. deviceFilePath[i],
  157. maxPathSize,
  158. kCFStringEncodingASCII);
  159. CFRelease(deviceFilePathAsCFString);
  160. if (result) {
  161. //NSLog(@"BSD path: %s\n", deviceFilePath[i]);
  162. i++;
  163. kernResult = KERN_SUCCESS;
  164. }
  165. }
  166. // Release the io_service_t now that we are done with it.
  167. (void) IOObjectRelease(modemService);
  168. }
  169. deviceFilePath[i] = NULL;
  170. return kernResult;
  171. }