serial.pl 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. } elsif (basename($0) =~ /TV/i) {
  48. $DEV = 'TV';
  49. $PORT = '/dev/tty.TV-DevB';
  50. $CRLF = "\r";
  51. $DELIMITER = "\r";
  52. %CMDS = (
  53. 'INIT' => 'RSPW1',
  54. 'ON' => 'POWR1',
  55. 'OFF' => 'POWR0',
  56. 'STATUS' => 'POWR?',
  57. 'VOL+' => 'MVUP',
  58. 'VOL-' => 'MVDOWN',
  59. 'MUTE' => 'MUTE1',
  60. 'UNMUTE' => 'MUTE2',
  61. 'TV' => 'IAVD0',
  62. 'PLEX' => 'IAVD7',
  63. 'VOL_CHECK' => 'VOLM?',
  64. 'VOL6' => 'VOLM6',
  65. 'VOL12' => 'VOLM12',
  66. 'VOL24' => 'VOLM24',
  67. 'VOL+' => 'VOLM',
  68. 'VOL-' => 'VOLM'
  69. );
  70. $STATUS_ON = '1';
  71. } else {
  72. die("No device specified\n");
  73. }
  74. # App config
  75. my $DELAY_STATUS = 5;
  76. my $BYTE_TIMEOUT = 50;
  77. my $SILENCE_TIMEOUT = $BYTE_TIMEOUT * 10;
  78. my $MAX_CMD_LEN = 1024;
  79. my $TEMP_DIR = `getconf DARWIN_USER_TEMP_DIR`;
  80. chomp($TEMP_DIR);
  81. my $DATA_DIR = $TEMP_DIR . 'plexMonitor/';
  82. my $CMD_FILE = $DATA_DIR . $DEV . '.socket';
  83. # Debug
  84. my $DEBUG = 0;
  85. if ($ENV{'DEBUG'}) {
  86. $DEBUG = 1;
  87. }
  88. # Command-line arguments
  89. my ($DELAY) = @ARGV;
  90. if (!$DELAY) {
  91. $DELAY = 15;
  92. }
  93. # Sanity check
  94. if (!-r $PORT || !-d $DATA_DIR) {
  95. die("Bad config\n");
  96. }
  97. # Socket init
  98. if (-e $CMD_FILE) {
  99. unlink($CMD_FILE);
  100. }
  101. my $sock = IO::Socket::UNIX->new(
  102. 'Local' => $CMD_FILE,
  103. 'Type' => SOCK_DGRAM
  104. ) or die('Unable to open socket: ' . $CMD_FILE . ": ${@}\n");
  105. if (!-S $CMD_FILE) {
  106. die('Failed to create socket: ' . $CMD_FILE . "\n");
  107. }
  108. my $select = IO::Select->new($sock)
  109. or die('Unable to select socket: ' . $CMD_FILE . ": ${!}\n");
  110. # Port init
  111. my $port = new Device::SerialPort($PORT)
  112. or die('Unable to open serial connection: ' . $PORT . ": ${!}\n");
  113. $port->read_const_time($BYTE_TIMEOUT);
  114. # Init (clear any previous state)
  115. sendQuery($port, $CMDS{'INIT'});
  116. # Track the power state
  117. # Check for new commands
  118. my $power = -1;
  119. my $powerLast = $power;
  120. my $lastStatus = 0;
  121. while (1) {
  122. # Calculate our next timeout
  123. # Hold on select() but not more than $DELAY_STATUS after our last update
  124. # Plus 1 because we aren't using hi-res time
  125. my $timeout = ($lastStatus + $DELAY_STATUS + 1) - time();
  126. if ($timeout < 1) {
  127. $timeout = 0;
  128. }
  129. if ($DEBUG) {
  130. print STDERR 'Waiting for commands with timeout: ' . $timeout . "\n";
  131. }
  132. # Check for queued commands
  133. my @ready_clients = $select->can_read($timeout);
  134. foreach my $fh (@ready_clients) {
  135. # Grab the inbound text
  136. my $text = undef();
  137. $fh->recv($text, $MAX_CMD_LEN);
  138. $text =~ s/^\s+//;
  139. $text =~ s/\s+$//;
  140. if ($DEBUG) {
  141. print STDERR 'Got command: ' . $text . "\n";
  142. }
  143. # Only accept valid commands
  144. my $cmd = undef();
  145. foreach my $name (keys(%CMDS)) {
  146. if ($name eq $text) {
  147. $cmd = $name;
  148. last;
  149. }
  150. }
  151. # Send command to serial device
  152. if ($cmd) {
  153. if ($DEBUG) {
  154. print STDERR 'Sending command: ' . $cmd . "\n";
  155. }
  156. my $result = sendQuery($port, $CMDS{$cmd});
  157. if ($DEBUG && $result) {
  158. print STDERR "\tGot result: " . $result . "\n";
  159. }
  160. }
  161. }
  162. # Check the power state, but not too frequently
  163. if (time() > $lastStatus + $DELAY_STATUS) {
  164. $lastStatus = time();
  165. $powerLast = $power;
  166. $power = 0;
  167. my $result = sendQuery($port, $CMDS{'STATUS'});
  168. if ($result && $result eq $STATUS_ON) {
  169. $power = 1;
  170. }
  171. # If something has changed, save the state to disk
  172. if ($powerLast != $power) {
  173. if ($DEBUG) {
  174. print STDERR 'New ' . $DEV . ' power state: ' . $power . "\n";
  175. }
  176. my ($fh, $tmp) = tempfile($DATA_DIR . $DEV . '.XXXXXXXX', 'UNLINK' => 0);
  177. print $fh $power . "\n";
  178. close($fh);
  179. rename($tmp, $DATA_DIR . $DEV);
  180. }
  181. }
  182. }
  183. # Cleanup
  184. undef($select);
  185. close($sock);
  186. undef($sock);
  187. $port->close();
  188. undef($port);
  189. exit(0);
  190. sub sendQuery($$) {
  191. my ($port, $query) = @_;
  192. # Read until the queue is clear (i.e. no data available)
  193. # Since we don't have flow control this always causes one read timeout
  194. $port->lookclear();
  195. clearBuffer($port);
  196. # Send the command
  197. my $bytes = $port->write($query . $CRLF);
  198. if ($DEBUG) {
  199. print STDERR "\tWrote (" . $bytes . '): ' . $query . "\n";
  200. }
  201. # Wait for a reply (delimited or timeout)
  202. return collectUntil($port, $DELIMITER);
  203. }
  204. sub clearBuffer($) {
  205. my ($port) = @_;
  206. my $byte = 1;
  207. while (length($byte) > 0) {
  208. $byte = $port->read(1);
  209. if ($DEBUG && length($byte)) {
  210. print STDERR "\tIgnored: " . $byte . "\n";
  211. }
  212. }
  213. }
  214. sub collectUntil($$) {
  215. my ($port, $char) = @_;
  216. if (length($char) != 1) {
  217. die('Invalid collection delimiter: ' . $char . "\n");
  218. }
  219. # This byte-by-byte reading is not efficient, but it's safe
  220. # Allow reading forever as long as we don't exceed the silence timeout
  221. my $count = 0;
  222. my $string = '';
  223. while ($count < $SILENCE_TIMEOUT / $BYTE_TIMEOUT) {
  224. my $byte = $port->read(1);
  225. if (length($byte)) {
  226. $count = 0;
  227. $string .= $byte;
  228. if ($DEBUG) {
  229. print STDERR "\tRead: " . $byte . "\n";
  230. }
  231. if ($byte eq $char) {
  232. last;
  233. }
  234. } else {
  235. $count++;
  236. }
  237. }
  238. # Return undef if there was no data (as opposed to just a delimiter and/or whitespace)
  239. if (length($string) < 1) {
  240. if ($DEBUG) {
  241. print STDERR "Read: <NO DATA>\n";
  242. }
  243. return undef();
  244. }
  245. # Translate CRLF and CR to LF
  246. $string =~ s/\r\n/\n/g;
  247. $string =~ s/\r/\n/g;
  248. # Strip the trailing delimiter
  249. $string =~ s/${char}$//;
  250. # Strip leading or trailing whitespace
  251. $string =~ s/^\s+//;
  252. $string =~ s/\s+$//;
  253. # Return our clean string
  254. if ($DEBUG) {
  255. print STDERR 'Read: ' . $string . "\n";
  256. }
  257. return $string;
  258. }