state.pl 19 KB

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