state.pl 8.1 KB

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