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.

Thread.m 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // Thread.m
  3. // SerialGamepad
  4. //
  5. // Created by Thomas Buck on 15.12.15.
  6. // Copyright © 2015 xythobuz. All rights reserved.
  7. //
  8. #import <termios.h>
  9. #import <fcntl.h>
  10. #import <unistd.h>
  11. #include <poll.h>
  12. #import "Thread.h"
  13. #import "AppDelegate.h"
  14. @implementation Thread
  15. @synthesize running, fd, portName, appDelegate;
  16. - (id)initWithDelegate:(AppDelegate *)delegate {
  17. self = [super init];
  18. if (self != nil) {
  19. appDelegate = delegate;
  20. }
  21. return self;
  22. }
  23. - (NSInteger)openPort {
  24. if (portName == nil) {
  25. return 1;
  26. }
  27. // Open port read-only, without controlling terminal, non-blocking
  28. fd = open([portName UTF8String], O_RDONLY | O_NOCTTY | O_NONBLOCK);
  29. if (fd == -1) {
  30. NSLog(@"Error opening serial port \"%@\"!\n", portName);
  31. return 1;
  32. }
  33. fcntl(fd, F_SETFL, 0); // Enable blocking I/O
  34. // Read current settings
  35. struct termios options;
  36. tcgetattr(fd, &options);
  37. options.c_lflag = 0;
  38. options.c_oflag = 0;
  39. options.c_iflag = 0;
  40. options.c_cflag = 0;
  41. options.c_cflag |= CS8; // 8 data bits
  42. options.c_cflag |= CREAD; // Enable receiver
  43. options.c_cflag |= CLOCAL; // Ignore modem status lines
  44. cfsetispeed(&options, B115200);
  45. cfsetospeed(&options, B115200);
  46. options.c_cc[VMIN] = 0; // Return even with zero bytes...
  47. options.c_cc[VTIME] = 1; // ...but only after .1 seconds
  48. // Set new settings
  49. tcsetattr(fd, TCSANOW, &options);
  50. tcflush(fd, TCIOFLUSH);
  51. return 0;
  52. }
  53. - (NSInteger)hasData {
  54. struct pollfd fds;
  55. fds.fd = fd;
  56. fds.events = (POLLIN | POLLPRI); // Data may be read
  57. if (poll(&fds, 1, 0) > 0) {
  58. return 1;
  59. } else {
  60. return 0;
  61. }
  62. }
  63. - (void)main {
  64. NSLog(@"Connection running...\n");
  65. running = YES;
  66. while (running) {
  67. }
  68. close(fd);
  69. NSLog(@"Connection closed...\n");
  70. fd = -1;
  71. }
  72. @end