state.pl 18 KB

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