state.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 = $DATA_DIR . 'STATE.socket';
  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. if ($DEBUG) {
  202. print STDERR 'Got path: ' . $path . "\n";
  203. }
  204. # Only accept valid paths
  205. if (!-r $path) {
  206. print STDERR 'Invalid socket path: ' . $path . "\n";
  207. next;
  208. }
  209. # Open the new socket
  210. my $sub = eval { DMX::clientSock($path); };
  211. if (!$sub) {
  212. print STDERR 'Unable to open socket: ' . $path . ": ${@}\n";
  213. next;
  214. }
  215. # Add the socket to our subscriber list
  216. my %tmp = (
  217. 'path' => $path,
  218. 'socket' => $sub,
  219. );
  220. push(@subscribers, \%tmp);
  221. # Force an update
  222. $update = 1;
  223. }
  224. # Use opendir/readdir in each folder to ensure fresh results
  225. my %folders = ();
  226. foreach my $file (values(%files)) {
  227. if (!$folders{ $file->{'dir'} }) {
  228. my $dh = undef();
  229. if (opendir($dh, $file->{'dir'})) {
  230. if ($DEBUG) {
  231. print STDERR 'Refreshed folder: ' . $file->{'dir'} . "\n";
  232. }
  233. my @files = readdir($dh);
  234. closedir($dh);
  235. }
  236. $folders{ $file->{'dir'} } = 1;
  237. }
  238. }
  239. # Monitor files of all types
  240. foreach my $file (values(%files)) {
  241. # Skip "NONE" files -- they are data stores handled in other actions
  242. if ($file->{'type'} eq 'NONE') {
  243. next;
  244. }
  245. # Always record the previous status and clear the new one
  246. $file->{'last'} = $file->{'value'};
  247. $file->{'value'} = 0;
  248. # Track available/unavailable status in each cycle
  249. {
  250. my $wasAvailable = $file->{'attr'}->{'available'};
  251. $file->{'attr'}->{'available'} = -r $file->{'path'} ? 1 : 0;
  252. if ($wasAvailable != $file->{'attr'}->{'available'}) {
  253. # Reset and extras for this file
  254. if (exists($EXTRAS{ $file->{'name'} })) {
  255. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  256. my $name = $file->{'name'} . '_' . $extra;
  257. $files{$name}{'last'} = $files{$name}{'value'};
  258. $files{$name}{'value'} = 0;
  259. }
  260. }
  261. # Determine which display device we have (if any)
  262. if (exists($DISPLAY_DEVS{ $file->{'name'} })) {
  263. $DISPLAY = $file->{'name'};
  264. if ($DEBUG) {
  265. print STDERR 'Selecting display device: ' . $DISPLAY . "\n";
  266. }
  267. }
  268. if ($DEBUG) {
  269. if ($file->{'attr'}->{'available'}) {
  270. print STDERR 'Added file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  271. } else {
  272. print STDERR 'Dropped file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  273. }
  274. }
  275. }
  276. }
  277. # Skip unavailable files
  278. if (!$file->{'attr'}->{'available'}) {
  279. next;
  280. }
  281. # Record the last update for MTIME files
  282. if ($file->{'attr'}->{'mtime'}) {
  283. my $mtime = mtime($file->{'path'});
  284. # All EXISTS files have MTIME set, and mtime returns 0 if the file does not exist, so we can overload this check
  285. if ($file->{'attr'}->{'exists'}) {
  286. if ($mtime > 0) {
  287. $file->{'update'} = $mtime;
  288. $file->{'value'} = 1;
  289. } elsif ($file->{'last'}) {
  290. $file->{'update'} = time();
  291. }
  292. } else {
  293. $file->{'update'} = $mtime;
  294. }
  295. if ($DEBUG) {
  296. print STDERR 'Mtime: ' . $file->{'name'} . ': ' . $file->{'value'} . ':' . $file->{'update'} . "\n";
  297. }
  298. }
  299. # Grab the state from STATUS files
  300. if ($file->{'attr'}->{'status'}) {
  301. my $text = '';
  302. {
  303. if (!open(my $fh, $file->{'path'})) {
  304. warn('Unable to open ' . $file->{'path'} . "\n");
  305. } else {
  306. local $/;
  307. $text = <$fh>;
  308. close($fh);
  309. }
  310. }
  311. # Parse the value for the file
  312. if ($file->{'attr'}->{'value'}) {
  313. $text =~ s/\n$//;
  314. $file->{'value'} = $text;
  315. } elsif ($file->{'attr'}->{'playing'}) {
  316. if ($text =~ /PlayStatus\:Playing/) {
  317. $file->{'value'} = 1;
  318. }
  319. } elsif ($file->{'attr'}->{'gui'}) {
  320. if (!($text =~ /ActiveWindowName\:Fullscreen video/)) {
  321. $file->{'value'} = 1;
  322. }
  323. } else {
  324. if ($text =~ /1/) {
  325. $file->{'value'} = 1;
  326. }
  327. }
  328. if ($DEBUG) {
  329. print STDERR 'Status: ' . $file->{'name'} . ': ' . $file->{'value'} . "\n";
  330. }
  331. # Handle extras, if any
  332. if (exists($EXTRAS{ $file->{'name'} })) {
  333. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  334. my $name = $file->{'name'} . '_' . $extra;
  335. $files{$name}{'last'} = $files{$name}{'value'};
  336. $files{$name}{'value'} = 0;
  337. $files{$name}{'update'} = $file->{'update'};
  338. if ($text =~ $EXTRAS{ $file->{'name'} }{$extra}) {
  339. $files{$name}{'value'} = $1;
  340. }
  341. if ($DEBUG) {
  342. print STDERR 'Status (extra): ' . $name . ': ' . $files{$name}{'value'} . "\n";
  343. }
  344. }
  345. }
  346. }
  347. }
  348. # Set the global update timestamp
  349. foreach my $file (values(%files)) {
  350. if ($file->{'update'} > $updateLast) {
  351. $updateLast = $file->{'update'};
  352. }
  353. }
  354. # Determine some intermediate state data
  355. my $playing = 0;
  356. if (exists($files{'PLAYING'}) && $files{'PLAYING'}->{'value'}) {
  357. $playing = 1;
  358. }
  359. my $video = 0;
  360. if (exists($files{'PLAYING_TYPE'}) && $files{'PLAYING_TYPE'}->{'value'} ne 'Audio') {
  361. $video = 1;
  362. } elsif (!exists($files{'PLAYING_TYPE'})) {
  363. $video = 1;
  364. }
  365. # Calculate the new state
  366. $stateLast = $state;
  367. if (!defined($DISPLAY) || !exists($files{$DISPLAY})) {
  368. # If there's no display the state is always PLAY or PAUSE, as indicated by the master
  369. if ($playing) {
  370. $state = 'PLAY';
  371. } else {
  372. $state = 'PAUSE';
  373. }
  374. } elsif ($files{$DISPLAY}->{'value'}) {
  375. # If a display exists and is on:
  376. # PLAY when video is active and playing
  377. # PAUSE any other time (including when audio is active)
  378. if ($playing && $video) {
  379. $state = 'PLAY';
  380. } else {
  381. $state = 'PAUSE';
  382. }
  383. } else {
  384. # If the display exists but is off, check the timeouts to determine MOTION vs. OFF
  385. my $timeSinceUpdate = time() - $updateLast;
  386. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  387. $state = 'OFF';
  388. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  389. if (exists($files{'NO_MOTION'}) && $files{'NO_MOTION'}->{'value'}) {
  390. $state = 'OFF';
  391. } else {
  392. $state = 'MOTION';
  393. }
  394. }
  395. }
  396. if ($state eq 'INIT') {
  397. $state = 'OFF';
  398. }
  399. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  400. foreach my $file (values(%files)) {
  401. if ($file->{'attr'}->{'clear_off'} && $file->{'value'} && $state eq 'OFF') {
  402. unlink($file->{'path'});
  403. $file->{'stauts'} = 0;
  404. if ($DEBUG) {
  405. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  406. }
  407. }
  408. }
  409. # Calculate the new status
  410. $statusLast = $status;
  411. {
  412. my @statTime = ();
  413. foreach my $file (values(%files)) {
  414. my $text = $file->{'value'};
  415. $text =~ s/\s/ /g;
  416. $text =~ s/\|/-/g;
  417. push(@statTime, $file->{'name'} . '|' . $text . '|' . $file->{'update'});
  418. }
  419. $status = "\n" . join("\n", @statTime);
  420. }
  421. # Clear EXISTS_CLEAR files immediately (but after we append their status)
  422. foreach my $file (values(%files)) {
  423. if ($file->{'attr'}->{'clear'} && $file->{'value'}) {
  424. unlink($file->{'path'});
  425. $file->{'stauts'} = 0;
  426. if ($DEBUG) {
  427. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  428. }
  429. }
  430. }
  431. # Force updates on a periodic basis
  432. if (time() - $pushLast > $PUSH_TIMEOUT) {
  433. $update = 1;
  434. }
  435. # Update on any status change
  436. foreach my $file (values(%files)) {
  437. if ($file->{'value'} ne $file->{'last'}) {
  438. $update = 1;
  439. last;
  440. }
  441. }
  442. # Force updates on any state change
  443. if ($stateLast ne $state || $statusLast ne $status) {
  444. if ($DEBUG) {
  445. print STDERR 'State change: ' . $stateLast . $statusLast . ' => ' . $state . $status . "\n";
  446. }
  447. $update = 1;
  448. }
  449. # Push the update
  450. if ($update) {
  451. # Note the push
  452. $pushLast = time();
  453. # Send notifications to all subscribers
  454. foreach my $sub (@subscribers) {
  455. # Drop subscribers that are not available
  456. if (!eval { $sub->{'socket'}->send($state . $status) }) {
  457. print STDERR 'Dropping bad socket from subscriber list: ' . $sub->{'path'} . "\n";
  458. my @new_subscribers = ();
  459. foreach my $new (@subscribers) {
  460. if ($new->{'socket'} eq $sub->{'socket'}) {
  461. next;
  462. }
  463. push(@new_subscribers, $new);
  464. }
  465. @subscribers = @new_subscribers;
  466. }
  467. }
  468. # Save the state and value to disk
  469. my ($fh, $tmp) = tempfile($DATA_DIR . 'STATE.XXXXXXXX', 'UNLINK' => 0);
  470. print $fh $state . "\n";
  471. close($fh);
  472. rename($tmp, $DATA_DIR . 'STATE');
  473. }
  474. }
  475. sub mtime($) {
  476. my ($file) = @_;
  477. my $mtime = 0;
  478. if (-r $file) {
  479. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), $mtime, undef(), undef(), undef()) = stat($file);
  480. }
  481. return $mtime;
  482. }