state.pl 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. use IPC::System::Simple qw( system capture );
  9. # Local modules
  10. use Cwd qw(abs_path);
  11. use File::Basename qw(dirname);
  12. use lib dirname(abs_path($0));
  13. use DMX;
  14. # Prototypes
  15. sub mtime($);
  16. # User config
  17. my %DISPLAY_DEVS = ('TV' => 1, 'PROJECTOR' => 1);
  18. my $DISPLAY = undef();
  19. my $STATE_TIMEOUT = 180;
  20. my $EXISTS_TIMEOUT = 900;
  21. my $START_DELAY = 15;
  22. my %MON_FILES = ();
  23. # Host-specific config
  24. # This is necessary to avoid contention on shared disks
  25. my $HOST = Sys::Hostname::hostname();
  26. if ($HOST =~ /loki/i) {
  27. # Ensure the media path is available before we get going
  28. my $MEDIA_PATH = undef();
  29. {
  30. my $mount = $ENV{'HOME'} . '/bin/video/mediaPath';
  31. $MEDIA_PATH = capture($mount);
  32. }
  33. if (!$MEDIA_PATH || !-d $MEDIA_PATH) {
  34. die("Unable to access media path\n");
  35. }
  36. # Garage door opener
  37. $MON_FILES{ $MEDIA_PATH . '/DMX/cmd/GARAGE_CMD' } = 'EXISTS-LINE-CLEAR';
  38. }
  39. # Available state files
  40. {
  41. # Plex
  42. $MON_FILES{'PLEX'} = 'NONE';
  43. $MON_FILES{'GUI'} = 'NONE';
  44. $MON_FILES{'PLAYING'} = 'PLAYING';
  45. # RiffTrax
  46. $MON_FILES{'RIFF'} = 'LINE-NOUPDATE';
  47. # Motion detection
  48. $MON_FILES{'MOTION'} = 'MTIME';
  49. $MON_FILES{'MOTION_STAIRS'} = 'MTIME-NOUPDATE';
  50. $MON_FILES{'NO_MOTION'} = 'EXISTS-NOUPDATE';
  51. # Projector
  52. $MON_FILES{'PROJECTOR'} = 'STATUS';
  53. $MON_FILES{'PROJECTOR_COLOR'} = 'LINE-NOUPDATE';
  54. $MON_FILES{'PROJECTOR_INPUT'} = 'LINE-NOUPDATE';
  55. $MON_FILES{'PROJECTOR_LAMP'} = 'LINE-NOUPDATE';
  56. # Amplifier
  57. $MON_FILES{'AMPLIFIER'} = 'STATUS';
  58. $MON_FILES{'AMPLIFIER_VOL'} = 'LINE-NOUPDATE';
  59. $MON_FILES{'AMPLIFIER_MODE'} = 'LINE-NOUPDATE';
  60. $MON_FILES{'AMPLIFIER_INPUT'} = 'LINE-NOUPDATE';
  61. $MON_FILES{'AUDIO_AMP'} = 'EXISTS-ON';
  62. $MON_FILES{'STEREO_CMD'} = 'EXISTS-ON';
  63. # A/V Effects
  64. $MON_FILES{'LIGHTS'} = 'EXISTS-TIMEOUT';
  65. $MON_FILES{'BRIGHT'} = 'EXISTS-TIMEOUT';
  66. $MON_FILES{'RAVE'} = 'EXISTS';
  67. $MON_FILES{'EFFECT'} = 'EXISTS';
  68. # Equipment
  69. $MON_FILES{'FAN'} = 'LINE-NOUPDATE';
  70. $MON_FILES{'FAN_CMD'} = 'EXISTS-TIMEOUT';
  71. $MON_FILES{'LOCK'} = 'EXISTS-NOUPDATE';
  72. $MON_FILES{'ALARM'} = 'NONE';
  73. # OS State
  74. $MON_FILES{'FRONT_APP'} = 'LINE-NOUPDATE';
  75. $MON_FILES{'COLOR'} = 'LINE-NOUPDATE';
  76. $MON_FILES{'AUDIO'} = 'LINE-NOUPDATE';
  77. $MON_FILES{'AUDIO_STATE'} = 'LINE-NOUPDATE';
  78. # Lights
  79. $MON_FILES{'LED'} = 'LINE-NOUPDATE';
  80. $MON_FILES{'OVERHEAD'} = 'LINE-NOUPDATE';
  81. $MON_FILES{'ROPE'} = 'LINE-NOUPDATE';
  82. $MON_FILES{'STAIRS'} = 'LINE-NOUPDATE';
  83. # TV
  84. $MON_FILES{'TV'} = 'STATUS';
  85. $MON_FILES{'TV_VOL'} = 'LINE-NOUPDATE';
  86. $MON_FILES{'TV_INPUT'} = 'LINE-NOUPDATE';
  87. }
  88. my %EXTRAS = (
  89. 'PLAYING' => {
  90. 'URL' => qr/^file:(.+)$/m,
  91. 'YEAR' => qr/^year:(\d+)/m,
  92. 'SERIES' => qr/^showtitle:(.+)$/m,
  93. 'SEASON' => qr/^season:(\d+)/m,
  94. 'EPISODE' => qr/^episode:(\d+)/m,
  95. 'TITLE' => qr/^title:(.+)$/m,
  96. 'LENGTH' => qr/^duration:(\d+)/m,
  97. 'POSITION' => qr/^time:(\d+(?:\.\d+)?)/m,
  98. 'TYPE' => qr/^type:(.+)$/m,
  99. 'ALBUM' => qr/^album:(.+)$/m,
  100. 'ARTIST' => qr/^artist:(.+)$/m,
  101. 'SELECTION' => qr/^selection:(.+)$/m,
  102. 'WINDOW' => qr/^window:(.+)$/m,
  103. 'WINDOWID' => qr/^windowid:(\d+)/m,
  104. # Available, but big and mostly useless
  105. #'IMAGE' => qr/^fanart:(.+)$/m,
  106. #'THUMB' => qr/^thumbnail:(.+)$/m,
  107. }
  108. );
  109. # App config
  110. my $SOCK_TIMEOUT = 5;
  111. my $DATA_DIR = DMX::dataDir();
  112. my $CMD_FILE = 'STATE';
  113. my $MAX_CMD_LEN = DMX::maxCmdLen();
  114. my $RESET_CMD = $ENV{'HOME'} . '/bin/video/dmx/reset.sh';
  115. my $PUSH_TIMEOUT = 20;
  116. # Debug
  117. my $DEBUG = 0;
  118. if ($ENV{'DEBUG'}) {
  119. $DEBUG = 1;
  120. }
  121. # Command-line arguments
  122. my ($DELAY) = @ARGV;
  123. if (!$DELAY) {
  124. $DELAY = 0.5;
  125. }
  126. # Socket init
  127. my $select = DMX::stateSocket($CMD_FILE);
  128. # Add the extras to the main file list
  129. foreach my $file (keys(%EXTRAS)) {
  130. if (exists($MON_FILES{$file})) {
  131. foreach my $extra (keys(%{ $EXTRAS{$file} })) {
  132. $MON_FILES{ $file . '_' . $extra } = 'EXTRA';
  133. }
  134. }
  135. }
  136. # Init the file tracking structure
  137. my %files = ();
  138. foreach my $name (keys(%MON_FILES)) {
  139. my %file = (
  140. 'name' => basename($name),
  141. 'type' => $MON_FILES{$name},
  142. 'path' => $DATA_DIR . $name,
  143. 'update' => 0,
  144. 'value' => 0,
  145. 'last' => 0,
  146. );
  147. # Allow absolute paths to override the $DATA_DIR path
  148. if ($name =~ /^\//) {
  149. $file{'path'} = $name;
  150. }
  151. # Record the directory name for folder monitoring
  152. $file{'dir'} = dirname($file{'path'});
  153. # Set the attribute bits, for use in later update handling logic
  154. my %attr = (
  155. 'available' => 0,
  156. 'status' => 0,
  157. 'exists' => 0,
  158. 'value' => 0,
  159. 'line' => 0,
  160. 'clear' => 0,
  161. 'clear_off' => 0,
  162. 'mtime' => 0,
  163. 'playing' => 0,
  164. 'no_update' => 0,
  165. 'no_value' => 0,
  166. 'extra' => 0,
  167. );
  168. if ($file{'type'} =~ /\bSTATUS\b/i) {
  169. $attr{'status'} = 1;
  170. }
  171. if ($file{'type'} =~ /\bEXISTS\b/i) {
  172. $attr{'exists'} = 1;
  173. }
  174. if ($file{'type'} =~ /\bVALUE\b/i) {
  175. $attr{'value'} = 1;
  176. }
  177. if ($file{'type'} =~ /\bLINE\b/i) {
  178. $attr{'line'} = 1;
  179. }
  180. if ($file{'type'} =~ /\bCLEAR\b/i) {
  181. $attr{'clear'} = 1;
  182. }
  183. if ($file{'type'} =~ /\bON\b/i) {
  184. $attr{'clear_off'} = 1;
  185. }
  186. if ($file{'type'} =~ /\bTIMEOUT\b/i) {
  187. $attr{'clear_timeout'} = 1;
  188. }
  189. if ($file{'type'} =~ /\bMTIME\b/i) {
  190. $attr{'mtime'} = 1;
  191. }
  192. if ($file{'type'} =~ /\bPLAYING\b/i) {
  193. $attr{'playing'} = 1;
  194. }
  195. if ($file{'type'} =~ /\bNOUPDATE\b/i) {
  196. $attr{'no_update'} = 1;
  197. }
  198. if ($file{'type'} =~ /\bNONE\b/i) {
  199. $attr{'no_value'} = 1;
  200. }
  201. if ($file{'type'} =~ /\bEXTRA\b/i) {
  202. $attr{'extra'} = 1;
  203. }
  204. # Cross-match some data types for easy of use
  205. if ($attr{'extra'}) {
  206. $attr{'no_value'} = 1;
  207. }
  208. if ($attr{'no_value'}) {
  209. $attr{'no_update'} = 1;
  210. }
  211. if ($attr{'line'}) {
  212. $attr{'value'} = 1;
  213. }
  214. if ($attr{'value'} || $attr{'playing'}) {
  215. $attr{'status'} = 1;
  216. }
  217. if ($attr{'status'} || $attr{'exists'}) {
  218. $attr{'mtime'} = 1;
  219. }
  220. # Push ATTR into the file hash
  221. $file{'attr'} = \%attr;
  222. # Push FILE into the files hash
  223. $files{$name} = \%file;
  224. }
  225. # Delete any existing input files, to ensure our state is reset
  226. foreach my $file (values(%files)) {
  227. if (-e $file->{'path'}) {
  228. if ($DEBUG) {
  229. print STDERR 'Deleting ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  230. }
  231. unlink($file->{'path'});
  232. }
  233. }
  234. # Reset all dependents at starts
  235. system($RESET_CMD);
  236. # Subscribers
  237. my @subscribers = ();
  238. # State
  239. my $state = 'INIT';
  240. my $stateLast = $state;
  241. my $status = '';
  242. my $statusLast = $status;
  243. my $updateLast = 0;
  244. my $timeSinceUpdate = 0;
  245. my $startTime = time() + $START_DELAY;
  246. my $pushLast = 0;
  247. # Announce startup
  248. DMX::say('System initializing');
  249. # Loop forever
  250. while (1) {
  251. # Provide a method to force updates
  252. my $update = 0;
  253. # Avoid repeated calls to time()
  254. my $now = time();
  255. # Check for queued commands
  256. my @ready_clients = $select->can_read($DELAY);
  257. foreach my $fh (@ready_clients) {
  258. # Grab the inbound text
  259. my $path = undef();
  260. $fh->recv($path, $MAX_CMD_LEN);
  261. $path =~ s/^\s+//;
  262. $path =~ s/\s+$//;
  263. $path =~ s/\W/_/g;
  264. if ($DEBUG) {
  265. print STDERR 'Got path: ' . $path . "\n";
  266. }
  267. # Open the new socket
  268. my $sub = eval { DMX::clientSock($path); };
  269. if (!$sub) {
  270. print STDERR 'Unable to open socket: ' . $path . ": ${@}\n";
  271. next;
  272. }
  273. # Add the socket to our subscriber list
  274. my %tmp = (
  275. 'path' => $path,
  276. 'socket' => $sub,
  277. );
  278. push(@subscribers, \%tmp);
  279. # Send immediately when someone subscribes
  280. if (!$update) {
  281. if ($DEBUG) {
  282. print STDERR "New subscriber\n";
  283. }
  284. $update = 1;
  285. }
  286. }
  287. # Use opendir/readdir in each folder to ensure fresh results
  288. my %folders = ();
  289. foreach my $file (values(%files)) {
  290. if (!$folders{ $file->{'dir'} }) {
  291. my $dh = undef();
  292. opendir($dh, $file->{'dir'})
  293. or die('Unable to open directory: ' . $file->{'dir'});
  294. if ($DEBUG) {
  295. print STDERR 'Refreshed folder: ' . $file->{'dir'} . "\n";
  296. }
  297. my @files = readdir($dh);
  298. closedir($dh);
  299. $folders{ $file->{'dir'} } = 1;
  300. }
  301. }
  302. # Monitor files of all types
  303. foreach my $file (values(%files)) {
  304. # Record the previous status and clear the new one, unless the file is type EXTRA
  305. if (!$file->{'attr'}->{'extra'}) {
  306. $file->{'last'} = $file->{'value'};
  307. $file->{'value'} = 0;
  308. }
  309. # Skip NO_VALUE files -- their values are abstracted from other data
  310. if ($file->{'attr'}->{'no_value'}) {
  311. next;
  312. }
  313. # Track available/unavailable status in each cycle
  314. {
  315. my $wasAvailable = $file->{'attr'}->{'available'};
  316. $file->{'attr'}->{'available'} = -r $file->{'path'} ? 1 : 0;
  317. if ($wasAvailable != $file->{'attr'}->{'available'}) {
  318. # Reset and extras for this file
  319. if (exists($EXTRAS{ $file->{'name'} })) {
  320. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  321. my $name = $file->{'name'} . '_' . $extra;
  322. $files{$name}{'last'} = $files{$name}{'value'};
  323. $files{$name}{'value'} = 0;
  324. }
  325. }
  326. # Determine which display device we have (if any)
  327. if (exists($DISPLAY_DEVS{ $file->{'name'} })) {
  328. $DISPLAY = $file->{'name'};
  329. if ($DEBUG) {
  330. print STDERR 'Selecting display device: ' . $DISPLAY . "\n";
  331. }
  332. }
  333. if ($DEBUG) {
  334. if ($file->{'attr'}->{'available'}) {
  335. print STDERR 'Added file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  336. } else {
  337. print STDERR 'Dropped file ' . $file->{'name'} . ': ' . $file->{'path'} . "\n";
  338. }
  339. }
  340. }
  341. }
  342. # Skip unavailable files
  343. if (!$file->{'attr'}->{'available'}) {
  344. next;
  345. }
  346. # Record the last update for MTIME files
  347. if ($file->{'attr'}->{'mtime'}) {
  348. my $mtime = mtime($file->{'path'});
  349. # All EXISTS files have MTIME set, and mtime returns 0 if the file does not exist, so we can overload this check
  350. if ($file->{'attr'}->{'exists'}) {
  351. if ($mtime > 0) {
  352. $file->{'update'} = $mtime;
  353. $file->{'value'} = 1;
  354. } elsif ($file->{'last'}) {
  355. $file->{'update'} = $now;
  356. }
  357. } else {
  358. $file->{'update'} = $mtime;
  359. # Set the value if the update is recent -- VALUE and STATUS will overwrite as needed
  360. if ($mtime >= $now) {
  361. $file->{'value'} = 1;
  362. }
  363. }
  364. if ($DEBUG) {
  365. print STDERR 'Mtime: ' . $file->{'name'} . ': ' . $file->{'value'} . ':' . $file->{'update'} . "\n";
  366. }
  367. }
  368. # Grab the state from STATUS files (including VALUE files)
  369. if ($file->{'attr'}->{'status'}) {
  370. # Overwrite the mtime-based value
  371. $file->{'value'} = 0;
  372. my $text = '';
  373. {
  374. if (!open(my $fh, $file->{'path'})) {
  375. warn('Unable to open ' . $file->{'path'} . "\n");
  376. } else {
  377. local $/;
  378. $text = <$fh>;
  379. close($fh);
  380. }
  381. }
  382. # Parse the value for the file
  383. if ($file->{'attr'}->{'value'}) {
  384. if ($file->{'attr'}->{'line'}) {
  385. ($text) = $text =~ /^([^\n]+)\s*\n/;
  386. } else {
  387. $text =~ s/\s+$//;
  388. }
  389. $file->{'value'} = $text;
  390. } elsif ($file->{'attr'}->{'playing'}) {
  391. if ($text =~ /^playing:1/m) {
  392. $file->{'value'} = 1;
  393. }
  394. } else {
  395. if ($text =~ /1/) {
  396. $file->{'value'} = 1;
  397. }
  398. }
  399. if ($DEBUG) {
  400. print STDERR 'Status: ' . $file->{'name'} . ': ' . $file->{'value'} . "\n";
  401. }
  402. # Handle extras, if any
  403. if (exists($EXTRAS{ $file->{'name'} })) {
  404. foreach my $extra (keys(%{ $EXTRAS{ $file->{'name'} } })) {
  405. my $name = $file->{'name'} . '_' . $extra;
  406. $files{$name}{'last'} = $files{$name}{'value'};
  407. $files{$name}{'value'} = 0;
  408. $files{$name}{'update'} = $file->{'update'};
  409. if ($text =~ $EXTRAS{ $file->{'name'} }{$extra}) {
  410. $files{$name}{'value'} = $1;
  411. }
  412. if ($DEBUG) {
  413. print STDERR "\t" . $name . ': ' . $files{$name}{'value'} . "\n";
  414. }
  415. }
  416. }
  417. }
  418. }
  419. # Simulate the old GUI indicator
  420. {
  421. my $gui = 0;
  422. if (exists($files{'PLAYING_WINDOW'}) && $files{'PLAYING_WINDOW'}->{'value'} ne 'Fullscreen video') {
  423. $gui = 1;
  424. }
  425. $files{'GUI'}->{'value'} = $gui;
  426. }
  427. if (exists($files{'PLAYING'})) {
  428. $files{'GUI'}->{'update'} = $files{'PLAYING'}->{'update'};
  429. }
  430. # Ignore the MOTION file if NO_MOTION is set
  431. if (exists($files{'NO_MOTION'}) && $files{'NO_MOTION'}->{'value'}) {
  432. if (exists($files{'MOTION'})) {
  433. $files{'MOTION'}->{'value'} = 0;
  434. $files{'MOTION'}->{'update'} = 0;
  435. }
  436. }
  437. # Set the global update timestamp, excluding files marked NOUPDATE
  438. foreach my $file (values(%files)) {
  439. if ( $file->{'update'} > $updateLast
  440. && !$file->{'attr'}->{'no_update'}
  441. && $file->{'update'} > $startTime)
  442. {
  443. $updateLast = $file->{'update'};
  444. }
  445. }
  446. $timeSinceUpdate = $now - $updateLast;
  447. # Calculate the PLEX state
  448. if (exists($files{'FRONT_APP'})) {
  449. if ( $files{'FRONT_APP'}->{'value'} =~ 'com.plexapp.plexhometheater'
  450. || $files{'FRONT_APP'}->{'value'} eq 'com.apple.ScreenSaver.Engine')
  451. {
  452. $files{'PLEX'}->{'value'} = 1;
  453. }
  454. }
  455. if ($files{'PLEX'}->{'last'} != $files{'PLEX'}->{'value'}) {
  456. $files{'PLEX'}->{'update'} = $now;
  457. }
  458. # Determine some intermediate state data
  459. my $playing = 0;
  460. if (exists($files{'PLAYING'}) && $files{'PLAYING'}->{'value'}) {
  461. $playing = 1;
  462. }
  463. my $video = 0;
  464. if (exists($files{'PLAYING_TYPE'}) && $files{'PLAYING_TYPE'}->{'value'} ne 'audio') {
  465. $video = 1;
  466. } elsif (!exists($files{'PLAYING_TYPE'})) {
  467. $video = 1;
  468. }
  469. # Non-plex apps are always "playing" and "video"
  470. if (exists($files{'PLEX'}) && !$files{'PLEX'}->{'value'}) {
  471. $playing = 1;
  472. $video = 1;
  473. }
  474. # Calculate the new state
  475. $stateLast = $state;
  476. if (!defined($DISPLAY) || !exists($files{$DISPLAY})) {
  477. # If there's no display the state is always PLAY or PAUSE, as indicated by the master
  478. if ($playing) {
  479. $state = 'PLAY';
  480. } else {
  481. $state = 'PAUSE';
  482. }
  483. } elsif ($files{$DISPLAY}->{'value'}) {
  484. # If a display exists and is on:
  485. # PLAY when video is active and playing
  486. # PAUSE any other time (including when audio is active)
  487. if ($playing && $video) {
  488. $state = 'PLAY';
  489. } else {
  490. $state = 'PAUSE';
  491. }
  492. } else {
  493. # If the display exists but is off, check the timeouts to determine MOTION vs. OFF
  494. if ($timeSinceUpdate > $STATE_TIMEOUT) {
  495. $state = 'OFF';
  496. } elsif ($timeSinceUpdate < $STATE_TIMEOUT) {
  497. $state = 'MOTION';
  498. }
  499. }
  500. if ($state eq 'INIT') {
  501. $state = 'OFF';
  502. }
  503. # ALARM if LOCK exists and the master state is not OFF or any motion exists
  504. {
  505. my $alarm = 0;
  506. if (exists($files{'LOCK'}) && $files{'LOCK'}->{'value'}) {
  507. if ( $state ne 'OFF'
  508. || (exists($files{'MOTION'}) && $files{'MOTION'}->{'value'})
  509. || (exists($files{'MOTION_STAIRS'}) && $files{'MOTION_STAIRS'}->{'value'}))
  510. {
  511. $alarm = 1;
  512. }
  513. }
  514. if (!exists($files{'ALARM'}->{'value'}) || $files{'ALARM'}->{'value'} != $alarm) {
  515. $files{'ALARM'}->{'update'} = $now;
  516. }
  517. $files{'ALARM'}->{'value'} = $alarm;
  518. }
  519. # Clear EXISTS_ON files when the main state is "OFF" (and before we append their status)
  520. foreach my $file (values(%files)) {
  521. if ( $file->{'attr'}->{'clear_off'}
  522. && $file->{'value'}
  523. && $state eq 'OFF')
  524. {
  525. unlink($file->{'path'});
  526. $file->{'status'} = 0;
  527. if ($DEBUG) {
  528. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  529. }
  530. }
  531. }
  532. # Clear EXISTS_TIMEOUT files when the main state is "OFF" and EXISTS_TIMEOUT has expired (and before we append their status)
  533. foreach my $file (values(%files)) {
  534. if ( $file->{'attr'}->{'clear_timeout'}
  535. && $file->{'value'}
  536. && $state eq 'OFF'
  537. && $timeSinceUpdate > $EXISTS_TIMEOUT)
  538. {
  539. unlink($file->{'path'});
  540. $file->{'status'} = 0;
  541. if ($DEBUG) {
  542. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  543. }
  544. }
  545. }
  546. # Calculate the new status
  547. $statusLast = $status;
  548. {
  549. my @statTime = ();
  550. foreach my $file (values(%files)) {
  551. my $text = $file->{'value'};
  552. $text =~ s/\s/ /g;
  553. $text =~ s/\|/-/g;
  554. push(@statTime, $file->{'name'} . '|' . $text . '|' . $file->{'update'});
  555. }
  556. $status = "\n" . join("\n", @statTime);
  557. }
  558. # Clear EXISTS_CLEAR files immediately (but after we append their status)
  559. foreach my $file (values(%files)) {
  560. if ($file->{'attr'}->{'clear'} && $file->{'value'}) {
  561. unlink($file->{'path'});
  562. $file->{'status'} = 0;
  563. if ($DEBUG) {
  564. print STDERR 'Clearing exists flag for: ' . $file->{'name'} . "\n";
  565. }
  566. }
  567. }
  568. # Update on a periodic basis, so we don't timeout
  569. if (!$update && $now - $pushLast > $PUSH_TIMEOUT) {
  570. if ($DEBUG) {
  571. print STDERR "Periodic update\n";
  572. }
  573. $update = 1;
  574. }
  575. # Update on a master state change
  576. if (!$update && $stateLast ne $state) {
  577. if ($DEBUG) {
  578. print STDERR 'State change: ' . $stateLast . ' => ' . $state . "\n";
  579. }
  580. $update = 1;
  581. }
  582. # Update on any mtime change
  583. if (!$update) {
  584. foreach my $file (values(%files)) {
  585. if ($file->{'update'} > $pushLast) {
  586. if ($DEBUG) {
  587. print STDERR 'Mtime change: ' . $file->{'name'} . ' (' . $file->{'update'} . ")\n";
  588. }
  589. $update = 1;
  590. last;
  591. }
  592. }
  593. }
  594. # Update on any value change
  595. if (!$update) {
  596. foreach my $file (values(%files)) {
  597. if ($file->{'value'} ne $file->{'last'}) {
  598. if ($DEBUG) {
  599. print STDERR 'Value change: ' . $file->{'name'} . ' (' . $file->{'last'} . ' => ' . $file->{'value'} . ")\n";
  600. }
  601. $update = 1;
  602. last;
  603. }
  604. }
  605. }
  606. # Push the update
  607. if ($update) {
  608. # Note the push
  609. $pushLast = $now;
  610. # Send notifications to all subscribers
  611. my $msg = $state . $status;
  612. if ($DEBUG) {
  613. print STDERR '<STATE (' . length($msg) . ")>\n" . $msg . "\n<END STATE>\n\n";
  614. }
  615. foreach my $sub (@subscribers) {
  616. # Drop subscribers that are not available
  617. if (!eval { $sub->{'socket'}->send($state . $status) }) {
  618. print STDERR 'Dropping bad socket from subscriber list: ' . $sub->{'path'} . "\n";
  619. my @new_subscribers = ();
  620. foreach my $new (@subscribers) {
  621. if ($new->{'socket'} eq $sub->{'socket'}) {
  622. next;
  623. }
  624. push(@new_subscribers, $new);
  625. }
  626. @subscribers = @new_subscribers;
  627. }
  628. }
  629. # Save the state and value to disk
  630. my ($fh, $tmp) = tempfile($DATA_DIR . 'STATE.XXXXXXXX', 'UNLINK' => 0);
  631. print $fh $state . "\n";
  632. close($fh);
  633. rename($tmp, $DATA_DIR . 'STATE');
  634. }
  635. }
  636. sub mtime($) {
  637. my ($file) = @_;
  638. my $mtime = 0;
  639. if (-r $file) {
  640. (undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), undef(), $mtime, undef(), undef(), undef()) = stat($file);
  641. }
  642. return $mtime;
  643. }