serial.pl 6.7 KB

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