serial.pl 8.2 KB

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