serial.pl 6.7 KB

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