#!/usr/bin/env ruby
#
# Author: Norbert Wigbels - foobla.wigbels.de/uber-foobla
#
# HotColdRain continously reads output of USB-WDE1
# and pushes data to mosquitto-db
#
# todos: 
# 

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


#------------------------------------------
require 'logger'
require 'serialport'
require 'mqtt'

#------------------------------------------
class HotColdRain < Logger::Application
  attr_accessor :temp1, :humidity1, :serialport, :mypath

  def initialize(application_name)
    super(application_name)
    @serialport = SerialPort.new("/dev/ttyUSB0", 9600, 8, 1, SerialPort::NONE)
    @mypath = File.expand_path(File.dirname(__FILE__))
  end

  def logOutReadableData(datagrams)
    puts "TemperaturUnten: " + datagrams[3]
    puts "LuftfeuchtigkeitUnten: " + datagrams[11]
    puts
    puts "TemperaturOben: " + datagrams[4]
    puts "LuftfeuchtigkeitOben: " + datagrams[12]
    puts        
    puts "TemperaturAussen: " + datagrams[19]
    puts "LuftfeuchtigkeitAussen: " + datagrams[20]
    puts "Windgeschwindigkeit km/h: " + datagrams[21]
    puts "Niederschlag: " + datagrams[22]
    puts "Regen ja/nein: " + datagrams[23]        
    puts "---------------------"
  end

  def run
    begin
      while true do
        openformat = @serialport.readline
        #openformat = "$1;1;;21,3;20,0;;;;;;;50;55;;;;;;;4,9;74;3,0;6;0;0"
        datagrams = openformat.split(';')

        logOutReadableData(datagrams)

        # $1;1;;21,3;20,0;;;;;;;50;55;;;;;;;4,9;74;3,0;6;0;0
        # extract only data
        # then replace empty data with U
        # then localize float value
        # finally prepare updatestring for rrdtool
        datagrams = datagrams.values_at(3..23)
        datagrams.collect! { |element| (element.empty?) ? "U" : element }
        datagrams.collect! { |element| (element.include? ',') ? element.sub!(',','.') : element }
        rrddata = 'N:'+datagrams.join(':')

        system("rrdtool update #{mypath}/weather.rrd #{rrddata}")

        # MQTT::Client.connect('mqtt://notwist:pixies@wigbels.net') do |c|
        #   c.publish('oben/temperatur', datagrams[0])
        # end
      end
      @serialport.close
    rescue => msg
      log(ERROR, "error: #{msg}")
      retry
    ensure
      @serialport.close
    end
  end
end


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





