state.pl 9.8 KB

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