state.pl 12 KB

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