Class: MyFirmataPluginPir

Inherits:
Object
  • Object
show all
Defined in:
lib/myfirmata-plugin-pir.rb

Overview

note: the conditional statement for publishing a notice was based on the code from the humble_rpi-plugin-pir gem

Instance Method Summary collapse

Constructor Details

#initialize(arduino, settings: {}, variables: {}) ⇒ MyFirmataPluginPir

Returns a new instance of MyFirmataPluginPir.



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/myfirmata-plugin-pir.rb', line 17

def initialize(arduino, settings: {}, variables: {})
  
  @arduino = arduino
  @settings, @variables = settings, {debug: false}.merge(variables)
  @debug = @variables[:debug
                      ]
  @pinx = @settings[:pin] || 2

  @arduino.pin_mode @pinx, ArduinoFirmata::INPUT
  @duration = settings[:duration] || '1 minute'
  
end

Instance Method Details

#startObject Also known as: on_start



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/myfirmata-plugin-pir.rb', line 30

def start()
       
  count = 0
  
  duration = @duration    
  puts 'duration: ' + duration.inspect if @debug
  notifier = @variables[:notifier]
  topic = @variables[:device_id]
  msg = @settings[:msg] || 'motion'    
  pinx = @pinx
  threshold = if @settings[:threshold] then
    @settings[:threshold]
  else
    ChronicDuration.parse(duration) > 30 ? 5 : 0
  end
  
  t1 = Time.now - (ChronicDuration.parse(duration) + 10)   
  puts 't1: ' + t1.inspect if @debug
  
  puts 'ready to detect PIR sensor'    
  
  debug = @debug
  
  @arduino.on :digital_read do |pin, high|

    if pin == pinx and high then
              
      count += 1
      puts 'count: ' + count.inspect if debug

      if Time.now > t1 + ChronicDuration.parse(duration)  then

        if count > threshold then
          
          
          fqm = if ChronicDuration.parse(duration) == 1 then
            "%s/motion: detected within the past second" % topic
          elsif count == 1
            "%s/motion: detected once within the past %s"% [topic, duration]
          elsif count == 2
            "%s/motion: detected twice within the past %s" % \
              [topic, duration]
          else
            "%s/motion: detected %s times within the past %s" % \
              [topic, count, duration]
          end
          
          notifier.notice fqm 
        end
        t1 = Time.now
        count = 0
      end        
      
    end
  end

end