state.pl 8.0 KB

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