state.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 = '<NONE>';
  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 $file (keys(%MON_FILES)) {
  107. my %tmp = (
  108. 'name' => basename($file),
  109. 'type' => $MON_FILES{$file},
  110. 'path' => $DATA_DIR . $file,
  111. 'update' => 0,
  112. 'value' => 0,
  113. 'last' => 0,
  114. );
  115. # Allow absolute paths to override the $DATA_DIR path
  116. if ($file =~ /^\//) {
  117. $tmp{'path'} = $file;
  118. }
  119. # Record the directory name for folder monitoring
  120. $tmp{'dir'} = dirname($tmp{'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 ($tmp{'type'} =~ /\bSTATUS\b/i) {
  134. $attr{'status'} = 1;
  135. $attr{'mtime'} = 1;
  136. }
  137. if ($tmp{'type'} =~ /\bEXISTS\b/i) {
  138. $attr{'exists'} = 1;
  139. $attr{'mtime'} = 1;
  140. }
  141. if ($tmp{'type'} =~ /\bVALUE\b/i) {
  142. $attr{'status'} = 1;
  143. $attr{'value'} = 1;
  144. $attr{'mtime'} = 1;
  145. }
  146. if ($tmp{'type'} =~ /\bCLEAR\b/i) {
  147. $attr{'clear'} = 1;
  148. }
  149. if ($tmp{'type'} =~ /\bON\b/i) {
  150. $attr{'clear_off'} = 1;
  151. }
  152. if ($tmp{'type'} =~ /\bMTIME\b/i) {
  153. $attr{'mtime'} = 1;
  154. }
  155. if ($tmp{'type'} =~ /\bGUI\b/i) {
  156. $attr{'status'} = 1;
  157. $attr{'gui'} = 1;
  158. }
  159. if ($tmp{'type'} =~ /\bPLAYING\b/i) {
  160. $attr{'status'} = 1;
  161. $attr{'playing'} = 1;
  162. }
  163. $tmp{'attr'} = \%attr;
  164. # Push a hash ref
  165. $files{$file} = \%tmp;
  166. }
  167. # Delete any existing input files, to ensure our state is reset
  168. foreach my $file (values(%files)) {
  169. if (-e $file->{'path'}) {
  170. if ($DEBUG) {
  171. print STDERR 'Deleting ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  172. }
  173. unlink($file->{'path'});
  174. }
  175. }
  176. # Reset all dependents at starts
  177. system($RESET_CMD);
  178. # Subscribers
  179. my @subscribers = ();
  180. # State
  181. my $state = 'INIT';
  182. my $stateLast = $state;
  183. my $status = '';
  184. my $statusLast = $status;
  185. my $updateLast = 0;
  186. my $pushLast = 0;
  187. # Loop forever
  188. while (1) {
  189. # Provide a method to force updates even when the state does not change
  190. my $update = 0;
  191. # Check for queued commands
  192. my @ready_clients = $select->can_read($DELAY);
  193. foreach my $fh (@ready_clients) {
  194. # Grab the inbound text
  195. my $path = undef();
  196. $fh->recv($path, $MAX_CMD_LEN);
  197. $path =~ s/^\s+//;
  198. $path =~ s/\s+$//;
  199. if ($DEBUG) {
  200. print STDERR 'Got path: ' . $path . "\n";
  201. }
  202. # Only accept valid paths
  203. if (!-r $path) {
  204. print STDERR 'Invalid socket path: ' . $path . "\n";
  205. next;
  206. }
  207. # Open the new socket
  208. my $sub = eval { DMX::clientSock($path); };
  209. if (!$sub) {
  210. print STDERR 'Unable to open socket: ' . $path . ": ${@}\n";
  211. next;
  212. }
  213. # Add the socket to our subscriber list
  214. my %tmp = (
  215. 'path' => $path,
  216. 'socket' => $sub,
  217. );
  218. push(@subscribers, \%tmp);
  219. # Force an update
  220. $update = 1;
  221. }
  222. # Use opendir/readdir in each folder to ensure fresh results
  223. my %folders = ();
  224. foreach my $file (values(%files)) {
  225. if (!$folders{ $file->{'dir'} }) {
  226. my $dh = undef();
  227. if (opendir($dh, $file->{'dir'})) {
  228. if ($DEBUG) {
  229. print STDERR 'Refreshed folder: ' . $file->{'dir'} . "\n";
  230. }
  231. my @files = readdir($dh);
  232. closedir($dh);
  233. }
  234. $folders{ $file->{'dir'} } = 1;
  235. }
  236. }
  237. # Monitor files of all types
  238. foreach my $file (values(%files)) {
  239. # Skip "NONE" files -- they are data stores handled in other actions
  240. if ($file->{'type'} eq 'NONE') {
  241. next;
  242. }
  243. # Always record the previous status and clear the new one
  244. $file->{'last'} = $file->{'value'};
  245. $file->{'value'} = 0;
  246. # Track available/unavailable status in each cycle
  247. {
  248. my $wasAvailable = $file->{'attr'}->{'available'};
  249. $file->{'attr'}->{'available'} = -r $file->{'path'} ? 1 : 0;
  250. if ($wasAvailable != $file->{'attr'}->{'available'}) {
  251. # Reset and extras for this file
  252. if (exists($EXTRAS{ $file->{'name'} })) {
  253. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  254. my $name = $file->{'name'} . '_' . $extra;
  255. $files{$name}{'last'} = $files{$name}{'value'};
  256. $files{$name}{'value'} = 0;
  257. }
  258. }
  259. # Determine which display device we have (if any)
  260. if (exists($DISPLAY_DEVS{ $file->{'name'} })) {
  261. $DISPLAY = $file->{'name'};
  262. if ($DEBUG) {
  263. print STDERR 'Selecting display device: ' . $DISPLAY . "\n";
  264. }
  265. }
  266. if ($DEBUG) {
  267. if ($file->{'attr'}->{'available'}) {
  268. print STDERR 'Added file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  269. } else {
  270. print STDERR 'Dropped file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  271. }
  272. }
  273. }
  274. }
  275. # Skip unavailable files
  276. if (!$file->{'attr'}->{'available'}) {
  277. next;
  278. }
  279. # Record the last update for MTIME files
  280. if ($file->{'attr'}->{'mtime'}) {
  281. my $mtime = mtime($file->{'path'});
  282. # All EXISTS files have MTIME set, and mtime returns 0 if the file does not exist, so we can overload this check
  283. if ($file->{'attr'}->{'exists'}) {
  284. if ($mtime > 0) {
  285. $file->{'update'} = $mtime;
  286. $file->{'value'} = 1;
  287. } elsif ($file->{'last'}) {
  288. $file->{'update'} = time();
  289. }
  290. } else {
  291. $file->{'update'} = $mtime;
  292. }
  293. if ($DEBUG) {
  294. print STDERR 'Mtime: ' . $file->{'name'} . ': ' . $file->{'value'} . ':' . $file->{'update'} . "\n";
  295. }
  296. }
  297. # Grab the state from STATUS files
  298. if ($file->{'attr'}->{'status'}) {
  299. my $text = '';
  300. {
  301. if (!open(my $fh, $file->{'path'})) {
  302. warn('Unable to open ' . $file->{'path'} . "\n");
  303. } else {
  304. local $/;
  305. $text = <$fh>;
  306. close($fh);
  307. }
  308. }
  309. # Parse the value for the file
  310. if ($file->{'attr'}->{'value'}) {
  311. $text =~ s/\n$//;
  312. $file->{'value'} = $text;
  313. } elsif ($file->{'attr'}->{'playing'}) {
  314. if ($text =~ /PlayStatus\:Playing/) {
  315. $file->{'value'} = 1;
  316. }
  317. } elsif ($file->{'attr'}->{'gui'}) {
  318. if (!($text =~ /ActiveWindowName\:Fullscreen video/)) {
  319. $file->{'value'} = 1;
  320. }
  321. } else {
  322. if ($text =~ /1/) {
  323. $file->{'value'} = 1;
  324. }
  325. }
  326. if ($DEBUG) {
  327. print STDERR 'Status: ' . $file->{'name'} . ': ' . $file->{'value'} . "\n";
  328. }
  329. # Handle extras, if any
  330. if (exists($EXTRAS{ $file->{'name'} })) {
  331. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  332. my $name = $file->{'name'} . '_' . $extra;
  333. $files{$name}{'last'} = $files{$name}{'value'};
  334. $files{$name}{'value'} = 0;
  335. $files{$name}{'update'} = $file->{'update'};
  336. if ($text =~ $EXTRAS{ $file->{'name'} }{$extra}) {
  337. $files{$name}{'value'} = $1;
  338. }
  339. if ($DEBUG) {
  340. print STDERR 'Status (extra): ' . $name . ': ' . $files{$name}{'value'} . "\n";
  341. }
  342. }
  343. }
  344. }
  345. }
  346. # Set the global update timestamp
  347. foreach my $file (values(%files)) {
  348. if ($file->{'update'} > $updateLast) {
  349. $updateLast = $file->{'update'};
  350. }
  351. }
  352. # Calculate the new state
  353. $stateLast = $state;
  354. if ($DISPLAY && exists($files{$DISPLAY}) && $files{$DISPLAY}->{'value'}) {
  355. # We are always either playing or paused if the display is on
  356. # When we're playing "Audio" assume we are paused
  357. if ( (exists($files{'PLAYING'}) && $files{'PLAYING'}->{'value'})
  358. && ((exists($files{'PLAYING_TYPE'}) && $files{'PLAYING_TYPE'}->{'value'} ne 'Audio') || !exists($files{'PLAYING_TYPE'})))
  359. {
  360. $state = 'PLAY';
  361. } else {
  362. $state = 'PAUSE';
  363. }
  364. } else {
  365. # If the display is off, check the timeouts
  366. my $timeSinceUpdate = time() - $updateLast;
  367. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  368. $state = 'OFF';
  369. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  370. if (exists($files{'NO_MOTION'}) && $files{'NO_MOTION'}->{'value'}) {
  371. $state = 'OFF';
  372. } else {
  373. $state = 'MOTION';
  374. }
  375. }
  376. }
  377. if ($state eq 'INIT') {
  378. $state = 'OFF';
  379. }
  380. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  381. foreach my $file (values(%files)) {
  382. if ($file->{'attr'}->{'clear_off'} && $file->{'value'} && $state eq 'OFF') {
  383. unlink($file->{'path'});
  384. $file->{'stauts'} = 0;
  385. if ($DEBUG) {
  386. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  387. }
  388. }
  389. }
  390. # Calculate the new status
  391. $statusLast = $status;
  392. {
  393. my @statTime = ();
  394. foreach my $file (values(%files)) {
  395. my $text = $file->{'value'};
  396. $text =~ s/\s/ /g;
  397. $text =~ s/\|/-/g;
  398. push(@statTime, $file->{'name'} . '|' . $text . '|' . $file->{'update'});
  399. }
  400. $status = "\n" . join("\n", @statTime);
  401. }
  402. # Clear EXISTS_CLEAR files immediately (but after we append their status)
  403. foreach my $file (values(%files)) {
  404. if ($file->{'attr'}->{'clear'} && $file->{'value'}) {
  405. unlink($file->{'path'});
  406. $file->{'stauts'} = 0;
  407. if ($DEBUG) {
  408. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  409. }
  410. }
  411. }
  412. # Force updates on a periodic basis
  413. if (time() - $pushLast > $PUSH_TIMEOUT) {
  414. $update = 1;
  415. }
  416. # Update on any status change
  417. foreach my $file (values(%files)) {
  418. if ($file->{'value'} ne $file->{'last'}) {
  419. $update = 1;
  420. last;
  421. }
  422. }
  423. # Force updates on any state change
  424. if ($stateLast ne $state || $statusLast ne $status) {
  425. if ($DEBUG) {
  426. print STDERR 'State change: ' . $stateLast . $statusLast . ' => ' . $state . $status . "\n";
  427. }
  428. $update = 1;
  429. }
  430. # Push the update
  431. if ($update) {
  432. # Note the push
  433. $pushLast = time();
  434. # Send notifications to all subscribers
  435. foreach my $sub (@subscribers) {
  436. # Drop subscribers that are not available
  437. if (!eval { $sub->{'socket'}->send($state . $status) }) {
  438. print STDERR 'Dropping bad socket from subscriber list: ' . $sub->{'path'} . "\n";
  439. my @new_subscribers = ();
  440. foreach my $new (@subscribers) {
  441. if ($new->{'socket'} eq $sub->{'socket'}) {
  442. next;
  443. }
  444. push(@new_subscribers, $new);
  445. }
  446. @subscribers = @new_subscribers;
  447. }
  448. }
  449. # Save the state and value to disk
  450. my ($fh, $tmp) = tempfile($DATA_DIR . 'STATE.XXXXXXXX', 'UNLINK' => 0);
  451. print $fh $state . "\n";
  452. close($fh);
  453. rename($tmp, $DATA_DIR . 'STATE');
  454. }
  455. }
  456. sub mtime($) {
  457. my ($file) = @_;
  458. my $mtime = 0;
  459. if (-r $file) {
  460. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), $mtime, undef(), undef(), undef()) = stat($file);
  461. }
  462. return $mtime;
  463. }