forked from Ale32bit-CC/SmartNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstartup.lua
396 lines (355 loc) · 12.5 KB
/
startup.lua
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
local VERSION = "1.2.0"
local config = require("config")
local chacha20 = require("lib.chacha20")
local sha256 = require("lib.sha256")
local Logger = require("lib.logger")
local utils = require("lib.utils")
local enum = utils.enum
local OP = enum {
"PING", -- normal pings
"DISCOVER_REQUEST", -- when a device requests a discover
"DISCOVER", -- let people know you exist
"GET", -- a device asked for your value
"SET", -- a device wants to set you a value
"RESPONSE", -- a device answered your get request
"MODULE", -- generic message for custom stuff
"COLLISION", -- in case you forgot to change ids when copying configs
"COLLISION_ACK"
}
local logger = Logger(
config.id,
{
format = "[%date%][%level%] %log%",
enableDebug = config.debug
}
)
local devices = {}
-- Make the UI
local w, h = term.getSize()
term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
local mainWindow = window.create(term.current(), 1, 2, w, h - 1, true)
local nTerm = term.redirect(mainWindow)
local function redrawBar()
nTerm.setBackgroundColor(colors.white)
nTerm.setTextColor(colors.black)
nTerm.setCursorPos(1, 1)
nTerm.clearLine()
nTerm.write("SmartNet " .. VERSION)
local rightText = string.format("%s (%s)", config.label, config.id)
nTerm.setCursorPos(w - #rightText + 1, 1)
nTerm.write(rightText)
end
redrawBar()
logger:info("Welcome to SmartNet v" .. VERSION)
logger:info("(c) 2022 AlexDevs")
logger:info(config.label, "ID is", config.id)
logger:info("Role is set to", config.role)
local module
local ok, par = pcall(require, "modules." .. config.role)
if ok then
module = par
else
logger:error(par)
return
end
local modem
if config.modemSide == "auto" then
modem = peripheral.find("modem")
else
modem = peripheral.wrap(config.modemSide)
end
if not modem then
logger:error("Modem not found")
return
end
modem.open(config.channel)
local function get_key(token)
token = tostring(sha256.digest(token))
return { string.byte(token, 1, -1) }
end
local function gen_nonce()
local n = {}
for i = 1, 12 do n[#n+1] = math.random(0, 255) end
return n
end
local function encrypt(data)
local nonce = gen_nonce()
local ctx = chacha20.crypt(data, get_key(config.token), nonce)
return ctx, nonce
end
local function decrypt(data, nonce)
local ok, par = pcall(function() return chacha20.crypt(data, get_key(config.token), nonce) end)
if not ok then
return nil
end
return par
end
local function packMessage(msg, nonce)
-- nonce is always 12 bytes
return string.char(unpack(nonce)) .. string.char(unpack(msg))
end
local function unpackMessage(data)
local nonce = string.sub(data, 1, 12)
local msg = string.sub(data, 13, -1)
return {
nonce = {string.byte(nonce, 1, -1)},
data = {string.byte(msg, 1, -1)}
}
end
local function send(op, data)
data._nonce = math.random(1, 2147483647)
data.computerId = os.getComputerID()
data.id = config.id
data.op = utils.getEnum(OP, op)
local sData = textutils.serialise(data)
sData, nonce = encrypt(sData)
modem.transmit(config.channel, data.op, packMessage(sData, nonce))
end
local function broadcastDiscover()
logger:debug("Broadcasting discovery")
send(
OP.DISCOVER,
{
data = {
id = config.id,
role = config.role,
label = config.label,
setup = config.setup,
version = VERSION
}
}
)
end
local function requestDiscover()
logger:debug("Requesting discovery")
send(
OP.DISCOVER_REQUEST,
{
data = {
id = config.id,
role = config.role,
label = config.label
}
}
)
end
local function ping()
send(
OP.PING,
{
time = os.epoch("utc")
}
)
end
local function request(id)
logger:debug("Requesting to ", id)
local nonce = os.epoch("utc")
send(
OP.GET,
{
target = id,
nonce = nonce
}
)
local _, rNonce, value
repeat
_, rNonce, value = os.pullEvent("smart_response")
until rNonce == nonce
end
local function get(data)
if (data.target ~= "*" and data.target ~= config.id) then
return
end
logger:debug(data.id, "getter")
local nonce = data.nonce
if module.get and config.setup.getter then
local value = module.get()
send(
OP.RESPONSE,
{
target = data.id,
nonce = nonce,
value = value,
valueType = config.setup.getter,
ok = true
}
)
else
send(
OP.RESPONSE,
{
target = data.id,
nonce = nonce,
ok = false
}
)
end
end
local function set(data)
if (data.target == "*" or data.target == config.id) and config.setup.setter and module.set then
if type(data.value) == config.setup.setter or config.setup.setter == "*" then
logger:debug(data.id, "setter")
module.set(data.value)
end
end
end
local function setInDevice(target, value)
send(
OP.SET,
{
target = target,
value = value
}
)
end
local luck = 0
local nLuck = 0
local randomLuck = false
local function resolveCollision(id)
luck = randomLuck and math.random(0, 0xffff) or os.clock()
logger:warn("ID Collision with computer #" .. tostring(id) .. ".", "My luck is", luck)
if nLuck > 5 then
logger:error("Stalemate")
error(nil, 0)
end
send(
OP.COLLISION,
{
luck = luck
}
)
end
config.setup =
module.init(
{
logger = logger,
config = config,
send = send,
set = setInDevice,
get = request,
devices = devices
}
)
-- It is polite to introduce yourself
broadcastDiscover()
sleep(0.1)
-- But you also want to know who the others are
requestDiscover()
parallel.waitForAll(
function()
local receivedMessages, pruneReceivedTimer = {}
while true do
local ev = {os.pullEventRaw()}
if ev[1] == "modem_message" then
if ev[3] == config.channel then
if type(ev[5]) == "string" then
local unpacked = unpackMessage(ev[5])
local sData = decrypt(unpacked.data, unpacked.nonce)
if sData then
local data = textutils.unserialise(string.char(unpack(sData)))
if type(data) == "table" and not receivedMessages[data._nonce] and type(data.id) == "string" then
receivedMessages[data._nonce] = os.clock() + 9.5
if not pruneReceivedTimer then
prune_received_timer = os.startTimer(10)
end
local opCode = data.op
if opCode == OP.PING then
logger:debug("PONG from", data.id)
if data.id == config.id then
resolveCollision(data.computerId)
end
if devices[data.id] then
devices[data.id].lastPing = data.time
else
-- Just in case, every device should introduce themselves upon request
logger:debug("Couldn't find", data.id, "from ping")
requestDiscover()
end
if module.ping then
module.ping(data.id)
end
elseif opCode == OP.DISCOVER then
logger:debug("Discovered", data.id)
if data.id == config.id then
resolveCollision(data.computerId)
end
devices[data.id] = data.data
elseif opCode == OP.DISCOVER_REQUEST then
broadcastDiscover()
elseif opCode == OP.GET then
get(data)
elseif opCode == OP.SET then
set(data)
elseif opCode == OP.RESPONSE then
os.queueEvent("smart_response", data.nonce, data.value)
elseif opCode == OP.MODULE then
if module.request and (data.target == config.id or data.target == "*") then
logger:debug("Received raw request")
module.request(data)
end
elseif opCode == OP.COLLISION then
if data.id == config.id then
nLuck = nLuck + 1
send(
OP.COLLISION_ACK,
{
luck = luck
}
)
if luck < data.luck then
logger:warn("Collision resolved! I lost")
nLuck = 0
config.id = config.id .. tostring(luck)
redrawBar()
elseif luck > data.luck then
logger:warn("Collision resolved! I won")
nLuck = 0
else -- oh no
randomLuck = true
logger:warn("Retrying attempt", nLuck)
resolveCollision(data.computerId)
end
end
elseif opCode == OP.COLLISION_ACK then
if data.id == config.id then
logger:warn("Collider luck is", data.luck)
end
end
end
end
end
end
elseif ev[1] == "timer" and ev[2] == pruneReceivedTimer then
-- Stole from RedNet API
-- Got a timer event, use it to prune the set of received messages
pruneReceivedTimer = nil
local now, has_more = os.clock(), nil
for message_id, deadline in pairs(receivedMessages) do
if deadline <= now then receivedMessages[message_id] = nil
else has_more = true end
end
pruneReceivedTimer = has_more and os.startTimer(10)
elseif ev[1] == "terminate" then
term.redirect(nTerm)
term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1, 1)
print("Exited from SmartNet")
end
end
end,
function()
if module.run then
module.run()
end
end,
function()
while true do
ping()
sleep(10)
end
end
)