state.pl 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use IO::Select;
  5. use IO::Socket::UNIX;
  6. use File::Basename;
  7. use File::Temp qw( tempfile );
  8. # Local modules
  9. use Cwd qw(abs_path);
  10. use File::Basename qw(dirname);
  11. use lib dirname(abs_path($0));
  12. use DMX;
  13. # Prototypes
  14. sub mtime($);
  15. # User config
  16. my $STATE_TIMEOUT = 180;
  17. my %MON_FILES = (
  18. 'GUI' => 'MTIME',
  19. 'MOTION' => 'MTIME',
  20. 'PROJECTOR' => 'STATUS',
  21. 'AMPLIFIER' => 'STATUS',
  22. 'PLAYING' => 'STATUS_PLAYING',
  23. 'NO_MOTION' => 'EXISTS',
  24. 'RAVE' => 'EXISTS',
  25. 'EFFECT' => 'EXISTS',
  26. 'FAN_CMD' => 'EXISTS_ON',
  27. 'LIGHTS' => 'EXISTS_ON',
  28. 'STEREO_CMD' => 'EXISTS_ON',
  29. 'AMPLIFIER_VOL' => 'STATUS_VALUE',
  30. 'AMPLIFIER_MODE' => 'STATUS_VALUE',
  31. 'AMPLIFIER_INPUT' => 'STATUS_VALUE',
  32. 'AUDIO_OUTPUT' => 'STATUS_VALUE',
  33. '/mnt/media/DMX/cmd/GARAGE_CMD' => 'EXISTS_CLEAR',
  34. );
  35. # App config
  36. my $SOCK_TIMEOUT = 5;
  37. my $DATA_DIR = DMX::dataDir();
  38. my $CMD_FILE = $DATA_DIR . 'STATE.socket';
  39. my $MAX_CMD_LEN = 4096;
  40. my $RESET_CMD = $ENV{'HOME'} . '/bin/video/dmx/reset.sh';
  41. my $PUSH_TIMEOUT = 20;
  42. # Debug
  43. my $DEBUG = 0;
  44. if ($ENV{'DEBUG'}) {
  45. $DEBUG = 1;
  46. }
  47. # Command-line arguments
  48. my ($DELAY) = @ARGV;
  49. if (!$DELAY) {
  50. $DELAY = 0.5;
  51. }
  52. # Socket init
  53. my $select = DMX::stateSocket($CMD_FILE);
  54. # Reset all dependents at starts
  55. system($RESET_CMD);
  56. # Subscribers
  57. my @subscribers = ();
  58. # State
  59. my $state = 'INIT';
  60. my $stateLast = $state;
  61. my $status = '';
  62. my $statusLast = $status;
  63. my $updateLast = 0;
  64. my $pushLast = 0;
  65. # Init the file tracking structure
  66. my %files = ();
  67. foreach my $file (keys(%MON_FILES)) {
  68. my %tmp = (
  69. 'name' => basename($file),
  70. 'type' => $MON_FILES{$file},
  71. 'path' => $DATA_DIR . $file,
  72. 'update' => 0,
  73. 'status' => 0,
  74. 'last' => 0,
  75. );
  76. # Allow absolute paths to override the $DATA_DIR path
  77. if ($file =~ /^\//) {
  78. $tmp{'path'} = $file;
  79. }
  80. # Record the directory name for folder monitoring
  81. $tmp{'dir'} = dirname($tmp{'path'});
  82. # Push a hash ref
  83. $files{$file} = \%tmp;
  84. }
  85. # Loop forever
  86. while (1) {
  87. # Provide a method to force updates even when the state does not change
  88. my $update = 0;
  89. # Check for queued commands
  90. my @ready_clients = $select->can_read($DELAY);
  91. foreach my $fh (@ready_clients) {
  92. # Grab the inbound text
  93. my $path = undef();
  94. $fh->recv($path, $MAX_CMD_LEN);
  95. $path =~ s/^\s+//;
  96. $path =~ s/\s+$//;
  97. if ($DEBUG) {
  98. print STDERR 'Got path: ' . $path . "\n";
  99. }
  100. # Only accept valid paths
  101. if (!-r $path) {
  102. print STDERR 'Invalid socket path: ' . $path . "\n";
  103. next;
  104. }
  105. # Open the new socket
  106. my $sub = IO::Socket::UNIX->new(
  107. 'Peer' => $path,
  108. 'Type' => SOCK_DGRAM,
  109. 'Timeout' => $SOCK_TIMEOUT
  110. );
  111. if (!$sub) {
  112. print STDERR 'Unable to open socket: ' . $path . ": ${@}\n";
  113. next;
  114. }
  115. # Add the socket to our subscriber list
  116. my %tmp = (
  117. 'path' => $path,
  118. 'socket' => $sub,
  119. );
  120. push(@subscribers, \%tmp);
  121. # Force an update
  122. $update = 1;
  123. }
  124. # Use opendir/readdir in each folder to ensure fresh results
  125. my %folders = ();
  126. foreach my $file (values(%files)) {
  127. if (!$folders{ $file->{'dir'} }) {
  128. my $dh = undef();
  129. if (opendir($dh, $file->{'dir'})) {
  130. if ($DEBUG) {
  131. print STDERR 'Refreshed folder: ' . $file->{'dir'} . "\n";
  132. }
  133. my @files = readdir($dh);
  134. closedir($dh);
  135. }
  136. $folders{ $file->{'dir'} } = 1;
  137. }
  138. }
  139. # Monitor files of all types
  140. foreach my $file (values(%files)) {
  141. # Always record the previous status and clear the new one
  142. $file->{'last'} = $file->{'status'};
  143. $file->{'status'} = 0;
  144. # Record the last update for STATUS and MTIME files
  145. if ($file->{'type'} =~ /^STATUS/ || $file->{'type'} =~ /^MTIME/) {
  146. $file->{'update'} = mtime($file->{'path'});
  147. if ($DEBUG) {
  148. print STDERR 'Last change: ' . $file->{'name'} . ': ' . localtime($file->{'update'}) . "\n";
  149. }
  150. }
  151. # Grab the state from STATUS files
  152. if ($file->{'type'} =~ /^STATUS/) {
  153. my $text = undef();
  154. {
  155. my $fh;
  156. open($fh, $file->{'path'})
  157. or die('Unable to open ' . $file->{'path'} . "\n");
  158. local $/;
  159. $text = <$fh>;
  160. close($fh);
  161. }
  162. if ($file->{'type'} eq 'STATUS_PLAYING') {
  163. if ($text =~ /PlayStatus\:Playing/) {
  164. $file->{'status'} = 1;
  165. }
  166. } elsif ($file->{'type'} eq 'STATUS_VALUE') {
  167. $text =~ s/\n$//;
  168. $file->{'status'} = $text;
  169. } else {
  170. if ($text =~ /1/) {
  171. $file->{'status'} = 1;
  172. }
  173. }
  174. if ($DEBUG) {
  175. print STDERR 'Status: ' . $file->{'name'} . ': ' . $file->{'status'} . "\n";
  176. }
  177. }
  178. # Check for the presence of EXISTS files and record their last change
  179. if ($file->{'type'} =~ /^EXISTS/) {
  180. my $mtime = mtime($file->{'path'});
  181. if ($mtime > 0) {
  182. $file->{'status'} = 1;
  183. $file->{'update'} = $mtime;
  184. } elsif ($file->{'last'}) {
  185. $file->{'update'} = time();
  186. }
  187. if ($DEBUG) {
  188. print STDERR 'Exists: ' . $file->{'name'} . ': ' . $file->{'status'} . ':' . $file->{'update'} . "\n";
  189. }
  190. }
  191. }
  192. # Set the global update timestamp
  193. foreach my $file (values(%files)) {
  194. if ($file->{'update'} > $updateLast) {
  195. $updateLast = $file->{'update'};
  196. }
  197. }
  198. # Calculate the new state
  199. $stateLast = $state;
  200. if ($files{'PROJECTOR'}->{'status'}) {
  201. # We are always either playing or paused if the projector is on
  202. if ($files{'PLAYING'}->{'status'}) {
  203. $state = 'PLAY';
  204. } else {
  205. $state = 'PAUSE';
  206. }
  207. } else {
  208. # If the projector is off, check the timeouts
  209. my $timeSinceUpdate = time() - $updateLast;
  210. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  211. $state = 'OFF';
  212. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  213. if ($files{'NO_MOTION'}->{'status'}) {
  214. $state = 'OFF';
  215. } else {
  216. $state = 'MOTION';
  217. }
  218. }
  219. }
  220. if ($state eq 'INIT') {
  221. $state = 'OFF';
  222. }
  223. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  224. foreach my $file (values(%files)) {
  225. if ($file->{'type'} eq 'EXISTS_ON' && $file->{'status'} && $state eq 'OFF') {
  226. unlink($file->{'path'});
  227. $file->{'stauts'} = 0;
  228. if ($DEBUG) {
  229. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  230. }
  231. }
  232. }
  233. # Calculate the new status
  234. $statusLast = $status;
  235. {
  236. my @statTime = ();
  237. foreach my $file (values(%files)) {
  238. push(@statTime, $file->{'name'} . ':' . $file->{'status'} . ':' . $file->{'update'});
  239. }
  240. $status = ' (' . join(', ', @statTime) . ')';
  241. }
  242. # Clear EXISTS_CLEAR files immediately (but after we append their status)
  243. foreach my $file (values(%files)) {
  244. if ($file->{'type'} eq 'EXISTS_CLEAR' && $file->{'status'}) {
  245. unlink($file->{'path'});
  246. $file->{'stauts'} = 0;
  247. if ($DEBUG) {
  248. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  249. }
  250. }
  251. }
  252. # Force updates on a periodic basis
  253. if (time() - $pushLast > $PUSH_TIMEOUT) {
  254. $update = 1;
  255. }
  256. # Update on any status change
  257. foreach my $file (values(%files)) {
  258. if ($file->{'status'} ne $file->{'last'}) {
  259. $update = 1;
  260. last;
  261. }
  262. }
  263. # Force updates on any state change
  264. if ($stateLast ne $state || $statusLast ne $status) {
  265. if ($DEBUG) {
  266. print STDERR 'State change: ' . $stateLast . $statusLast . ' => ' . $state . $status . "\n";
  267. }
  268. $update = 1;
  269. }
  270. # Push the update
  271. if ($update) {
  272. # Note the push
  273. $pushLast = time();
  274. # Send notifications to all subscribers
  275. foreach my $sub (@subscribers) {
  276. # Drop subscribers that are not available
  277. if (!eval { $sub->{'socket'}->send($state . $status) }) {
  278. print STDERR 'Dropping bad socket from subscriber list: ' . $sub->{'path'} . "\n";
  279. my @new_subscribers = ();
  280. foreach my $new (@subscribers) {
  281. if ($new->{'socket'} eq $sub->{'socket'}) {
  282. next;
  283. }
  284. push(@new_subscribers, $new);
  285. }
  286. @subscribers = @new_subscribers;
  287. }
  288. }
  289. # Save the state and value to disk
  290. my ($fh, $tmp) = tempfile($DATA_DIR . 'STATE.XXXXXXXX', 'UNLINK' => 0);
  291. print $fh $state . "\n";
  292. close($fh);
  293. rename($tmp, $DATA_DIR . 'STATE');
  294. }
  295. }
  296. sub mtime($) {
  297. my ($file) = @_;
  298. my $mtime = 0;
  299. if (-r $file) {
  300. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), $mtime, undef(), undef(), undef()) = stat($file);
  301. }
  302. return $mtime;
  303. }