serial.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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, $BAUD, $DBITS, $SBITS, $PARITY, $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. 'PLEX' => '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. } elsif (basename($0) =~ /HDMI/i) {
  175. $DEV = 'HDMI';
  176. $PORT = '/dev/tty.usbserial-AL0096TO';
  177. $BLUETOOTH = 0;
  178. $BAUD = 19200;
  179. $CRLF = "\r";
  180. $DELIMITER = "\r";
  181. %CMDS = (
  182. 'INIT' => '',
  183. 'PLEX' => 'sw i01',
  184. 'GAME' => 'sw i02',
  185. 'IN_3' => 'sw i03',
  186. 'IN_4' => 'sw i04',
  187. 'IN_NEXT' => 'sw +',
  188. 'IN_PREV' => 'sw -',
  189. 'POD_ON' => 'pod on',
  190. 'POD_OFF' => 'pod off',
  191. );
  192. %STATUS_CMDS = ();
  193. } else {
  194. die("No device specified\n");
  195. }
  196. # App config
  197. my $DATA_DIR = DMX::dataDir();
  198. my $CMD_FILE = uc($DEV);
  199. my $BT_CHECK = $ENV{'HOME'} . '/bin/btcheck';
  200. my $BYTE_TIMEOUT = 50;
  201. my $SILENCE_TIMEOUT = $BYTE_TIMEOUT * 10;
  202. # Debug
  203. my $DEBUG = 0;
  204. if ($ENV{'DEBUG'}) {
  205. $DEBUG = $ENV{'DEBUG'};
  206. print STDERR "Debug enabled\n";
  207. }
  208. # Command-line arguments
  209. my ($DELAY) = @ARGV;
  210. if (!$DELAY) {
  211. $DELAY = 1;
  212. }
  213. # Sanity check
  214. if (!-r $PORT) {
  215. die('Serial port not available: ' . $PORT . "\n");
  216. } elsif (!-d $DATA_DIR) {
  217. die('Data directory not available: ' . $DATA_DIR . "\n");
  218. }
  219. # Wait for the serial port to become available
  220. if ($BLUETOOTH) {
  221. system($BT_CHECK, $DEV);
  222. if ($? != 0) {
  223. sleep($DELAY);
  224. die('Bluetooth device "' . $DEV . "\" not available\n");
  225. }
  226. }
  227. # Socket init
  228. my $select = DMX::selectSock($CMD_FILE);
  229. # Port init
  230. my $port = new Device::SerialPort($PORT)
  231. or die('Unable to open serial connection: ' . $PORT . ": ${!}\n");
  232. if ($BAUD) {
  233. $port->baudrate($BAUD);
  234. }
  235. if ($DBITS) {
  236. $port->databits($DBITS);
  237. }
  238. if ($SBITS) {
  239. $port->stopbits($SBITS);
  240. }
  241. if ($PARITY) {
  242. $port->parity($PARITY);
  243. }
  244. $port->read_const_time($BYTE_TIMEOUT);
  245. # Init (clear any previous state)
  246. sendQuery($port, $CMDS{'INIT'});
  247. # State
  248. my $lastStatus = 0;
  249. my %STATUS = ();
  250. foreach my $cmd (keys(%STATUS_CMDS)) {
  251. my %tmp = ('status' => 0, 'last' => '');
  252. $tmp{'path'} = $DATA_DIR . uc($DEV);
  253. if ($cmd ne 'STATUS') {
  254. $tmp{'path'} .= '_' . uc($cmd);
  255. }
  256. if (-r $tmp{'path'}) {
  257. unlink($tmp{'path'});
  258. }
  259. $STATUS{$cmd} = \%tmp;
  260. }
  261. # Loop forever
  262. while (1) {
  263. # Calculate our next timeout
  264. # Hold on select() but not more than $DELAY after our last update
  265. my $timeout = ($lastStatus + $DELAY) - time();
  266. if ($timeout < 0) {
  267. $timeout = 0;
  268. }
  269. if ($DEBUG > 1) {
  270. print STDERR 'Waiting for commands with timeout: ' . $timeout . "\n";
  271. }
  272. # Check for queued commands
  273. my @ready_clients = $select->can_read($timeout);
  274. foreach my $fh (@ready_clients) {
  275. # Ensure we won't block on recv()
  276. $fh->blocking(0);
  277. # Grab the inbound text
  278. while (defined($fh->recv(my $text, DMX::maxCmdLen()))) {
  279. # Clean the input data
  280. $text =~ s/^\s+//;
  281. $text =~ s/\s+$//;
  282. if ($DEBUG) {
  283. print STDERR 'Got command: ' . $text . "\n";
  284. }
  285. # Only accept valid commands
  286. my $cmd = undef();
  287. foreach my $name (keys(%CMDS)) {
  288. if ($name eq $text) {
  289. $cmd = $name;
  290. last;
  291. }
  292. }
  293. # Send commands to serial device
  294. if ($cmd) {
  295. if ($DEBUG) {
  296. print STDERR 'Sending command: ' . $cmd . "\n";
  297. }
  298. my $result = sendQuery($port, $CMDS{$cmd});
  299. if ($DEBUG && $result) {
  300. print STDERR "\tGot result: " . $result . "\n";
  301. }
  302. }
  303. }
  304. }
  305. # Read periodic data, but not too frequently
  306. if (time() > $lastStatus + $DELAY) {
  307. # Record the last status update time
  308. $lastStatus = time();
  309. foreach my $cmd (keys(%STATUS_CMDS)) {
  310. # Save the previous status
  311. $STATUS{$cmd}->{'last'} = $STATUS{$cmd}->{'status'};
  312. # Less typing
  313. my $scmd = $STATUS_CMDS{$cmd};
  314. # Query
  315. if (!defined($CMDS{$cmd})) {
  316. die('No such command: ' . $cmd . "\n");
  317. }
  318. my $result = sendQuery($port, $CMDS{$cmd});
  319. # On read error wait a short while for the device to recover
  320. if (!defined($result) || $result eq '' || !($result =~ /[[:print:]]/)) {
  321. print STDERR 'Read error. Delaying ' . (4 * $DELAY) . " seconds\n";
  322. sleep(4 * $DELAY);
  323. next;
  324. }
  325. # Process the (non-empty) result as requested
  326. if ($scmd->{'MATCH'}) {
  327. if ($result =~ $scmd->{'MATCH'}[0]) {
  328. if ($result =~ $scmd->{'MATCH'}[1]) {
  329. $STATUS{$cmd}->{'status'} = 1;
  330. } else {
  331. $STATUS{$cmd}->{'status'} = 0;
  332. }
  333. }
  334. } elsif ($scmd->{'REPLACE'}) {
  335. if ($result =~ $scmd->{'REPLACE'}) {
  336. $STATUS{$cmd}->{'status'} = $result;
  337. $STATUS{$cmd}->{'status'} =~ s/$scmd->{'REPLACE'}/$1/;
  338. }
  339. } elsif ($scmd->{'EVAL'}) {
  340. my $a = $result;
  341. if ($result =~ $scmd->{'EVAL'}[0]) {
  342. eval($scmd->{'EVAL'}[1]);
  343. $STATUS{$cmd}->{'status'} = $a;
  344. }
  345. } else {
  346. die('Invalid status match type "' . (keys(%{$scmd}))[0] . '" in command: ' . $cmd . "\n");
  347. }
  348. # Ensure the data is clean
  349. $STATUS{$cmd}->{'status'} =~ s/[^\w\.\-]/_/g;
  350. # If something has changed, save the state to disk
  351. # (if the output file does not exist, something has changed)
  352. if ($STATUS{$cmd}->{'status'} ne $STATUS{$cmd}->{'last'} || !-r $STATUS{$cmd}->{'path'}) {
  353. if ($DEBUG) {
  354. print STDERR 'New ' . uc($DEV) . ' status: ' . $cmd . ' => ' . $STATUS{$cmd}->{'status'} . "\n";
  355. }
  356. my ($fh, $tmp) = tempfile($STATUS{$cmd}->{'path'} . '.XXXXXXXX', 'UNLINK' => 0);
  357. print $fh $STATUS{$cmd}->{'status'} . "\n";
  358. close($fh);
  359. rename($tmp, $STATUS{$cmd}->{'path'});
  360. }
  361. }
  362. }
  363. }
  364. # Cleanup
  365. undef($select);
  366. $port->close();
  367. undef($port);
  368. exit(0);
  369. sub sendQuery($$) {
  370. my ($port, $query) = @_;
  371. # Enforce an inter-command delay
  372. usleep($SILENCE_TIMEOUT);
  373. # Read until the queue is clear (i.e. no data available)
  374. # Since we don't have flow control this always causes one read timeout
  375. $port->lookclear();
  376. clearBuffer($port);
  377. # Send the command
  378. my $bytes = $port->write($query . $CRLF);
  379. if ($DEBUG) {
  380. print STDERR "\tWrote (" . $bytes . '): ' . $query . "\n";
  381. }
  382. # Wait for a reply (delimited or timeout)
  383. return collectUntil($port, $DELIMITER);
  384. }
  385. sub clearBuffer($) {
  386. my ($port) = @_;
  387. my $byte = 1;
  388. while (length($byte) > 0) {
  389. $byte = $port->read(1);
  390. if ($DEBUG && length($byte)) {
  391. print STDERR "\tIgnored: " . $byte . "\n";
  392. }
  393. }
  394. }
  395. sub collectUntil($$) {
  396. my ($port, $delim) = @_;
  397. my $char = substr($delim, 0, 1);
  398. # This byte-by-byte reading is not efficient, but it's safe
  399. # Allow reading forever as long as we don't exceed the silence timeout
  400. my $count = 0;
  401. my $string = '';
  402. my $end = undef();
  403. while ($count < $SILENCE_TIMEOUT / $BYTE_TIMEOUT) {
  404. my $byte = $port->read(1);
  405. if (length($byte)) {
  406. $count = 0;
  407. $string .= $byte;
  408. if ($DEBUG > 1) {
  409. print STDERR "\tRead: " . $byte . "\n";
  410. }
  411. if (defined($end)) {
  412. $end .= $byte;
  413. if ($end eq $delim) {
  414. last;
  415. } elsif ($end ne substr($delim, 0, length($end))) {
  416. undef($end);
  417. }
  418. } elsif ($byte eq $char) {
  419. if (length($delim) == 1) {
  420. last;
  421. } else {
  422. $end = $byte;
  423. }
  424. }
  425. } else {
  426. $count++;
  427. }
  428. }
  429. # Return undef if there was no data (as opposed to just a delimiter and/or whitespace)
  430. if (length($string) < 1) {
  431. if ($DEBUG) {
  432. print STDERR "Read: <NO DATA>\n";
  433. }
  434. return undef();
  435. }
  436. # Translate CRLF and CR to LF
  437. $string =~ s/\r\n/\n/g;
  438. $string =~ s/\r/\n/g;
  439. # Strip the trailing delimiter
  440. $string =~ s/${char}$//;
  441. # Strip leading or trailing whitespace
  442. $string =~ s/^\s+//;
  443. $string =~ s/\s+$//;
  444. # Return our clean string
  445. if ($DEBUG) {
  446. print STDERR 'Read: ' . $string . "\n";
  447. }
  448. return $string;
  449. }