summaryrefslogtreecommitdiff
path: root/scarecrow.rb
blob: a5275159cad6cdd13ae154c3fc02d85379b81c9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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.59') 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')
    @temp_val = Temperature.last[:value]
    @humidity_val = Humidity.last[:value]
    temp_time = Temperature.last[:timestamp]
    humidity_time = Humidity.last[:timestamp]
    @time_formatted = temp_time.strftime("%A, %d %b %Y %l:%M %p")
    erb :index
    # return "#{temp_val}°C and #{humidity_val}% humidity at #{time_formatted}"
end

get '/temperature' do
    temp = Temperature.last[:value]
    return "#{temp}"
end

get '/humidity' do
    humidity = Humidity.last[:value]
    "#{humidity}"
end

init