state.pl 7.5 KB

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