serial.pl 8.3 KB

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