state.pl 9.8 KB

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