-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.rb
98 lines (80 loc) · 2.27 KB
/
web.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
require 'sinatra'
require 'json'
require_relative 'binary'
require_relative 'hardware_id'
require_relative 'storage'
if ENV['RACK_ENV'] != 'production'
set :port, 5000
ENV['MONGOHQ_URL']='mongodb://firefly:design@dharma.mongohq.com:10015/firefly-data'
end
FD_CONTROL_SYNC_START = 15
FD_CONTROL_SYNC_DATA = 16
FD_CONTROL_SYNC_ACK = 17
$storage = Storage.new
def self.storage_type(s)
s.encode(Encoding.find('ASCII-8BIT')).unpack('L<').first
end
FD_LOG_TYPE = storage_type('FDLO')
FD_VMA_TYPE = storage_type('FDVM')
def sync_log(hardware_id, binary)
time = binary.get_time64
length = binary.remaining_length
message = binary.get_bytes(length)
$storage.sync(hardware_id.to_s, time, 'log', {time: time, message: message})
end
def sync_vma(hardware_id, binary)
time = binary.get_time32
interval = binary.get_uint16
n = binary.remaining_length / 4 # 4 == sizeof(float32)
values = n.times.collect { binary.get_float32 }
$storage.sync(hardware_id.to_s, time, 'vmas', {time: time, interval: interval, values: values})
end
def sync_data(binary)
hardware_id = HardwareId.new(binary.get_bytes(16))
page = binary.get_uint32
length = binary.get_uint16
hash = binary.get_uint16
type = binary.get_uint32
if page == 0xfffffffe
return 'nothing to sync'
end
case type
when FD_LOG_TYPE
sync_log(hardware_id, binary)
when FD_VMA_TYPE
sync_vma(hardware_id, binary)
else
return "unknown type #{type}"
end
content_type 'application/octet-stream'
response = Binary.new('')
response.put_uint8(FD_CONTROL_SYNC_ACK)
response.put_uint32(page)
response.put_uint16(length)
response.put_uint16(hash)
response.put_uint32(type)
response.to_bytes
end
post '/sync' do
binary = Binary.new(request.env['rack.input'].read)
sync_data(binary)
end
post '/query' do
json_request = request.env['rack.input'].read
object = JSON.parse(json_request)
query = object['query']
type = query['type']
span = {start: query['start'], end: query['end'], duration: query['duration']}
result = $storage.query(type, span)
content_type :json
response = {query: query, result: result}
response.to_json
end
post '/echo' do
json_object = JSON.parse(request.env['rack.input'].read)
content_type :json
json_object.to_json
end
get '/' do
'hello'
end