state.pl 11 KB

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