amplifierPower.pl 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use IO::Socket::UNIX;
  5. use POSIX qw(ceil floor);
  6. # App config
  7. my $DELAY = 5;
  8. my $TIMEOUT = 5;
  9. my $TEMP_DIR = `getconf DARWIN_USER_TEMP_DIR`;
  10. chomp($TEMP_DIR);
  11. my $DATA_DIR = $TEMP_DIR . 'plexMonitor/';
  12. my $CMD_FILE = $DATA_DIR . 'AMPLIFIER.socket';
  13. # Debug
  14. my $DEBUG = 0;
  15. if ($ENV{'DEBUG'}) {
  16. $DEBUG = 1;
  17. }
  18. # Sanity check
  19. if (!-d $DATA_DIR || !-S $CMD_FILE) {
  20. die("Bad config\n");
  21. }
  22. # Socket init
  23. my $sock = IO::Socket::UNIX->new(
  24. 'Peer' => $CMD_FILE,
  25. 'Type' => SOCK_DGRAM,
  26. 'Timeout' => $TIMEOUT
  27. ) or die('Unable to open socket: ' . $CMD_FILE . ": ${@}\n");
  28. # State
  29. my $state = 'INIT';
  30. my $stateLast = $state;
  31. my $projector = 0;
  32. # Loop forever
  33. while (1) {
  34. # Monitor the PROJECTOR file for state only
  35. {
  36. $projector = 0;
  37. my $fh;
  38. open($fh, $DATA_DIR . 'PROJECTOR')
  39. or die("Unable to open PROJECTOR\n");
  40. my $text = <$fh>;
  41. close($fh);
  42. if ($text =~ /1/) {
  43. $projector = 1;
  44. }
  45. if ($DEBUG) {
  46. print STDERR 'Projector: ' . $projector . "\n";
  47. }
  48. }
  49. # Monitor the AMPLIFIER file for state only
  50. {
  51. $stateLast = 'OFF';
  52. my $fh;
  53. open($fh, $DATA_DIR . 'AMPLIFIER')
  54. or die("Unable to open AMPLIFIER\n");
  55. my $text = <$fh>;
  56. close($fh);
  57. if ($text =~ /1/) {
  58. $stateLast = 'ON';
  59. }
  60. if ($DEBUG) {
  61. print STDERR 'Amplifier: ' . $stateLast . "\n";
  62. }
  63. }
  64. # Calculate the new state -- track the projector power state
  65. if ($projector) {
  66. $state = 'ON';
  67. } else {
  68. $state = 'OFF';
  69. }
  70. # If the state changed, do something about if
  71. if ($state ne $stateLast) {
  72. if ($DEBUG) {
  73. print STDERR 'State change: ' . $stateLast . ' => ' . $state . "\n";
  74. }
  75. if ($state eq 'OFF' || $state eq 'ON') {
  76. $sock->send($state)
  77. or die('Unable to write command to socket: ' . $CMD_FILE . ': ' . $state . ": ${!}\n");
  78. }
  79. # Reset to TV @ 5.1 at power on
  80. if ($state eq 'ON') {
  81. # Wait for the amp to boot
  82. sleep($DELAY);
  83. $sock->send('TV')
  84. or die('Unable to write command to socket: ' . $CMD_FILE . ': TV' . ": ${!}\n");
  85. $sock->send('SURROUND')
  86. or die('Unable to write command to socket: ' . $CMD_FILE . ': SURROUND' . ": ${!}\n");
  87. }
  88. }
  89. # Wait and loop
  90. sleep($DELAY);
  91. }
  92. # Cleanup
  93. $sock->close();
  94. undef($sock);
  95. exit(0);