state.pl 11 KB

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