serial.pl 6.6 KB

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