state.pl 18 KB

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