state.pl 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. '/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. # 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. # Use opendir/readdir in each folder to ensure fresh results
  120. my %folders = ();
  121. foreach my $file (values(%files)) {
  122. if (!$folders{ $file->{'dir'} }) {
  123. my $dh = undef();
  124. if (opendir($dh, $file->{'dir'})) {
  125. if ($DEBUG) {
  126. print STDERR 'Refreshed folder: ' . $file->{'dir'} . "\n";
  127. }
  128. my @files = readdir($dh);
  129. closedir($dh);
  130. }
  131. $folders{ $file->{'dir'} } = 1;
  132. }
  133. }
  134. # Monitor files of all types
  135. foreach my $file (values(%files)) {
  136. # Always record the previous status and clear the new one
  137. $file->{'last'} = $file->{'status'};
  138. $file->{'status'} = 0;
  139. # Record the last update for STATUS and MTIME files
  140. if ($file->{'type'} =~ /^STATUS/ || $file->{'type'} =~ /^MTIME/) {
  141. $file->{'update'} = mtime($file->{'path'});
  142. if ($DEBUG) {
  143. print STDERR 'Last change: ' . $file->{'name'} . ': ' . localtime($file->{'update'}) . "\n";
  144. }
  145. }
  146. # Grab the state from STATUS files
  147. if ($file->{'type'} =~ /^STATUS/) {
  148. my $text = undef();
  149. {
  150. my $fh;
  151. open($fh, $file->{'path'})
  152. or die('Unable to open ' . $file->{'path'} . "\n");
  153. local $/;
  154. $text = <$fh>;
  155. close($fh);
  156. }
  157. if ($file->{'type'} eq 'STATUS_PLAYING') {
  158. if ($text =~ /PlayStatus\:Playing/) {
  159. $file->{'status'} = 1;
  160. }
  161. } else {
  162. if ($text =~ /1/) {
  163. $file->{'status'} = 1;
  164. }
  165. }
  166. if ($DEBUG) {
  167. print STDERR 'Status: ' . $file->{'name'} . ': ' . $file->{'status'} . "\n";
  168. }
  169. }
  170. # Check for the presence of EXISTS files and record their last change
  171. if ($file->{'type'} =~ /^EXISTS/) {
  172. my $mtime = mtime($file->{'path'});
  173. if ($mtime > 0) {
  174. $file->{'status'} = 1;
  175. $file->{'update'} = $mtime;
  176. } elsif ($file->{'last'}) {
  177. $file->{'update'} = time();
  178. }
  179. if ($DEBUG) {
  180. print STDERR 'Exists: ' . $file->{'name'} . ': ' . $file->{'status'} . ':' . $file->{'update'} . "\n";
  181. }
  182. }
  183. }
  184. # Set the global update timestamp
  185. foreach my $file (values(%files)) {
  186. if ($file->{'update'} > $updateLast) {
  187. $updateLast = $file->{'update'};
  188. }
  189. }
  190. # Calculate the new state
  191. $stateLast = $state;
  192. if ($files{'PROJECTOR'}->{'status'}) {
  193. # We are always either playing or paused if the projector is on
  194. if ($files{'PLAYING'}->{'status'}) {
  195. $state = 'PLAY';
  196. } else {
  197. $state = 'PAUSE';
  198. }
  199. } else {
  200. # If the projector is off, check the timeouts
  201. my $timeSinceUpdate = time() - $updateLast;
  202. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  203. $state = 'OFF';
  204. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  205. if ($files{'NO_MOTION'}->{'status'}) {
  206. $state = 'OFF';
  207. } else {
  208. $state = 'MOTION';
  209. }
  210. }
  211. }
  212. if ($state eq 'INIT') {
  213. $state = 'OFF';
  214. }
  215. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  216. foreach my $file (values(%files)) {
  217. if ($file->{'type'} eq 'EXISTS_ON' && $file->{'status'} && $state eq 'OFF') {
  218. unlink($file->{'path'});
  219. $file->{'stauts'} = 0;
  220. if ($DEBUG) {
  221. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  222. }
  223. }
  224. }
  225. # Calculate the new status
  226. $statusLast = $status;
  227. {
  228. my @statTime = ();
  229. foreach my $file (values(%files)) {
  230. push(@statTime, $file->{'name'} . ':' . $file->{'status'} . ':' . $file->{'update'});
  231. }
  232. $status = ' (' . 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 . $status) }) {
  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. }