serial.pl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. 'DYNAMIC' => 'CMODE 06',
  34. 'LIVING_ROOM' => 'CMODE 0C',
  35. 'NATURAL' => 'CMODE 07',
  36. 'THEATER' => 'CMODE 05',
  37. 'THEATER_BLACK_1' => 'CMODE 09',
  38. 'THEATER_BLACK_2' => 'CMODE 0A',
  39. 'XV' => 'CMODE 0B',
  40. 'COLOR' => 'CMODE?',
  41. 'HDMI_1' => 'SOURCE 30',
  42. 'HDMI_2' => 'SOURCE A0',
  43. 'VGA' => 'SOURCE 20',
  44. 'INPUT' => 'SOURCE?',
  45. 'LAMP' => 'LAMP?',
  46. );
  47. %STATUS_CMDS = (
  48. 'STATUS' => { 'MATCH' => [ qr/^PWR=/, qr/PWR=01/ ] },
  49. 'COLOR' => { 'EVAL' => [ qr/^CMODE=[0-9A-Z]{2}$/i, 'if ($a =~ /06$/i) { $a = "DYNAMIC" } elsif ($a =~ /0C$/i) { $a = "LIVING_ROOM" } elsif ($a =~ /07$/i) { $a = "NATURAL" } elsif ($a =~ /05$/i) { $a = "THEATER" } elsif ($a =~ /09$/i) { $a = "THEATER_BLACK_1" } elsif ($a =~ /0A$/i) { $a = "THEATER_BLACK_2" } elsif ($a =~ /0B$/i) { $a = "XV" }' ] },
  50. 'INPUT' => { 'EVAL' => [ qr/^SOURCE=[0-9A-Z]{2}$/i, 'if ($a =~ /30$/i) { $a = "HDMI_1" } elsif ($a =~ /A0$/i) { $a = "HDMI_2" } elsif ($a =~ /20$/i) { $a = "VGA" }' ] },
  51. 'LAMP' => { 'REPLACE' => qr/^LAMP=(\d+)$/i },
  52. );
  53. } elsif (basename($0) =~ /AMPLIFIER/i) {
  54. $DEV = 'Amplifier';
  55. $PORT = '/dev/tty.usbserial-AM01C96Q';
  56. $BLUETOOTH = 0;
  57. $CRLF = "\r";
  58. $DELIMITER = "\r";
  59. %CMDS = (
  60. 'INIT' => '',
  61. 'ON' => 'PWON',
  62. 'OFF' => 'PWSTANDBY',
  63. 'STATUS' => 'PW?',
  64. 'VOL' => 'MV?',
  65. 'VOL+' => 'MVUP',
  66. 'VOL-' => 'MVDOWN',
  67. 'MUTE' => 'MUON',
  68. 'UNMUTE' => 'MUOFF',
  69. 'INPUT' => 'SI?',
  70. 'TV' => 'SITV',
  71. 'GAME' => 'SIDVD',
  72. 'MODE' => 'MS?',
  73. 'SURROUND' => 'MSDOLBY DIGITAL',
  74. 'STEREO' => 'MS7CH STEREO',
  75. 'INPUT' => 'SI?',
  76. 'INPUT_MODE' => 'SD?',
  77. 'INPUT_AUTO' => 'SDAUTO',
  78. 'INPUT_ANALOG' => 'SDANALOG',
  79. 'INPUT_EXT' => 'SDEXT.IN-1',
  80. );
  81. %STATUS_CMDS = (
  82. 'STATUS' => { 'MATCH' => [ qr/^PW/, qr/$CMDS{'ON'}/ ] },
  83. 'MODE' => { 'EVAL' => [ qr/^MS/, 'if ($a =~ /STEREO/i) { $a = "STEREO" } elsif ($a =~ /MS(?:DOLBY|DTS)/i) { $a = "SURROUND" }' ] },
  84. 'VOL' => { 'EVAL' => [ qr/^MV/, '$a =~ s/^MV//; if (length($a) > 2) { $a =~ s/(\d\d)(\d)/$1.$2/ }' ] },
  85. 'INPUT' => { 'EVAL' => [ qr/^SI/, 'my $done = 0; foreach my $cmd (keys(%CMDS)) { if ($a eq $CMDS{$cmd}) { $a = $cmd; $done = 1; last; } } if (!$done) { $a =~ s/^SI/UNKNOWN-/; }' ] },
  86. );
  87. } elsif (basename($0) =~ /TV/i) {
  88. $DEV = 'TV';
  89. $PORT = '/dev/tty.usbserial-A501JRBK';
  90. $BLUETOOTH = 0;
  91. $CRLF = "\r";
  92. $DELIMITER = "\r";
  93. %CMDS = (
  94. 'INIT' => 'RSPW1 ',
  95. 'ON' => 'POWR1 ',
  96. 'OFF' => 'POWR0 ',
  97. 'STATUS' => 'POWR? ',
  98. 'MUTE' => 'MUTE1 ',
  99. 'UNMUTE' => 'MUTE2 ',
  100. 'INPUT' => 'IAVD? ',
  101. 'TV' => 'ITVD0 ',
  102. 'PLEX' => 'IAVD7 ',
  103. 'VOL' => 'VOLM? ',
  104. 'CH+' => 'CHUP1 ',
  105. 'CH-' => 'CHDW1 ',
  106. 'CC' => 'CLCP1 ',
  107. 'VOL0' => 'VOLM0 ',
  108. 'VOL1' => 'VOLM1 ',
  109. 'VOL2' => 'VOLM2 ',
  110. 'VOL3' => 'VOLM3 ',
  111. 'VOL4' => 'VOLM4 ',
  112. 'VOL5' => 'VOLM5 ',
  113. 'VOL6' => 'VOLM6 ',
  114. 'VOL7' => 'VOLM7 ',
  115. 'VOL8' => 'VOLM8 ',
  116. 'VOL9' => 'VOLM9 ',
  117. 'VOL10' => 'VOLM10 ',
  118. 'VOL11' => 'VOLM11 ',
  119. 'VOL12' => 'VOLM12 ',
  120. 'VOL13' => 'VOLM13 ',
  121. 'VOL14' => 'VOLM14 ',
  122. 'VOL15' => 'VOLM15 ',
  123. 'VOL16' => 'VOLM16 ',
  124. 'VOL17' => 'VOLM17 ',
  125. 'VOL18' => 'VOLM18 ',
  126. 'VOL19' => 'VOLM19 ',
  127. 'VOL20' => 'VOLM20 ',
  128. 'VOL21' => 'VOLM21 ',
  129. 'VOL22' => 'VOLM22 ',
  130. 'VOL23' => 'VOLM23 ',
  131. 'VOL24' => 'VOLM24 ',
  132. 'VOL25' => 'VOLM25 ',
  133. 'VOL26' => 'VOLM26 ',
  134. 'VOL27' => 'VOLM27 ',
  135. 'VOL28' => 'VOLM28 ',
  136. 'VOL29' => 'VOLM29 ',
  137. 'VOL30' => 'VOLM30 ',
  138. 'VOL31' => 'VOLM31 ',
  139. 'VOL32' => 'VOLM32 ',
  140. 'VOL33' => 'VOLM33 ',
  141. 'VOL34' => 'VOLM34 ',
  142. 'VOL35' => 'VOLM35 ',
  143. 'VOL36' => 'VOLM36 ',
  144. 'VOL37' => 'VOLM37 ',
  145. 'VOL38' => 'VOLM38 ',
  146. 'VOL39' => 'VOLM39 ',
  147. 'VOL40' => 'VOLM40 ',
  148. 'VOL41' => 'VOLM41 ',
  149. 'VOL42' => 'VOLM42 ',
  150. 'VOL43' => 'VOLM43 ',
  151. 'VOL44' => 'VOLM44 ',
  152. 'VOL45' => 'VOLM45 ',
  153. 'VOL46' => 'VOLM46 ',
  154. 'VOL47' => 'VOLM47 ',
  155. 'VOL48' => 'VOLM48 ',
  156. 'VOL49' => 'VOLM49 ',
  157. 'VOL50' => 'VOLM50 ',
  158. 'VOL51' => 'VOLM51 ',
  159. 'VOL52' => 'VOLM52 ',
  160. 'VOL53' => 'VOLM53 ',
  161. 'VOL54' => 'VOLM54 ',
  162. 'VOL55' => 'VOLM55 ',
  163. 'VOL56' => 'VOLM56 ',
  164. 'VOL57' => 'VOLM57 ',
  165. 'VOL58' => 'VOLM58 ',
  166. 'VOL59' => 'VOLM59 ',
  167. 'VOL60' => 'VOLM60 ',
  168. );
  169. %STATUS_CMDS = (
  170. 'STATUS' => { 'MATCH' => [ qr/\d/, qr/1/ ] },
  171. 'VOL' => { 'EVAL' => [ qr/\d/, '' ] },
  172. 'INPUT' => { 'EVAL' => [ qr/(\d|ERR)/, 'if ($a =~ /7/i) { $a = "PLEX" } elsif ($a =~ /\d/i) { $a = "OTHER" } else { $a = "TV" }' ] },
  173. );
  174. } else {
  175. die("No device specified\n");
  176. }
  177. # App config
  178. my $DATA_DIR = DMX::dataDir();
  179. my $CMD_FILE = uc($DEV);
  180. my $BT_CHECK = $ENV{'HOME'} . '/bin/btcheck';
  181. my $BYTE_TIMEOUT = 50;
  182. my $SILENCE_TIMEOUT = $BYTE_TIMEOUT * 10;
  183. # Debug
  184. my $DEBUG = 0;
  185. if ($ENV{'DEBUG'}) {
  186. $DEBUG = $ENV{'DEBUG'};
  187. print STDERR "Debug enabled\n";
  188. }
  189. # Command-line arguments
  190. my ($DELAY) = @ARGV;
  191. if (!$DELAY) {
  192. $DELAY = 1;
  193. }
  194. # Sanity check
  195. if (!-r $PORT) {
  196. die('Serial port not available: ' . $PORT . "\n");
  197. } elsif (!-d $DATA_DIR) {
  198. die('Data directory not available: ' . $DATA_DIR . "\n");
  199. }
  200. # Wait for the serial port to become available
  201. if ($BLUETOOTH) {
  202. system($BT_CHECK, $DEV);
  203. if ($? != 0) {
  204. sleep($DELAY);
  205. die('Bluetooth device "' . $DEV . "\" not available\n");
  206. }
  207. }
  208. # Socket init
  209. my $select = DMX::selectSock($CMD_FILE);
  210. # Port init
  211. my $port = new Device::SerialPort($PORT)
  212. or die('Unable to open serial connection: ' . $PORT . ": ${!}\n");
  213. $port->read_const_time($BYTE_TIMEOUT);
  214. # Init (clear any previous state)
  215. sendQuery($port, $CMDS{'INIT'});
  216. # State
  217. my $lastStatus = 0;
  218. my %STATUS = ();
  219. foreach my $cmd (keys(%STATUS_CMDS)) {
  220. my %tmp = ('status' => 0, 'last' => '');
  221. $tmp{'path'} = $DATA_DIR . uc($DEV);
  222. if ($cmd ne 'STATUS') {
  223. $tmp{'path'} .= '_' . uc($cmd);
  224. }
  225. if (-r $tmp{'path'}) {
  226. unlink($tmp{'path'});
  227. }
  228. $STATUS{$cmd} = \%tmp;
  229. }
  230. # Loop forever
  231. while (1) {
  232. # Calculate our next timeout
  233. # Hold on select() but not more than $DELAY after our last update
  234. my $timeout = ($lastStatus + $DELAY) - time();
  235. if ($timeout < 0) {
  236. $timeout = 0;
  237. }
  238. if ($DEBUG > 1) {
  239. print STDERR 'Waiting for commands with timeout: ' . $timeout . "\n";
  240. }
  241. # Check for queued commands
  242. my @ready_clients = $select->can_read($timeout);
  243. foreach my $fh (@ready_clients) {
  244. # Ensure we won't block on recv()
  245. $fh->blocking(0);
  246. # Grab the inbound text
  247. while (defined($fh->recv(my $text, DMX::maxCmdLen()))) {
  248. # Clean the input data
  249. $text =~ s/^\s+//;
  250. $text =~ s/\s+$//;
  251. if ($DEBUG) {
  252. print STDERR 'Got command: ' . $text . "\n";
  253. }
  254. # Only accept valid commands
  255. my $cmd = undef();
  256. foreach my $name (keys(%CMDS)) {
  257. if ($name eq $text) {
  258. $cmd = $name;
  259. last;
  260. }
  261. }
  262. # Send commands to serial device
  263. if ($cmd) {
  264. if ($DEBUG) {
  265. print STDERR 'Sending command: ' . $cmd . "\n";
  266. }
  267. my $result = sendQuery($port, $CMDS{$cmd});
  268. if ($DEBUG && $result) {
  269. print STDERR "\tGot result: " . $result . "\n";
  270. }
  271. }
  272. }
  273. }
  274. # Read periodic data, but not too frequently
  275. if (time() > $lastStatus + $DELAY) {
  276. # Record the last status update time
  277. $lastStatus = time();
  278. foreach my $cmd (keys(%STATUS_CMDS)) {
  279. # Save the previous status
  280. $STATUS{$cmd}->{'last'} = $STATUS{$cmd}->{'status'};
  281. # Less typing
  282. my $scmd = $STATUS_CMDS{$cmd};
  283. # Query
  284. if (!defined($CMDS{$cmd})) {
  285. die('No such command: ' . $cmd . "\n");
  286. }
  287. my $result = sendQuery($port, $CMDS{$cmd});
  288. # On read error wait a short while for the device to recover
  289. if (!defined($result) || $result eq '' || !($result =~ /[[:print:]]/)) {
  290. print STDERR 'Read error. Delaying ' . (4 * $DELAY) . " seconds\n";
  291. sleep(4 * $DELAY);
  292. next;
  293. }
  294. # Process the (non-empty) result as requested
  295. if ($scmd->{'MATCH'}) {
  296. if ($result =~ $scmd->{'MATCH'}[0]) {
  297. if ($result =~ $scmd->{'MATCH'}[1]) {
  298. $STATUS{$cmd}->{'status'} = 1;
  299. } else {
  300. $STATUS{$cmd}->{'status'} = 0;
  301. }
  302. }
  303. } elsif ($scmd->{'REPLACE'}) {
  304. if ($result =~ $scmd->{'REPLACE'}) {
  305. $STATUS{$cmd}->{'status'} = $result;
  306. $STATUS{$cmd}->{'status'} =~ s/$scmd->{'REPLACE'}/$1/;
  307. }
  308. } elsif ($scmd->{'EVAL'}) {
  309. my $a = $result;
  310. if ($result =~ $scmd->{'EVAL'}[0]) {
  311. eval($scmd->{'EVAL'}[1]);
  312. $STATUS{$cmd}->{'status'} = $a;
  313. }
  314. } else {
  315. die('Invalid status match type "' . (keys(%{$scmd}))[0] . '" in command: ' . $cmd . "\n");
  316. }
  317. # Ensure the data is clean
  318. $STATUS{$cmd}->{'status'} =~ s/[^\w\.\-]/_/g;
  319. # If something has changed, save the state to disk
  320. # (if the output file does not exist, something has changed)
  321. if ($STATUS{$cmd}->{'status'} ne $STATUS{$cmd}->{'last'} || !-r $STATUS{$cmd}->{'path'}) {
  322. if ($DEBUG) {
  323. print STDERR 'New ' . uc($DEV) . ' status: ' . $cmd . ' => ' . $STATUS{$cmd}->{'status'} . "\n";
  324. }
  325. my ($fh, $tmp) = tempfile($STATUS{$cmd}->{'path'} . '.XXXXXXXX', 'UNLINK' => 0);
  326. print $fh $STATUS{$cmd}->{'status'} . "\n";
  327. close($fh);
  328. rename($tmp, $STATUS{$cmd}->{'path'});
  329. }
  330. }
  331. }
  332. }
  333. # Cleanup
  334. undef($select);
  335. $port->close();
  336. undef($port);
  337. exit(0);
  338. sub sendQuery($$) {
  339. my ($port, $query) = @_;
  340. # Enforce an inter-command delay
  341. usleep($SILENCE_TIMEOUT);
  342. # Read until the queue is clear (i.e. no data available)
  343. # Since we don't have flow control this always causes one read timeout
  344. $port->lookclear();
  345. clearBuffer($port);
  346. # Send the command
  347. my $bytes = $port->write($query . $CRLF);
  348. if ($DEBUG) {
  349. print STDERR "\tWrote (" . $bytes . '): ' . $query . "\n";
  350. }
  351. # Wait for a reply (delimited or timeout)
  352. return collectUntil($port, $DELIMITER);
  353. }
  354. sub clearBuffer($) {
  355. my ($port) = @_;
  356. my $byte = 1;
  357. while (length($byte) > 0) {
  358. $byte = $port->read(1);
  359. if ($DEBUG && length($byte)) {
  360. print STDERR "\tIgnored: " . $byte . "\n";
  361. }
  362. }
  363. }
  364. sub collectUntil($$) {
  365. my ($port, $char) = @_;
  366. if (length($char) != 1) {
  367. die('Invalid collection delimiter: ' . $char . "\n");
  368. }
  369. # This byte-by-byte reading is not efficient, but it's safe
  370. # Allow reading forever as long as we don't exceed the silence timeout
  371. my $count = 0;
  372. my $string = '';
  373. while ($count < $SILENCE_TIMEOUT / $BYTE_TIMEOUT) {
  374. my $byte = $port->read(1);
  375. if (length($byte)) {
  376. $count = 0;
  377. $string .= $byte;
  378. if ($DEBUG > 1) {
  379. print STDERR "\tRead: " . $byte . "\n";
  380. }
  381. if ($byte eq $char) {
  382. last;
  383. }
  384. } else {
  385. $count++;
  386. }
  387. }
  388. # Return undef if there was no data (as opposed to just a delimiter and/or whitespace)
  389. if (length($string) < 1) {
  390. if ($DEBUG) {
  391. print STDERR "Read: <NO DATA>\n";
  392. }
  393. return undef();
  394. }
  395. # Translate CRLF and CR to LF
  396. $string =~ s/\r\n/\n/g;
  397. $string =~ s/\r/\n/g;
  398. # Strip the trailing delimiter
  399. $string =~ s/${char}$//;
  400. # Strip leading or trailing whitespace
  401. $string =~ s/^\s+//;
  402. $string =~ s/\s+$//;
  403. # Return our clean string
  404. if ($DEBUG) {
  405. print STDERR 'Read: ' . $string . "\n";
  406. }
  407. return $string;
  408. }