-
Notifications
You must be signed in to change notification settings - Fork 0
/
receiver.rb
executable file
·124 lines (106 loc) · 2.5 KB
/
receiver.rb
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#!/usr/bin/env ruby
require 'net/http'
require 'rexml/document'
require 'date'
require 'aws-sdk'
require 'serialport'
require 'pry'
BAROMETER_HIGHT_METERS = 110;
GAS_OFFSET = 203820;
POWER_OFFSET = 1939560;
@dynamo = Aws::DynamoDB::Client.new(
region: 'us-east-1'
)
def calculate_pressure(val)
#Pressure drops 12 Pa per 1m;
#translate result to hPa
(val + BAROMETER_HIGHT_METERS * 12) / 100
end
def calculate_kwh()
end
def request_uv
begin
xml = Net::HTTP.get('www.arpansa.gov.au', '/uvindex/realtime/xml/uvvalues.xml')
doc = REXML::Document.new(xml)
doc.elements.each('stations/location') do |p|
if p.attributes['id'] == 'sydney'
ind = p.get_text('index').to_s
stat = p.get_text('status').to_s
dat = DateTime.parse(p.get_text('utcdatetime').to_s).to_time.to_i
return ind if Time.new_to_i - dat <= 120 && stat == 'OK'
end
end
rescue
end
-1
end
@last_value = {}
@process = {
#Sensors
'2' => lambda do |v|
[v[0]-308,request_uv]
end,
'3' => lambda do |v|
t = v[0] - 0.5
h = v[1] - 1.6
[t.round(1), h.round(1)]
end,
'4' => lambda do |v|
# Magic correction coefficients calculated experementally
t = v[0] - 0.5
h = v[1] - 3
[t.round(1), h.round(1)]
end,
'5' => lambda do |v|
v[2] = calculate_pressure(v[2])
[v[0].round(1), v[1].round(1), v[2].round(1) ]
end,
#Gas
'10' => lambda do |v|
[v.first.to_i + GAS_OFFSET]
end,
#Power
'20' => lambda do |v|
last = @last_value['20'] || {'time' => 0, 'data' => [0]}
current_watt_hours = v.first.to_i + POWER_OFFSET
last_watt_hours = last['data'].first
time_diff = ( Time.now.to_i - last['time'] ) / 3600.0
watt_hour_diff = current_watt_hours - last_watt_hours
current_watt = watt_hour_diff / time_diff
[current_watt_hours, current_watt.to_i]
end
}
def process(id, vals)
vals.map!(&:to_f)
@process[id].call(vals)
end
def items(raw)
data = raw.chomp.split(',')
id, *vals = data
item = {
'id' => id,
'time' => Time.now.to_i,
'data' => process(id, vals)
}
@last_value[id] = item;
p item
end
def put(item)
@dynamo.put_item({
table_name: "sensors",
item: item
})
end
#binding.pry
# Main
ser = SerialPort.new("/dev/ttyAMA0", 115200)
loop do
begin
data = ser.readline || ''
unless data.empty?
put(items(data))
end
rescue
sleep(2)
end
end