serial.pl 9.8 KB

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