#!/usr/bin/env ruby
#
# Author: Norbert Wigbels - foobla.wigbels.de/uber-foobla
#
# HotHotRead continously reads the status of a
# reed contact attached to the avr-net-io
#
# 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 'logger'
require 'socket'
require 'net/http'

#------------------------------------------
class HotHotRead < Logger::Application
  attr_accessor :socket, :socketaddr

  def initialize(application_name)
    super(application_name)
    @socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
    @sockaddr = Socket.sockaddr_in(2701, '192.168.14.42')
  end

  def run
    begin
      @socket.connect(@sockaddr)
      high2low = false;
      while true do
        @socket.print "io get pin 0\r\n"
        rawdata = @socket.recvfrom(128)
        # data contains "port 0: 0xfe"; extract last part
        data = rawdata.to_s.split(" ")[2]
        # we are only interested in the changes from high to low of the reed sensor
        if (data=="0xff")
          high2low = true
        else
          if (high2low==true)
            high2low = false
            Net::HTTP.get(URI.parse('http://www.wigbels.net/cgi-bin/hhw.rb?sensorid=1&data=10'))
            # fixme: response.body auswerten
            # bei fehler, lokales backlog schreibe 
            log(INFO, 'added 100 liter of gas to sensor-database')
          end
        end
        sleep(0.2)
      end
      # and terminate the connection when we're done
    rescue => msg
      log(ERROR, "error: #{msg}")
      retry
    ensure
      @socket.close
    end
    #puts "Filename: "+__FILE__.to_s
    #puts "Linenumber: "+__LINE__.to_s
    #log(WARN, 'warning',  'mymethod' )
    #@log.error('my_method2') { 'Error!' }
  end
end


#------------------------------------------
status = HotHotRead.new("HotHotRead").start

#if status != 0
#  puts "Some error occured."
#end
