state.pl 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. # 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 in each folder before calling stat(), 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. my @stat = stat($file->{'path'});
  172. if (scalar(@stat) > 0) {
  173. $file->{'status'} = 1;
  174. $file->{'update'} = $stat[9];
  175. }
  176. if ($DEBUG) {
  177. print STDERR 'Exists: ' . $file->{'name'} . ': ' . $file->{'status'} . "\n";
  178. }
  179. }
  180. }
  181. # Set the global update timestamp
  182. foreach my $file (values(%files)) {
  183. if ($file->{'update'} > $updateLast) {
  184. $updateLast = $file->{'update'};
  185. }
  186. }
  187. # Calculate the new state
  188. $stateLast = $state;
  189. if ($files{'PROJECTOR'}->{'status'}) {
  190. # We are always either playing or paused if the projector is on
  191. if ($files{'PLAYING'}->{'status'}) {
  192. $state = 'PLAY';
  193. } else {
  194. $state = 'PAUSE';
  195. }
  196. } else {
  197. # If the projector is off, check the timeouts
  198. my $timeSinceUpdate = time() - $updateLast;
  199. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  200. $state = 'OFF';
  201. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  202. if ($files{'NO_MOTION'}->{'status'}) {
  203. $state = 'OFF';
  204. } else {
  205. $state = 'MOTION';
  206. }
  207. }
  208. }
  209. if ($state eq 'INIT') {
  210. $state = 'OFF';
  211. }
  212. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  213. foreach my $file (values(%files)) {
  214. if ($file->{'type'} eq 'EXISTS_ON' && $file->{'status'} && $state eq 'OFF') {
  215. unlink($file->{'path'});
  216. $file->{'stauts'} = 0;
  217. if ($DEBUG) {
  218. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  219. }
  220. }
  221. }
  222. # Calculate the new status
  223. $statusLast = $status;
  224. {
  225. my @statTime = ();
  226. foreach my $file (values(%files)) {
  227. push(@statTime, $file->{'name'} . ':' . $file->{'status'} . ':' . $file->{'update'});
  228. }
  229. $status = ' (' . join(', ', @statTime) . ')';
  230. }
  231. # Clear EXISTS_CLEAR files immediately (but after we append their status)
  232. foreach my $file (values(%files)) {
  233. if ($file->{'type'} eq 'EXISTS_CLEAR' && $file->{'status'}) {
  234. unlink($file->{'path'});
  235. $file->{'stauts'} = 0;
  236. if ($DEBUG) {
  237. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  238. }
  239. }
  240. }
  241. # Force updates on a periodic basis
  242. if (time() - $pushLast > $PUSH_TIMEOUT) {
  243. $update = 1;
  244. }
  245. # Update on any status change
  246. foreach my $file (values(%files)) {
  247. if ($file->{'status'} != $file->{'last'}) {
  248. $update = 1;
  249. last;
  250. }
  251. }
  252. # Force updates on any state change
  253. if ($stateLast ne $state || $statusLast ne $status) {
  254. if ($DEBUG) {
  255. print STDERR 'State change: ' . $stateLast . $statusLast . ' => ' . $state . $status . "\n";
  256. }
  257. $update = 1;
  258. }
  259. # Push the update
  260. if ($update) {
  261. # Note the push
  262. $pushLast = time();
  263. # Send notifications to all subscribers
  264. foreach my $sub (@subscribers) {
  265. # Drop subscribers that are not available
  266. if (!eval { $sub->{'socket'}->send($state . $status) }) {
  267. print STDERR 'Dropping bad socket from subscriber list: ' . $sub->{'path'} . "\n";
  268. my @new_subscribers = ();
  269. foreach my $new (@subscribers) {
  270. if ($new->{'socket'} eq $sub->{'socket'}) {
  271. next;
  272. }
  273. push(@new_subscribers, $new);
  274. }
  275. @subscribers = @new_subscribers;
  276. }
  277. }
  278. # Save the state and value to disk
  279. my ($fh, $tmp) = tempfile($DATA_DIR . 'STATE.XXXXXXXX', 'UNLINK' => 0);
  280. print $fh $state . "\n";
  281. close($fh);
  282. rename($tmp, $DATA_DIR . 'STATE');
  283. }
  284. }
  285. sub mtime($) {
  286. my ($file) = @_;
  287. my $mtime = 0;
  288. if (-r $file) {
  289. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), $mtime, undef(), undef(), undef()) = stat($file);
  290. }
  291. return $mtime;
  292. }