serial.pl 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. use Time::HiRes qw( usleep sleep time );
  10. use IPC::System::Simple qw( system capture );
  11. # Local modules
  12. use Cwd qw(abs_path);
  13. use File::Basename qw(dirname);
  14. use lib dirname(abs_path($0));
  15. use DMX;
  16. # Prototypes
  17. sub sendQuery($$);
  18. sub clearBuffer($);
  19. sub collectUntil($$);
  20. # Device parameters
  21. my ($DEV, $PORT, $BLUETOOTH, $CRLF, $DELIMITER, %CMDS, %STATUS_CMDS);
  22. if (basename($0) =~ /PROJECTOR/i) {
  23. $DEV = 'Projector';
  24. $PORT = '/dev/tty.usbserial-A5006xbj';
  25. $BLUETOOTH = 0;
  26. $CRLF = "\r\n";
  27. $DELIMITER = ':';
  28. %CMDS = (
  29. 'INIT' => '',
  30. 'ON' => 'PWR ON',
  31. 'OFF' => 'PWR OFF',
  32. 'STATUS' => 'PWR?'
  33. );
  34. %STATUS_CMDS = ('STATUS' => { 'EQUAL' => 'PWR=01' },);
  35. } elsif (basename($0) =~ /AMPLIFIER/i) {
  36. $DEV = 'Amplifier';
  37. $PORT = '/dev/tty.usbserial-A5006x9u';
  38. $BLUETOOTH = 0;
  39. $CRLF = "\r";
  40. $DELIMITER = "\r";
  41. %CMDS = (
  42. 'INIT' => '',
  43. 'ON' => 'PWON',
  44. 'OFF' => 'PWSTANDBY',
  45. 'STATUS' => 'PW?',
  46. 'VOL' => 'MV?',
  47. 'VOL+' => 'MVUP',
  48. 'VOL-' => 'MVDOWN',
  49. 'MUTE' => 'MUON',
  50. 'UNMUTE' => 'MUOFF',
  51. 'INPUT' => 'SI?',
  52. 'TV' => 'SITV',
  53. 'DVD' => 'SIDVD',
  54. 'MODE' => 'MS?',
  55. 'SURROUND' => 'MSDOLBY DIGITAL',
  56. 'STEREO' => 'MS7CH STEREO',
  57. 'TV' => 'SITV',
  58. 'INPUT' => 'SI?',
  59. );
  60. %STATUS_CMDS = (
  61. 'STATUS' => { 'MATCH' => [ qr/^PW/, qr/$CMDS{'ON'}/ ] },
  62. 'MODE' => { 'EVAL' => [ qr/^MS/, 'if ($a =~ /STEREO/i) { $a = "STEREO" } elsif ($a =~ /MS(?:DOLBY|DTS)/i) { $a = "SURROUND" }' ] },
  63. 'VOL' => { 'EVAL' => [ qr/^MV/, '$a =~ s/^MV//; if (length($a) > 2) { $a =~ s/(\d\d)(\d)/$1.$2/ }' ] },
  64. 'INPUT' => { 'REPLACE' => qr/^SI(.*)/ },
  65. );
  66. } elsif (basename($0) =~ /TV/i) {
  67. $DEV = 'TV';
  68. $PORT = '/dev/tty.' . $DEV . '-DevB';
  69. $BLUETOOTH = 1;
  70. $CRLF = "\r";
  71. $DELIMITER = "\r";
  72. %CMDS = (
  73. 'INIT' => 'RSPW1',
  74. 'ON' => 'POWR1',
  75. 'OFF' => 'POWR0',
  76. 'STATUS' => 'POWR?',
  77. 'VOL+' => 'MVUP',
  78. 'VOL-' => 'MVDOWN',
  79. 'MUTE' => 'MUTE1',
  80. 'UNMUTE' => 'MUTE2',
  81. 'TV' => 'IAVD0',
  82. 'PLEX' => 'IAVD7',
  83. 'VOL_CHECK' => 'VOLM?',
  84. 'VOL6' => 'VOLM6',
  85. 'VOL12' => 'VOLM12',
  86. 'VOL24' => 'VOLM24',
  87. 'VOL+' => 'VOLM',
  88. 'VOL-' => 'VOLM'
  89. );
  90. %STATUS_CMDS = ('STATUS' => { 'EQUAL' => '1' },);
  91. } else {
  92. die("No device specified\n");
  93. }
  94. # App config
  95. my $DATA_DIR = DMX::dataDir();
  96. my $CMD_FILE = $DATA_DIR . uc($DEV) . '.socket';
  97. my $BT_CHECK = $ENV{'HOME'} . '/bin/btcheck';
  98. my $DELAY_STATUS = 1;
  99. my $BYTE_TIMEOUT = 50;
  100. my $SILENCE_TIMEOUT = $BYTE_TIMEOUT * 10;
  101. # Debug
  102. my $DEBUG = 0;
  103. if ($ENV{'DEBUG'}) {
  104. $DEBUG = $ENV{'DEBUG'};
  105. print STDERR "Debug enabled\n";
  106. }
  107. # Command-line arguments
  108. my ($DELAY) = @ARGV;
  109. if (!$DELAY) {
  110. $DELAY = 15;
  111. }
  112. # Sanity check
  113. if (!-r $PORT) {
  114. die('Serial port not available: ' . $PORT . "\n");
  115. } elsif (!-d $DATA_DIR) {
  116. die('Data directory not available: ' . $DATA_DIR . "\n");
  117. }
  118. # Wait for the serial port to become available
  119. if ($BLUETOOTH) {
  120. system($BT_CHECK, $DEV);
  121. if ($? != 0) {
  122. sleep($DELAY_STATUS);
  123. die('Bluetooth device "' . $DEV . "\" not available\n");
  124. }
  125. }
  126. # Socket init
  127. my $select = DMX::selectSock($CMD_FILE);
  128. # Port init
  129. my $port = new Device::SerialPort($PORT)
  130. or die('Unable to open serial connection: ' . $PORT . ": ${!}\n");
  131. $port->read_const_time($BYTE_TIMEOUT);
  132. # Init (clear any previous state)
  133. sendQuery($port, $CMDS{'INIT'});
  134. # State
  135. my $lastStatus = 0;
  136. my %STATUS = ();
  137. foreach my $cmd (keys(%STATUS_CMDS)) {
  138. my %tmp = ('status' => 0, 'last' => 0);
  139. $tmp{'path'} = $DATA_DIR . uc($DEV);
  140. if ($cmd ne 'STATUS') {
  141. $tmp{'path'} .= '_' . uc($cmd);
  142. }
  143. $STATUS{$cmd} = \%tmp;
  144. }
  145. # Loop forever
  146. while (1) {
  147. # Calculate our next timeout
  148. # Hold on select() but not more than $DELAY_STATUS after our last update
  149. my $timeout = ($lastStatus + $DELAY_STATUS) - time();
  150. if ($timeout < 0) {
  151. $timeout = 0;
  152. }
  153. if ($DEBUG > 1) {
  154. print STDERR 'Waiting for commands with timeout: ' . $timeout . "\n";
  155. }
  156. # Check for queued commands
  157. my @ready_clients = $select->can_read($timeout);
  158. foreach my $fh (@ready_clients) {
  159. # Ensure we won't block on recv()
  160. $fh->blocking(0);
  161. # Grab the inbound text
  162. while (defined($fh->recv(my $text, DMX::maxCmdLen()))) {
  163. # Clean the input data
  164. $text =~ s/^\s+//;
  165. $text =~ s/\s+$//;
  166. if ($DEBUG) {
  167. print STDERR 'Got command: ' . $text . "\n";
  168. }
  169. # Only accept valid commands
  170. my $cmd = undef();
  171. foreach my $name (keys(%CMDS)) {
  172. if ($name eq $text) {
  173. $cmd = $name;
  174. last;
  175. }
  176. }
  177. # Send commands to serial device
  178. if ($cmd) {
  179. if ($DEBUG) {
  180. print STDERR 'Sending command: ' . $cmd . "\n";
  181. }
  182. my $result = sendQuery($port, $CMDS{$cmd});
  183. if ($DEBUG && $result) {
  184. print STDERR "\tGot result: " . $result . "\n";
  185. }
  186. }
  187. }
  188. }
  189. # Read periodic data, but not too frequently
  190. if (time() > $lastStatus + $DELAY_STATUS) {
  191. # Record the last status update time
  192. $lastStatus = time();
  193. foreach my $cmd (keys(%STATUS_CMDS)) {
  194. # Save the previous status
  195. $STATUS{$cmd}->{'last'} = $STATUS{$cmd}->{'status'};
  196. # Less typing
  197. my $scmd = $STATUS_CMDS{$cmd};
  198. # Query
  199. if (!defined($CMDS{$cmd})) {
  200. die('No such command: ' . $cmd . "\n");
  201. }
  202. my $result = sendQuery($port, $CMDS{$cmd});
  203. # Process the result as requested
  204. if ($result) {
  205. if ($scmd->{'MATCH'}) {
  206. if ($result =~ $scmd->{'MATCH'}[0]) {
  207. if ($result =~ $scmd->{'MATCH'}[1]) {
  208. $STATUS{$cmd}->{'status'} = 1;
  209. } else {
  210. $STATUS{$cmd}->{'status'} = 0;
  211. }
  212. }
  213. } elsif ($scmd->{'REPLACE'}) {
  214. if ($result =~ $scmd->{'REPLACE'}) {
  215. $STATUS{$cmd}->{'status'} = $result;
  216. $STATUS{$cmd}->{'status'} =~ s/$scmd->{'REPLACE'}/$1/;
  217. }
  218. } elsif ($scmd->{'EVAL'}) {
  219. my $a = $result;
  220. if ($result =~ $scmd->{'EVAL'}[0]) {
  221. eval($scmd->{'EVAL'}[1]);
  222. $STATUS{$cmd}->{'status'} = $a;
  223. }
  224. } else {
  225. die('Invalid status match type "' . (keys(%{$scmd}))[0] . '" in command: ' . $cmd . "\n");
  226. }
  227. }
  228. # Ensure the data is clean
  229. $STATUS{$cmd}->{'status'} =~ s/[^\w\.\-]/_/g;
  230. # If something has changed, save the state to disk
  231. if ($STATUS{$cmd}->{'status'} ne $STATUS{$cmd}->{'last'}) {
  232. if ($DEBUG) {
  233. print STDERR 'New ' . uc($DEV) . ' status: ' . $cmd . ' => ' . $STATUS{$cmd}->{'status'} . "\n";
  234. }
  235. my ($fh, $tmp) = tempfile($STATUS{$cmd}->{'path'} . '.XXXXXXXX', 'UNLINK' => 0);
  236. print $fh $STATUS{$cmd}->{'status'} . "\n";
  237. close($fh);
  238. rename($tmp, $STATUS{$cmd}->{'path'});
  239. }
  240. }
  241. }
  242. }
  243. # Cleanup
  244. undef($select);
  245. $port->close();
  246. undef($port);
  247. exit(0);
  248. sub sendQuery($$) {
  249. my ($port, $query) = @_;
  250. # Enforce an inter-command delay
  251. usleep($SILENCE_TIMEOUT);
  252. # Read until the queue is clear (i.e. no data available)
  253. # Since we don't have flow control this always causes one read timeout
  254. $port->lookclear();
  255. clearBuffer($port);
  256. # Send the command
  257. my $bytes = $port->write($query . $CRLF);
  258. if ($DEBUG) {
  259. print STDERR "\tWrote (" . $bytes . '): ' . $query . "\n";
  260. }
  261. # Wait for a reply (delimited or timeout)
  262. return collectUntil($port, $DELIMITER);
  263. }
  264. sub clearBuffer($) {
  265. my ($port) = @_;
  266. my $byte = 1;
  267. while (length($byte) > 0) {
  268. $byte = $port->read(1);
  269. if ($DEBUG && length($byte)) {
  270. print STDERR "\tIgnored: " . $byte . "\n";
  271. }
  272. }
  273. }
  274. sub collectUntil($$) {
  275. my ($port, $char) = @_;
  276. if (length($char) != 1) {
  277. die('Invalid collection delimiter: ' . $char . "\n");
  278. }
  279. # This byte-by-byte reading is not efficient, but it's safe
  280. # Allow reading forever as long as we don't exceed the silence timeout
  281. my $count = 0;
  282. my $string = '';
  283. while ($count < $SILENCE_TIMEOUT / $BYTE_TIMEOUT) {
  284. my $byte = $port->read(1);
  285. if (length($byte)) {
  286. $count = 0;
  287. $string .= $byte;
  288. if ($DEBUG > 1) {
  289. print STDERR "\tRead: " . $byte . "\n";
  290. }
  291. if ($byte eq $char) {
  292. last;
  293. }
  294. } else {
  295. $count++;
  296. }
  297. }
  298. # Return undef if there was no data (as opposed to just a delimiter and/or whitespace)
  299. if (length($string) < 1) {
  300. if ($DEBUG) {
  301. print STDERR "Read: <NO DATA>\n";
  302. }
  303. return undef();
  304. }
  305. # Translate CRLF and CR to LF
  306. $string =~ s/\r\n/\n/g;
  307. $string =~ s/\r/\n/g;
  308. # Strip the trailing delimiter
  309. $string =~ s/${char}$//;
  310. # Strip leading or trailing whitespace
  311. $string =~ s/^\s+//;
  312. $string =~ s/\s+$//;
  313. # Return our clean string
  314. if ($DEBUG) {
  315. print STDERR 'Read: ' . $string . "\n";
  316. }
  317. return $string;
  318. }