state.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use IO::Select;
  5. use File::Basename;
  6. use File::Temp qw( tempfile );
  7. use Sys::Hostname;
  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 $MEDIA_PATH = `~/bin/video/mediaPath`;
  17. my %DISPLAY_DEVS = ('TV' => 1, 'PROJECTOR' => 1);
  18. my $DISPLAY = undef();
  19. my $STATE_TIMEOUT = 180;
  20. my %MON_FILES = ();
  21. # Host-specific config
  22. # This is necessary to avoid contention on shared disks
  23. my $HOST = Sys::Hostname::hostname();
  24. if ($HOST =~ /loki/i) {
  25. $MON_FILES{ $MEDIA_PATH . '/DMX/cmd/GARAGE_CMD' } = 'EXISTS-VALUE-CLEAR';
  26. }
  27. # Available state files
  28. {
  29. # Plex
  30. $MON_FILES{'GUI'} = 'GUI';
  31. $MON_FILES{'PLAYING'} = 'PLAYING';
  32. # RiffTrax
  33. $MON_FILES{'RIFF'} = 'VALUE';
  34. # Motion detection
  35. $MON_FILES{'MOTION'} = 'MTIME';
  36. $MON_FILES{'NO_MOTION'} = 'EXISTS';
  37. # Projector
  38. $MON_FILES{'PROJECTOR'} = 'STATUS';
  39. $MON_FILES{'PROJECTOR_COLOR'} = 'VALUE';
  40. $MON_FILES{'PROJECTOR_INPUT'} = 'VALUE';
  41. $MON_FILES{'PROJECTOR_LAMP'} = 'VALUE';
  42. # Amplifier
  43. $MON_FILES{'AMPLIFIER'} = 'STATUS';
  44. $MON_FILES{'AMPLIFIER_VOL'} = 'VALUE';
  45. $MON_FILES{'AMPLIFIER_MODE'} = 'VALUE';
  46. $MON_FILES{'AMPLIFIER_INPUT'} = 'VALUE';
  47. $MON_FILES{'AUDIO_AMP'} = 'EXISTS-ON';
  48. $MON_FILES{'STEREO_CMD'} = 'EXISTS-ON';
  49. # A/V Effects
  50. $MON_FILES{'LIGHTS'} = 'EXISTS-ON';
  51. $MON_FILES{'RAVE'} = 'EXISTS';
  52. $MON_FILES{'EFFECT'} = 'EXISTS';
  53. # Equipment
  54. $MON_FILES{'FAN_CMD'} = 'EXISTS-ON';
  55. # OS State
  56. $MON_FILES{'COLOR'} = 'VALUE';
  57. $MON_FILES{'AUDIO'} = 'VALUE';
  58. $MON_FILES{'AUDIO_STATE'} = 'VALUE';
  59. # TV
  60. $MON_FILES{'TV'} = 'STATUS';
  61. $MON_FILES{'TV_VOL'} = 'VALUE';
  62. }
  63. my %EXTRAS = (
  64. 'PLAYING' => {
  65. 'URL' => qr/^\<li\>Filename\:(.+)$/m,
  66. 'YEAR' => qr/^\<li\>Year\:(\d+)/m,
  67. 'SERIES' => qr/^\<li\>Show Title\:(.+)$/m,
  68. 'SEASON' => qr/^\<li\>Season\:(\d+)/m,
  69. 'EPISODE' => qr/^\<li\>Episode\:(\d+)/m,
  70. 'TITLE' => qr/^\<li\>Title\:(.+)$/m,
  71. 'LENGTH' => qr/^\<li\>Duration\:([\d\:]+)/m,
  72. 'POSITION' => qr/^\<li\>Time\:([\d\:]+)/m,
  73. 'SIZE' => qr/^\<li\>File size\:(\d+)/m,
  74. 'TYPE' => qr/^\<li\>Type\:(.+)$/m,
  75. }
  76. );
  77. # App config
  78. my $SOCK_TIMEOUT = 5;
  79. my $DATA_DIR = DMX::dataDir();
  80. my $CMD_FILE = 'STATE';
  81. my $MAX_CMD_LEN = 4096;
  82. my $RESET_CMD = $ENV{'HOME'} . '/bin/video/dmx/reset.sh';
  83. my $PUSH_TIMEOUT = 20;
  84. # Debug
  85. my $DEBUG = 0;
  86. if ($ENV{'DEBUG'}) {
  87. $DEBUG = 1;
  88. }
  89. # Command-line arguments
  90. my ($DELAY) = @ARGV;
  91. if (!$DELAY) {
  92. $DELAY = 0.5;
  93. }
  94. # Socket init
  95. my $select = DMX::stateSocket($CMD_FILE);
  96. # Add the extras to the main file list
  97. foreach my $file (keys(%EXTRAS)) {
  98. if (exists($MON_FILES{$file})) {
  99. foreach my $extra (keys(%{ $EXTRAS{$file} })) {
  100. $MON_FILES{ $file . '_' . $extra } = 'NONE';
  101. }
  102. }
  103. }
  104. # Init the file tracking structure
  105. my %files = ();
  106. foreach my $name (keys(%MON_FILES)) {
  107. my %file = (
  108. 'name' => basename($name),
  109. 'type' => $MON_FILES{$name},
  110. 'path' => $DATA_DIR . $name,
  111. 'update' => 0,
  112. 'value' => 0,
  113. 'last' => 0,
  114. );
  115. # Allow absolute paths to override the $DATA_DIR path
  116. if ($name =~ /^\//) {
  117. $file{'path'} = $name;
  118. }
  119. # Record the directory name for folder monitoring
  120. $file{'dir'} = dirname($file{'path'});
  121. # Set the attribute bits, for use in later update handling logic
  122. my %attr = (
  123. 'available' => 0,
  124. 'status' => 0,
  125. 'exists' => 0,
  126. 'value' => 0,
  127. 'clear' => 0,
  128. 'clear_off' => 0,
  129. 'mtime' => 0,
  130. 'gui' => 0,
  131. 'playing' => 0,
  132. );
  133. if ($file{'type'} =~ /\bSTATUS\b/i) {
  134. $attr{'status'} = 1;
  135. }
  136. if ($file{'type'} =~ /\bEXISTS\b/i) {
  137. $attr{'exists'} = 1;
  138. }
  139. if ($file{'type'} =~ /\bVALUE\b/i) {
  140. $attr{'value'} = 1;
  141. }
  142. if ($file{'type'} =~ /\bCLEAR\b/i) {
  143. $attr{'clear'} = 1;
  144. }
  145. if ($file{'type'} =~ /\bON\b/i) {
  146. $attr{'clear_off'} = 1;
  147. }
  148. if ($file{'type'} =~ /\bMTIME\b/i) {
  149. $attr{'mtime'} = 1;
  150. }
  151. if ($file{'type'} =~ /\bGUI\b/i) {
  152. $attr{'gui'} = 1;
  153. }
  154. if ($file{'type'} =~ /\bPLAYING\b/i) {
  155. $attr{'playing'} = 1;
  156. }
  157. # Cross-match some data types for easy of use
  158. if ($attr{'value'} || $attr{'gui'} || $attr{'playing'}) {
  159. $attr{'status'} = 1;
  160. }
  161. if ($attr{'status'} || $attr{'exists'}) {
  162. $attr{'mtime'} = 1;
  163. }
  164. # Push ATTR into the file hash
  165. $file{'attr'} = \%attr;
  166. # Push FILE into the files hash
  167. $files{$name} = \%file;
  168. }
  169. # Delete any existing input files, to ensure our state is reset
  170. foreach my $file (values(%files)) {
  171. if (-e $file->{'path'}) {
  172. if ($DEBUG) {
  173. print STDERR 'Deleting ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  174. }
  175. unlink($file->{'path'});
  176. }
  177. }
  178. # Reset all dependents at starts
  179. system($RESET_CMD);
  180. # Subscribers
  181. my @subscribers = ();
  182. # State
  183. my $state = 'INIT';
  184. my $stateLast = $state;
  185. my $status = '';
  186. my $statusLast = $status;
  187. my $updateLast = 0;
  188. my $pushLast = 0;
  189. # Loop forever
  190. while (1) {
  191. # Provide a method to force updates even when the state does not change
  192. my $update = 0;
  193. # Check for queued commands
  194. my @ready_clients = $select->can_read($DELAY);
  195. foreach my $fh (@ready_clients) {
  196. # Grab the inbound text
  197. my $path = undef();
  198. $fh->recv($path, $MAX_CMD_LEN);
  199. $path =~ s/^\s+//;
  200. $path =~ s/\s+$//;
  201. $path =~ s/\W/_/g;
  202. if ($DEBUG) {
  203. print STDERR 'Got path: ' . $path . "\n";
  204. }
  205. # Open the new socket
  206. my $sub = eval { DMX::clientSock($path); };
  207. if (!$sub) {
  208. print STDERR 'Unable to open socket: ' . $path . ": ${@}\n";
  209. next;
  210. }
  211. # Add the socket to our subscriber list
  212. my %tmp = (
  213. 'path' => $path,
  214. 'socket' => $sub,
  215. );
  216. push(@subscribers, \%tmp);
  217. # Force an update
  218. $update = 1;
  219. }
  220. # Use opendir/readdir in each folder to ensure fresh results
  221. my %folders = ();
  222. foreach my $file (values(%files)) {
  223. if (!$folders{ $file->{'dir'} }) {
  224. my $dh = undef();
  225. if (opendir($dh, $file->{'dir'})) {
  226. if ($DEBUG) {
  227. print STDERR 'Refreshed folder: ' . $file->{'dir'} . "\n";
  228. }
  229. my @files = readdir($dh);
  230. closedir($dh);
  231. }
  232. $folders{ $file->{'dir'} } = 1;
  233. }
  234. }
  235. # Monitor files of all types
  236. foreach my $file (values(%files)) {
  237. # Skip "NONE" files -- they are data stores handled in other actions
  238. if ($file->{'type'} eq 'NONE') {
  239. next;
  240. }
  241. # Always record the previous status and clear the new one
  242. $file->{'last'} = $file->{'value'};
  243. $file->{'value'} = 0;
  244. # Track available/unavailable status in each cycle
  245. {
  246. my $wasAvailable = $file->{'attr'}->{'available'};
  247. $file->{'attr'}->{'available'} = -r $file->{'path'} ? 1 : 0;
  248. if ($wasAvailable != $file->{'attr'}->{'available'}) {
  249. # Reset and extras for this file
  250. if (exists($EXTRAS{ $file->{'name'} })) {
  251. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  252. my $name = $file->{'name'} . '_' . $extra;
  253. $files{$name}{'last'} = $files{$name}{'value'};
  254. $files{$name}{'value'} = 0;
  255. }
  256. }
  257. # Determine which display device we have (if any)
  258. if (exists($DISPLAY_DEVS{ $file->{'name'} })) {
  259. $DISPLAY = $file->{'name'};
  260. if ($DEBUG) {
  261. print STDERR 'Selecting display device: ' . $DISPLAY . "\n";
  262. }
  263. }
  264. if ($DEBUG) {
  265. if ($file->{'attr'}->{'available'}) {
  266. print STDERR 'Added file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  267. } else {
  268. print STDERR 'Dropped file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  269. }
  270. }
  271. }
  272. }
  273. # Skip unavailable files
  274. if (!$file->{'attr'}->{'available'}) {
  275. next;
  276. }
  277. # Record the last update for MTIME files
  278. if ($file->{'attr'}->{'mtime'}) {
  279. my $mtime = mtime($file->{'path'});
  280. # All EXISTS files have MTIME set, and mtime returns 0 if the file does not exist, so we can overload this check
  281. if ($file->{'attr'}->{'exists'}) {
  282. if ($mtime > 0) {
  283. $file->{'update'} = $mtime;
  284. $file->{'value'} = 1;
  285. } elsif ($file->{'last'}) {
  286. $file->{'update'} = time();
  287. }
  288. } else {
  289. $file->{'update'} = $mtime;
  290. }
  291. if ($DEBUG) {
  292. print STDERR 'Mtime: ' . $file->{'name'} . ': ' . $file->{'value'} . ':' . $file->{'update'} . "\n";
  293. }
  294. }
  295. # Grab the state from STATUS files
  296. if ($file->{'attr'}->{'status'}) {
  297. my $text = '';
  298. {
  299. if (!open(my $fh, $file->{'path'})) {
  300. warn('Unable to open ' . $file->{'path'} . "\n");
  301. } else {
  302. local $/;
  303. $text = <$fh>;
  304. close($fh);
  305. }
  306. }
  307. # Parse the value for the file
  308. if ($file->{'attr'}->{'value'}) {
  309. $text =~ s/\n$//;
  310. $file->{'value'} = $text;
  311. } elsif ($file->{'attr'}->{'playing'}) {
  312. if ($text =~ /PlayStatus\:Playing/) {
  313. $file->{'value'} = 1;
  314. }
  315. } elsif ($file->{'attr'}->{'gui'}) {
  316. if (!($text =~ /ActiveWindowName\:Fullscreen video/)) {
  317. $file->{'value'} = 1;
  318. }
  319. } else {
  320. if ($text =~ /1/) {
  321. $file->{'value'} = 1;
  322. }
  323. }
  324. if ($DEBUG) {
  325. print STDERR 'Status: ' . $file->{'name'} . ': ' . $file->{'value'} . "\n";
  326. }
  327. # Handle extras, if any
  328. if (exists($EXTRAS{ $file->{'name'} })) {
  329. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  330. my $name = $file->{'name'} . '_' . $extra;
  331. $files{$name}{'last'} = $files{$name}{'value'};
  332. $files{$name}{'value'} = 0;
  333. $files{$name}{'update'} = $file->{'update'};
  334. if ($text =~ $EXTRAS{ $file->{'name'} }{$extra}) {
  335. $files{$name}{'value'} = $1;
  336. }
  337. if ($DEBUG) {
  338. print STDERR 'Status (extra): ' . $name . ': ' . $files{$name}{'value'} . "\n";
  339. }
  340. }
  341. }
  342. }
  343. }
  344. # Set the global update timestamp
  345. foreach my $file (values(%files)) {
  346. if ($file->{'update'} > $updateLast) {
  347. $updateLast = $file->{'update'};
  348. }
  349. }
  350. # Determine some intermediate state data
  351. my $playing = 0;
  352. if (exists($files{'PLAYING'}) && $files{'PLAYING'}->{'value'}) {
  353. $playing = 1;
  354. }
  355. my $video = 0;
  356. if (exists($files{'PLAYING_TYPE'}) && $files{'PLAYING_TYPE'}->{'value'} ne 'Audio') {
  357. $video = 1;
  358. } elsif (!exists($files{'PLAYING_TYPE'})) {
  359. $video = 1;
  360. }
  361. # Calculate the new state
  362. $stateLast = $state;
  363. if (!defined($DISPLAY) || !exists($files{$DISPLAY})) {
  364. # If there's no display the state is always PLAY or PAUSE, as indicated by the master
  365. if ($playing) {
  366. $state = 'PLAY';
  367. } else {
  368. $state = 'PAUSE';
  369. }
  370. } elsif ($files{$DISPLAY}->{'value'}) {
  371. # If a display exists and is on:
  372. # PLAY when video is active and playing
  373. # PAUSE any other time (including when audio is active)
  374. if ($playing && $video) {
  375. $state = 'PLAY';
  376. } else {
  377. $state = 'PAUSE';
  378. }
  379. } else {
  380. # If the display exists but is off, check the timeouts to determine MOTION vs. OFF
  381. my $timeSinceUpdate = time() - $updateLast;
  382. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  383. $state = 'OFF';
  384. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  385. if (exists($files{'NO_MOTION'}) && $files{'NO_MOTION'}->{'value'}) {
  386. $state = 'OFF';
  387. } else {
  388. $state = 'MOTION';
  389. }
  390. }
  391. }
  392. if ($state eq 'INIT') {
  393. $state = 'OFF';
  394. }
  395. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  396. foreach my $file (values(%files)) {
  397. if ($file->{'attr'}->{'clear_off'} && $file->{'value'} && $state eq 'OFF') {
  398. unlink($file->{'path'});
  399. $file->{'stauts'} = 0;
  400. if ($DEBUG) {
  401. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  402. }
  403. }
  404. }
  405. # Calculate the new status
  406. $statusLast = $status;
  407. {
  408. my @statTime = ();
  409. foreach my $file (values(%files)) {
  410. my $text = $file->{'value'};
  411. $text =~ s/\s/ /g;
  412. $text =~ s/\|/-/g;
  413. push(@statTime, $file->{'name'} . '|' . $text . '|' . $file->{'update'});
  414. }
  415. $status = "\n" . join("\n", @statTime);
  416. }
  417. # Clear EXISTS_CLEAR files immediately (but after we append their status)
  418. foreach my $file (values(%files)) {
  419. if ($file->{'attr'}->{'clear'} && $file->{'value'}) {
  420. unlink($file->{'path'});
  421. $file->{'stauts'} = 0;
  422. if ($DEBUG) {
  423. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  424. }
  425. }
  426. }
  427. # Force updates on a periodic basis
  428. if (time() - $pushLast > $PUSH_TIMEOUT) {
  429. $update = 1;
  430. }
  431. # Update on any status change
  432. foreach my $file (values(%files)) {
  433. if ($file->{'value'} ne $file->{'last'}) {
  434. $update = 1;
  435. last;
  436. }
  437. }
  438. # Force updates on any state change
  439. if ($stateLast ne $state || $statusLast ne $status) {
  440. if ($DEBUG) {
  441. print STDERR 'State change: ' . $stateLast . $statusLast . ' => ' . $state . $status . "\n";
  442. }
  443. $update = 1;
  444. }
  445. # Push the update
  446. if ($update) {
  447. # Note the push
  448. $pushLast = time();
  449. # Send notifications to all subscribers
  450. foreach my $sub (@subscribers) {
  451. # Drop subscribers that are not available
  452. if (!eval { $sub->{'socket'}->send($state . $status) }) {
  453. print STDERR 'Dropping bad socket from subscriber list: ' . $sub->{'path'} . "\n";
  454. my @new_subscribers = ();
  455. foreach my $new (@subscribers) {
  456. if ($new->{'socket'} eq $sub->{'socket'}) {
  457. next;
  458. }
  459. push(@new_subscribers, $new);
  460. }
  461. @subscribers = @new_subscribers;
  462. }
  463. }
  464. # Save the state and value to disk
  465. my ($fh, $tmp) = tempfile($DATA_DIR . 'STATE.XXXXXXXX', 'UNLINK' => 0);
  466. print $fh $state . "\n";
  467. close($fh);
  468. rename($tmp, $DATA_DIR . 'STATE');
  469. }
  470. }
  471. sub mtime($) {
  472. my ($file) = @_;
  473. my $mtime = 0;
  474. if (-r $file) {
  475. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), $mtime, undef(), undef(), undef()) = stat($file);
  476. }
  477. return $mtime;
  478. }