A program to read a Phidget IR sensor and log pull-ups with Fitbit's API
at master 95 lines 2.2 kB view raw
1require "rubygems" 2require "phidgets-ffi" 3 4class Phidget 5 attr_accessor :cur_value, :state, :fitbit 6 7 # default values for each state to transition 8 STATE_IDLE_TO_PULLING_UP = 150 9 STATE_PULLING_UP_TO_PULLED_UP = 325 10 STATE_PULLING_UP_TO_IDLE = 200 11 STATE_PULLED_UP_TO_IDLE = 150 12 13 def initialize(parent) 14 @parent = parent 15 @state = :idle 16 @last_state_change = Time.now 17 @last_pullup = nil 18 @cur_time = nil 19 end 20 21 def main_loop 22 begin 23 Phidgets::InterfaceKit.new do |ifkit| 24 @parent.vputs "reading from Phidget #{ifkit.serial_number}" 25 26 ifkit.on_sensor_change do |device, input, value, obj| 27 @cur_time = Time.now 28 if input.index == 1 29 self.cur_value = value 30 end 31 end 32 33 sleep 34 end 35 36 rescue => e 37 @parent.eputs "exception in Phidget handler: #{e.message}" 38 sleep 3 39 retry 40 end 41 end 42 43 def cur_value=(value) 44 if @parent.config["debug"] 45 # XXX: direct this somewhere so it doesn't get muxed with chatter 46 STDOUT.puts "#{@cur_time.to_f},#{value}" 47 end 48 49 if @cur_time.to_i - @last_state_change.to_i > 10 && self.state != :idle 50 # stuck in previous state, unlikely we're still hanging there, reset 51 self.state = :idle 52 end 53 54 @cur_value = value 55 56 case self.state 57 when :idle 58 if value >= STATE_IDLE_TO_PULLING_UP 59 self.state = :pulling_up 60 end 61 62 when :pulling_up 63 if value >= STATE_PULLING_UP_TO_PULLED_UP 64 self.state = :pulled_up 65 elsif value <= STATE_PULLING_UP_TO_IDLE 66 self.state = :idle 67 end 68 69 when :pulled_up 70 if value <= STATE_PULLED_UP_TO_IDLE 71 self.state = :idle 72 end 73 end 74 end 75 76 def state=(state) 77 @last_state_change = @cur_time 78 79 if @state == state 80 return 81 end 82 83 @state = state 84 @parent.vputs "state is now #{state} (#{self.cur_value})" 85 86 if state == :pulled_up 87 if @last_pullup && (@cur_time.to_f - @last_pullup.to_f < 1.0) 88 @parent.vputs "ignoring bad sensor data (duplicate pull-up)" 89 else 90 @parent.log_pullup!(@cur_time) 91 @last_pullup = @cur_time 92 end 93 end 94 end 95end