state.pl 13 KB

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