oil.pl 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Local modules
  5. use Cwd qw(abs_path);
  6. use File::Basename qw(dirname);
  7. use lib dirname(abs_path($0));
  8. use DMX;
  9. # User config
  10. my $MOTION_TIMEOUT = 120;
  11. my %DIM = (
  12. 'OFF' => [ { 'channel' => 20, 'value' => 0, 'time' => 0 }, ],
  13. 'ON' => [ { 'channel' => 20, 'value' => 255, 'time' => 0 }, ],
  14. );
  15. # App config
  16. my $DATA_DIR = DMX::dataDir();
  17. my $STATE_SOCK = 'OIL';
  18. my $OUTPUT_FILE = $DATA_DIR . $STATE_SOCK;
  19. my $PUSH_TIMEOUT = 20;
  20. my $PULL_TIMEOUT = $PUSH_TIMEOUT * 3;
  21. my $DELAY = $PULL_TIMEOUT / 2;
  22. # Debug
  23. my $DEBUG = 0;
  24. if ($ENV{'DEBUG'}) {
  25. $DEBUG = 1;
  26. }
  27. # State
  28. my $state = 'OFF';
  29. my $stateLast = $state;
  30. my %exists = ();
  31. my %mtime = ();
  32. my $pushLast = 0;
  33. my $pullLast = time();
  34. my $update = 0;
  35. # Always force the heater into OFF at launch
  36. $state = 'OFF';
  37. DMX::applyDataset($DIM{$state}, $state, $OUTPUT_FILE);
  38. # Sockets
  39. DMX::stateSocket($STATE_SOCK);
  40. DMX::stateSubscribe($STATE_SOCK);
  41. # Loop forever
  42. while (1) {
  43. # State is calculated; use newState to gather data
  44. my $newState = $state;
  45. # Wait for state updates
  46. my $cmdState = DMX::readState($DELAY, \%exists, \%mtime, undef());
  47. # Avoid repeated calls to time()
  48. my $now = time();
  49. # Record only valid states
  50. if (defined($cmdState)) {
  51. $newState = $cmdState;
  52. $pullLast = $now;
  53. }
  54. # Die if we don't see regular updates
  55. if ($now - $pullLast > $PULL_TIMEOUT) {
  56. die('No update on state socket in past ' . $PULL_TIMEOUT . " seconds. Exiting...\n");
  57. }
  58. # Calculate the new state
  59. $stateLast = $state;
  60. if ($mtime{'MOTION_GARAGE'} > $now - $MOTION_TIMEOUT) {
  61. $newState = 'ON';
  62. } else {
  63. $newState = 'OFF';
  64. }
  65. $state = $newState;
  66. # Force updates on a periodic basis
  67. if (!$update && $now - $pushLast > $PUSH_TIMEOUT) {
  68. if ($DEBUG) {
  69. print STDERR "Forcing periodic update\n";
  70. }
  71. $update = 1;
  72. }
  73. # Force updates on any state change
  74. if (!$update && $stateLast ne $state) {
  75. if ($DEBUG) {
  76. print STDERR 'State change: ' . $stateLast . ' => ' . $state . "\n";
  77. }
  78. $update = 1;
  79. }
  80. # Update the lighting
  81. if ($update) {
  82. # Update
  83. DMX::applyDataset($DIM{$state}, $state, $OUTPUT_FILE);
  84. # Update the push time
  85. $pushLast = $now;
  86. # Clear the update flag
  87. $update = 0;
  88. }
  89. }