-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.rb
124 lines (98 loc) · 1.93 KB
/
app.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
# coding: utf-8
require 'homebus'
require 'homebus_app'
require 'mqtt'
require 'dotenv'
require 'json'
class NMostRecentHomeBusApp < HomeBusApp
DDC = 'org.homebus.experimental.component.queue'
STATE_FILENAME = '.saved-state.json'
def initialize(options)
@options = options
super
Dotenv.load('.env')
@source_uuid = ENV['SOURCE_UUID']
@source_ddc = ENV['SOURCE_DDC']
@n = ENV['N'].to_i
@subscribed = false
@msgs = []
_restore_state
end
def setup!
end
def work!
unless @subscribed
subscribe_to_source_ddc! @source_uuid, @source_ddc
end
listen!
end
def _prune_msgs
if @msgs.length > @n
@msgs.shift
end
end
def receive!(msg)
if options[:verbose]
puts 'received', msg
end
@msgs.push({ ddc: msg[:ddc], payload: msg[:payload] })
_prune_msgs
if options[:verbose]
puts 'about to save'
end
_save_state
payload = {
max_length: @n,
source: @source_uuid,
ddc: msg[:ddc],
queue: @msgs
}
if options[:verbose]
pp payload
end
publish! DDC, payload
if options[:verbose]
puts 'published!'
end
end
def _restore_state
if File.exists? STATE_FILENAME
@msgs = JSON.parse File.read(STATE_FILENAME), symbolize_names: true
end
end
def _save_state
File.open(STATE_FILENAME, 'w') { |f| f.write(JSON.pretty_generate(@msgs)) }
end
def manufacturer
'HomeBus'
end
def model
'Queue Component v1'
end
def friendly_name
'Queue Component'
end
def friendly_location
'Portland, OR'
end
def serial_number
"#{@source_uuid}-#{@n}"
end
def pin
''
end
def devices
[
{ friendly_name: 'Queue Component',
friendly_location: '',
update_frequency: 0,
index: 0,
accuracy: 0,
precision: 0,
wo_topics: [ '#' ],
ro_topics: [],
rw_topics: []
}
]
end
end