serial.pl 9.7 KB

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