require 'mqtt'
require 'uri'
require 'json'

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

File.readlines("/etc/default/mqtttemp").each do |line|
  values = line.split("=")
  ENV[values[0]] = values[1]
end

# Create a hash with the connection parameters from the URL
uri = URI.parse ENV['CLOUDMQTT_URL']
conn_opts = {
    remote_host: uri.host,
    remote_port: uri.port,
    username: uri.user,
    password: uri.password
}
topic = uri.path[1, uri.path.length] || 'tele/enklave/SENSOR'

Thread.new do
  MQTT::Client.connect(conn_opts) do |c|
      c.get(topic) do |t, message|
            puts "#{t}: #{message}"
            my_hash = JSON.parse(message)
            temperature = my_hash["SI7021"]["Temperature"]
            humidity = my_hash["SI7021"]["Humidity"]
            rrddata = "N:#{temperature}:U:U:U:U:U:U:U:U:#{humidity}:U:U:U:U:U:U:U:U" 
            puts rrddata
            system("rrdtool update #{mypath}/mqtttemp.rrd #{rrddata}")
      end
  end
end

sleep
