serial.pl 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use File::Basename;
  5. use File::Temp qw( tempfile );
  6. use IO::Select;
  7. use IO::Socket::UNIX;
  8. use Device::SerialPort;
  9. # Prototypes
  10. sub sendQuery($$);
  11. sub clearBuffer($);
  12. sub collectUntil($$);
  13. # Device parameters
  14. my ($DEV, $PORT, $CRLF, $DELIMITER, %CMDS, $STATUS_ON);
  15. if (basename($0) =~ /PROJECTOR/i) {
  16. $DEV = 'PROJECTOR';
  17. $PORT = '/dev/tty.Projector-DevB';
  18. $CRLF = "\r\n";
  19. $DELIMITER = ':';
  20. %CMDS = (
  21. 'INIT' => '',
  22. 'ON' => 'PWR ON',
  23. 'OFF' => 'PWR OFF',
  24. 'STATUS' => 'PWR?'
  25. );
  26. $STATUS_ON = 'PWR=01';
  27. } elsif (basename($0) =~ /AMPLIFIER/i) {
  28. $DEV = 'AMPLIFIER';
  29. $PORT = '/dev/tty.Amplifier-DevB';
  30. $CRLF = "\r";
  31. $DELIMITER = "\r";
  32. %CMDS = (
  33. 'INIT' => '',
  34. 'ON' => 'PWON',
  35. 'OFF' => 'PWSTANDBY',
  36. 'STATUS' => 'PW?',
  37. 'VOL+' => 'MVUP',
  38. 'VOL-' => 'MVDOWN',
  39. 'MUTE' => 'MUON',
  40. 'UNMUTE' => 'MUOFF',
  41. 'TV' => 'SITV',
  42. 'DVD' => 'SIDVD',
  43. 'SURROUND' => 'MSDOLBY SURROUND',
  44. 'STEREO' => 'MS7CH STEREO',
  45. );
  46. $STATUS_ON = 'PWON';
  47. } else {
  48. die("No device specified\n");
  49. }
  50. # App config
  51. my $DELAY_STATUS = 5;
  52. my $BYTE_TIMEOUT = 50;
  53. my $SILENCE_TIMEOUT = $BYTE_TIMEOUT * 10;
  54. my $MAX_CMD_LEN = 1024;
  55. my $TEMP_DIR = `getconf DARWIN_USER_TEMP_DIR`;
  56. chomp($TEMP_DIR);
  57. my $DATA_DIR = $TEMP_DIR . 'plexMonitor/';
  58. my $CMD_FILE = $DATA_DIR . $DEV . '.socket';
  59. # Debug
  60. my $DEBUG = 0;
  61. if ($ENV{'DEBUG'}) {
  62. $DEBUG = 1;
  63. }
  64. # Command-line arguments
  65. my ($DELAY) = @ARGV;
  66. if (!$DELAY) {
  67. $DELAY = 15;
  68. }
  69. # Sanity check
  70. if (!-r $PORT || !-d $DATA_DIR) {
  71. die("Bad config\n");
  72. }
  73. # Socket init
  74. if (-e $CMD_FILE) {
  75. unlink($CMD_FILE);
  76. }
  77. my $sock = IO::Socket::UNIX->new(
  78. 'Local' => $CMD_FILE,
  79. 'Type' => SOCK_DGRAM
  80. ) or die('Unable to open socket: ' . $CMD_FILE . ": ${@}\n");
  81. if (!-S $CMD_FILE) {
  82. die('Failed to create socket: ' . $CMD_FILE . "\n");
  83. }
  84. my $select = IO::Select->new($sock)
  85. or die('Unable to select socket: ' . $CMD_FILE . ": ${!}\n");
  86. # Port init
  87. my $port = new Device::SerialPort($PORT)
  88. or die('Unable to open serial connection: ' . $PORT . ": ${!}\n");
  89. $port->read_const_time($BYTE_TIMEOUT);
  90. # Init (clear any previous state)
  91. sendQuery($port, $CMDS{'INIT'});
  92. # Track the power state
  93. # Check for new commands
  94. my $power = -1;
  95. my $powerLast = $power;
  96. my $lastStatus = 0;
  97. while (1) {
  98. # Calculate our next timeout
  99. # Hold on select() but not more than $DELAY_STATUS after our last update
  100. # Plus 1 because we aren't using hi-res time
  101. my $timeout = ($lastStatus + $DELAY_STATUS + 1) - time();
  102. if ($timeout < 1) {
  103. $timeout = 0;
  104. }
  105. if ($DEBUG) {
  106. print STDERR 'Waiting for commands with timeout: ' . $timeout . "\n";
  107. }
  108. # Check for queued commands
  109. my @ready_clients = $select->can_read($timeout);
  110. foreach my $fh (@ready_clients) {
  111. # Grab the inbound text
  112. my $text = undef();
  113. $fh->recv($text, $MAX_CMD_LEN);
  114. $text =~ s/^\s+//;
  115. $text =~ s/\s+$//;
  116. if ($DEBUG) {
  117. print STDERR 'Got command: ' . $text . "\n";
  118. }
  119. # Only accept valid commands
  120. my $cmd = undef();
  121. foreach my $name (keys(%CMDS)) {
  122. if ($name eq $text) {
  123. $cmd = $name;
  124. last;
  125. }
  126. }
  127. # Send command to serial device
  128. if ($cmd) {
  129. if ($DEBUG) {
  130. print STDERR 'Sending command: ' . $cmd . "\n";
  131. }
  132. my $result = sendQuery($port, $CMDS{$cmd});
  133. if ($DEBUG && $result) {
  134. print STDERR "\tGot result: " . $result . "\n";
  135. }
  136. }
  137. }
  138. # Check the power state, but not too frequently
  139. if (time() > $lastStatus + $DELAY_STATUS) {
  140. $lastStatus = time();
  141. $powerLast = $power;
  142. $power = 0;
  143. my $result = sendQuery($port, $CMDS{'STATUS'});
  144. if ($result && $result eq $STATUS_ON) {
  145. $power = 1;
  146. }
  147. # If something has changed, save the state to disk
  148. if ($powerLast != $power) {
  149. if ($DEBUG) {
  150. print STDERR 'New ' . $DEV . ' power state: ' . $power . "\n";
  151. }
  152. my ($fh, $tmp) = tempfile($DATA_DIR . $DEV . '.XXXXXXXX', 'UNLINK' => 0);
  153. print $fh $power . "\n";
  154. close($fh);
  155. rename($tmp, $DATA_DIR . $DEV);
  156. }
  157. }
  158. }
  159. # Cleanup
  160. undef($select);
  161. close($sock);
  162. undef($sock);
  163. $port->close();
  164. undef($port);
  165. exit(0);
  166. sub sendQuery($$) {
  167. my ($port, $query) = @_;
  168. # Read until the queue is clear (i.e. no data available)
  169. # Since we don't have flow control this always causes one read timeout
  170. $port->lookclear();
  171. clearBuffer($port);
  172. # Send the command
  173. my $bytes = $port->write($query . $CRLF);
  174. if ($DEBUG) {
  175. print STDERR "\tWrote (" . $bytes . '): ' . $query . "\n";
  176. }
  177. # Wait for a reply (delimited or timeout)
  178. return collectUntil($port, $DELIMITER);
  179. }
  180. sub clearBuffer($) {
  181. my ($port) = @_;
  182. my $byte = 1;
  183. while (length($byte) > 0) {
  184. $byte = $port->read(1);
  185. if ($DEBUG && length($byte)) {
  186. print STDERR "\tIgnored: " . $byte . "\n";
  187. }
  188. }
  189. }
  190. sub collectUntil($$) {
  191. my ($port, $char) = @_;
  192. if (length($char) != 1) {
  193. die('Invalid collection delimiter: ' . $char . "\n");
  194. }
  195. # This byte-by-byte reading is not efficient, but it's safe
  196. # Allow reading forever as long as we don't exceed the silence timeout
  197. my $count = 0;
  198. my $string = '';
  199. while ($count < $SILENCE_TIMEOUT / $BYTE_TIMEOUT) {
  200. my $byte = $port->read(1);
  201. if (length($byte)) {
  202. $count = 0;
  203. $string .= $byte;
  204. if ($DEBUG) {
  205. print STDERR "\tRead: " . $byte . "\n";
  206. }
  207. if ($byte eq $char) {
  208. last;
  209. }
  210. } else {
  211. $count++;
  212. }
  213. }
  214. # Return undef if there was no data (as opposed to just a delimiter and/or whitespace)
  215. if (length($string) < 1) {
  216. if ($DEBUG) {
  217. print STDERR "Read: <NO DATA>\n";
  218. }
  219. return undef();
  220. }
  221. # Translate CRLF and CR to LF
  222. $string =~ s/\r\n/\n/g;
  223. $string =~ s/\r/\n/g;
  224. # Strip the trailing delimiter
  225. $string =~ s/${char}$//;
  226. # Strip leading or trailing whitespace
  227. $string =~ s/^\s+//;
  228. $string =~ s/\s+$//;
  229. # Return our clean string
  230. if ($DEBUG) {
  231. print STDERR 'Read: ' . $string . "\n";
  232. }
  233. return $string;
  234. }