require 'sinatra' require 'mqtt' require 'sqlite3' require 'date' require 'dm-core' require 'dm-timestamps' require 'dm-validations' require 'dm-migrations' set :public_folder, File.dirname(__FILE__) + '/public' set :bind, '::' DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/scarecrow.sqlite") class Temperature include DataMapper::Resource property :id, Serial property :timestamp, DateTime property :value, Float end class Humidity include DataMapper::Resource property :id, Serial property :timestamp, DateTime property :value, Float end def init DataMapper.auto_migrate! DataMapper.auto_upgrade! Thread.new do MQTT::Client.connect('192.168.0.16') do |c| c.subscribe('temperature', 'humidity') loop do while !c.queue_empty? do topic, message = c.get handle_msg(topic, message) end sleep 1 end end end end def handle_msg(topic, msg) puts "#{topic}: #{msg}" if topic == "humidity" handle_humidity_msg(msg) elsif topic == "temperature" handle_temp_message(msg) end end def handle_humidity_msg(msg) humidity = Humidity.create(timestamp: DateTime.now, value: msg) humidity.errors.each do |error| puts error end end def handle_temp_message(msg) temp = Temperature.create(timestamp: DateTime.now, value: msg) temp.errors.each do |error| puts error end end get '/' do send_file File.join(settings.public_folder, 'index.html') end get '/temperature' do temp = Temperature.last[:value] return "#{temp}" end get '/humidity' do temp = Humidity.last[:value] "#{temp}" end init