serial.pl 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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' => { 'EQUAL' => $CMDS{'ON'} },
  62. 'MODE' => { 'EVAL' => 'if ($a =~ /STEREO/i) { $a = "STEREO" } elsif ($a =~ /MS(?:DOLBY|DTS)/i) { $a = "SURROUND" } else { $a = "UNKNOWN" }' },
  63. 'VOL' => { 'EVAL' => '$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. $STATUS{$cmd}->{'status'} = 0;
  197. # Less typing
  198. my $scmd = $STATUS_CMDS{$cmd};
  199. # Query
  200. my $result = sendQuery($port, $CMDS{$cmd});
  201. # Process the result as requested
  202. if ($result) {
  203. if ($scmd->{'EQUAL'}) {
  204. if ($result eq $scmd->{'EQUAL'}) {
  205. $STATUS{$cmd}->{'status'} = 1;
  206. }
  207. } elsif ($scmd->{'MATCH'}) {
  208. if ($result =~ $scmd->{'MATCH'}) {
  209. $STATUS{$cmd}->{'status'} = 1;
  210. }
  211. } elsif ($scmd->{'REPLACE'}) {
  212. $STATUS{$cmd}->{'status'} = $result;
  213. $STATUS{$cmd}->{'status'} =~ s/$scmd->{'REPLACE'}/$1/;
  214. } elsif ($scmd->{'EVAL'}) {
  215. my $a = $result;
  216. eval($scmd->{'EVAL'});
  217. $STATUS{$cmd}->{'status'} = $a;
  218. } else {
  219. $STATUS{$cmd}->{'status'} = $result;
  220. }
  221. }
  222. # Ensure the data is clean
  223. $STATUS{$cmd}->{'status'} =~ s/[^\w\.\-]/_/g;
  224. # If something has changed, save the state to disk
  225. if ($STATUS{$cmd}->{'status'} ne $STATUS{$cmd}->{'last'}) {
  226. if ($DEBUG) {
  227. print STDERR 'New ' . uc($DEV) . ' status: ' . $cmd . ' => ' . $STATUS{$cmd}->{'status'} . "\n";
  228. }
  229. my ($fh, $tmp) = tempfile($STATUS{$cmd}->{'path'} . '.XXXXXXXX', 'UNLINK' => 0);
  230. print $fh $STATUS{$cmd}->{'status'} . "\n";
  231. close($fh);
  232. rename($tmp, $STATUS{$cmd}->{'path'});
  233. }
  234. }
  235. }
  236. }
  237. # Cleanup
  238. undef($select);
  239. $port->close();
  240. undef($port);
  241. exit(0);
  242. sub sendQuery($$) {
  243. my ($port, $query) = @_;
  244. # Enforce an inter-command delay
  245. usleep($SILENCE_TIMEOUT);
  246. # Read until the queue is clear (i.e. no data available)
  247. # Since we don't have flow control this always causes one read timeout
  248. $port->lookclear();
  249. clearBuffer($port);
  250. # Send the command
  251. my $bytes = $port->write($query . $CRLF);
  252. if ($DEBUG) {
  253. print STDERR "\tWrote (" . $bytes . '): ' . $query . "\n";
  254. }
  255. # Wait for a reply (delimited or timeout)
  256. return collectUntil($port, $DELIMITER);
  257. }
  258. sub clearBuffer($) {
  259. my ($port) = @_;
  260. my $byte = 1;
  261. while (length($byte) > 0) {
  262. $byte = $port->read(1);
  263. if ($DEBUG && length($byte)) {
  264. print STDERR "\tIgnored: " . $byte . "\n";
  265. }
  266. }
  267. }
  268. sub collectUntil($$) {
  269. my ($port, $char) = @_;
  270. if (length($char) != 1) {
  271. die('Invalid collection delimiter: ' . $char . "\n");
  272. }
  273. # This byte-by-byte reading is not efficient, but it's safe
  274. # Allow reading forever as long as we don't exceed the silence timeout
  275. my $count = 0;
  276. my $string = '';
  277. while ($count < $SILENCE_TIMEOUT / $BYTE_TIMEOUT) {
  278. my $byte = $port->read(1);
  279. if (length($byte)) {
  280. $count = 0;
  281. $string .= $byte;
  282. if ($DEBUG > 1) {
  283. print STDERR "\tRead: " . $byte . "\n";
  284. }
  285. if ($byte eq $char) {
  286. last;
  287. }
  288. } else {
  289. $count++;
  290. }
  291. }
  292. # Return undef if there was no data (as opposed to just a delimiter and/or whitespace)
  293. if (length($string) < 1) {
  294. if ($DEBUG) {
  295. print STDERR "Read: <NO DATA>\n";
  296. }
  297. return undef();
  298. }
  299. # Translate CRLF and CR to LF
  300. $string =~ s/\r\n/\n/g;
  301. $string =~ s/\r/\n/g;
  302. # Strip the trailing delimiter
  303. $string =~ s/${char}$//;
  304. # Strip leading or trailing whitespace
  305. $string =~ s/^\s+//;
  306. $string =~ s/\s+$//;
  307. # Return our clean string
  308. if ($DEBUG) {
  309. print STDERR 'Read: ' . $string . "\n";
  310. }
  311. return $string;
  312. }