#!/usr/bin/env ruby
#
# Author: Norbert Wigbels - foobla.wigbels.de/uber-foobla
#
# HotHotPiper continously reads the status of a
# reed contact attached to the Raspberry Pi GPIO
#
# The reed measures gas usage.
#
# A magig URL is formed and called; the url
# stores the sensor-data to wigbels.net
#
# todo: status-led
# 

#------------------------------------------
# Tainted mode 0-4
$SAFE=0

#------------------------------------------
require 'pi_piper'
include PiPiper

$mypath = File.expand_path(File.dirname(__FILE__))


def last_rrd_count
  val = 0.0
  handle = IO.popen("rrdtool lastupdate #{$mypath}/power.rrd")
  handle.each_line do |line|
    m = line.match("^[0-9]*: ([0-9.]*) [0-9.]*")
    if m
      val = m[1].to_f
      break
    end
  end
  return val
end


watch :pin => 4, :trigger => :falling do 
  puts('added 10 liter of gas to sensor-database')
  system("rrdtool update #{$mypath}/gas.rrd N:10")
end

watch :pin => 11, :trigger => :falling  do
  puts('updated power consumption')
  $counter = $counter + $trigger_step
  trigger_update = $trigger_step * 3600000.0
  system("rrdtool update #{$mypath}/power.rrd N:#{$counter}:#{trigger_update}")
end

$trigger_step = 1.0 / 96
$counter = last_rrd_count

PiPiper.wait
