state.pl 7.7 KB

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