state.pl 12 KB

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