-
Notifications
You must be signed in to change notification settings - Fork 2
/
startup.lua
273 lines (244 loc) · 8.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
--NOTE: Replace with your server IP
local connectionURL = "127.0.0.1:5757"
local version = tonumber(string.sub(os.version(), 9))
local ws
local logLevel = 0
local maxBytesPerMessage = 131072
local function send(msg, uuid)
if uuid == nil then
uuid = ""
end
-- msg + end of transmission
local messageWithEnding = msg .. string.char(0x04)
local index = 0
local messageNumber = 1
local size = string.len(msg)
local uuidSize = string.len(uuid)
while index < size do
if ws then
-- start of heading + message index + uuid + start of text
local maxBodySize = maxBytesPerMessage - (11 + uuidSize);
ws.send(string.char(0x01) .. string.pack(">i4", messageNumber) .. string.pack(">i4", uuidSize) .. uuid .. string.char(0x02) .. messageWithEnding:sub(index + 1, index + maxBodySize), true)
index = index + maxBodySize
messageNumber = messageNumber + 1
end
end
end
local function eval(f, uuid)
if logLevel == 0 then
print("EVAL => " .. f)
end
local func = loadstring(f)
local result = {func()}
local type = "EVAL"
local response = { type = type, message = result }
if version >= 1.9 then
send(textutils.serializeJSON(response, {allow_repetitions = true}), uuid)
else
send(textutils.serializeJSON(response), uuid)
end
end
local function handshake(uuid)
local id = os.getComputerID()
local label = os.getComputerLabel()
local inventory = {}
for i = 1, 16 do
local item = turtle.getItemDetail(i, true) or textutils.json_null
inventory[tostring(i)] = item
end
local peripherals = {}
local peripheralNames = peripheral.getNames()
for k, v in pairs(peripheralNames) do
peripherals[v] = {types = {peripheral.getType(v)}}
end
local fuelLevel = turtle.getFuelLevel()
local fuelLimit = turtle.getFuelLimit()
if logLevel < 3 then
if fuelLevel == 0 then
term.setTextColor(colors.yellow)
print("WARN: Out of fuel")
term.setTextColor(colors.white)
elseif fuelLevel < 0.1 * fuelLimit then
term.setTextColor(colors.yellow)
print("WARN: Low on fuel")
term.setTextColor(colors.white)
end
end
local fuel = { level = fuelLevel, limit = fuelLimit }
local selectedSlot = turtle.getSelectedSlot()
local computer = { id = id, label = label, fuel = fuel, inventory = inventory, selectedSlot = selectedSlot, peripherals = peripherals }
local response = { type = "HANDSHAKE", message = computer }
if version >= 1.9 then
send(textutils.serializeJSON(response, {allow_repetitions = true}), uuid)
else
send(textutils.serializeJSON(response), uuid)
end
end
local function main()
if logLevel < 2 then
print("> CONNECTING...")
end
ws, err = http.websocket(connectionURL)
if ws and logLevel < 2 then
print("> CONNECTED")
elseif err == "Domain not permitted" then
print("Unable to connect to \"" .. connectionURL .. "\"")
print()
print("Potential solutions:")
print("https://tweaked.cc/guide/local_ips.html")
error(err, 2)
else
printError(err)
end
local reconnectionAttempts = 0
while true do
local message = nil
if ws then
message = ws.receive()
end
if message == nil then
if ws then
ws.close()
end
if logLevel < 2 then
print("> RECONNECTING..." .. " [" .. (reconnectionAttempts + 1) .. "]")
end
ws, err = http.websocket(connectionURL)
if ws then
if logLevel < 2 then
print("> CONNECTED")
end
reconnectionAttempts = 0
else
reconnectionAttempts = reconnectionAttempts + 1
printError(err)
os.sleep(math.min(reconnectionAttempts, 30))
end
else
local obj = textutils.unserializeJSON(message)
xpcall(function ()
if obj.type == "HANDSHAKE" then
logLevel = obj.logLevel or 0
handshake(obj.uuid)
elseif obj.type == "RENAME" then
os.setComputerLabel(obj["message"])
local response = { type = "RENAME" }
if version >= 1.9 then
send(textutils.serializeJSON(response, {allow_repetitions = true}), obj.uuid)
else
send(textutils.serializeJSON(response), obj.uuid)
end
elseif obj.type == "EVAL" then
eval(obj["function"], obj.uuid)
elseif obj.type == "DISCONNECT" then
if ws then
ws.close()
end
return print("TERMINATED")
elseif obj.type == "REBOOT" then
if ws then
ws.close()
end
if logLevel < 2 then
print("> REBOOTING")
end
os.reboot()
end
end, function (msg)
printError(msg)
local response = { type = "ERROR", message = msg }
if version >= 1.9 then
send(textutils.serializeJSON(response, {allow_repetitions = true}), obj.uuid)
else
send(textutils.serializeJSON(response), obj.uuid)
end
end)
end
end
end
local function wrappedMain()
while true do
local ok, errorMessage = pcall(main)
pcall(ws and ws.close or function()end)
if not ok then
printError(errorMessage)
if errorMessage == "Domain not permitted" then
-- Exit on this special case
break
end
end
end
end
local function waitForDisconnect()
while true do
os.pullEvent("websocket_closed")
if logLevel < 3 then
print("> WEBSOCKET CLOSED")
end
ws = nil
end
end
local function inventoryUpdate()
local function waitForEvent()
os.pullEvent("turtle_inventory")
end
local function inventoryUpdate()
local inventory = {}
local f = {}
for i = 1, 16 do
f[i] = function ()
local item = turtle.getItemDetail(i, true) or textutils.json_null
inventory[tostring(i)] = item
end
end
parallel.waitForAll(table.unpack(f))
if ws then
if version >= 1.9 then
send(textutils.serializeJSON({ type = "INVENTORY_UPDATE", message = inventory }, {allow_repetitions = true}), "update")
else
send(textutils.serializeJSON({ type = "INVENTORY_UPDATE", message = inventory }), "update")
end
end
end
waitForEvent()
local existingUpdateRoutine = nil
while true do
parallel.waitForAll(waitForEvent, inventoryUpdate)
end
end
local function peripheralAttached()
local function waitForEvent()
os.pullEvent("peripheral")
end
local function peripheralUpdate()
local peripherals = {}
local names = peripheral.getNames()
for k, v in pairs(names) do
peripherals[v] = {types = {peripheral.getType(v)}}
end
if ws then
if version >= 1.9 then
send(textutils.serializeJSON({ type = "PERIPHERAL_ATTACHED", message = peripherals }, {allow_repetitions = true}), "update")
else
send(textutils.serializeJSON({ type = "PERIPHERAL_ATTACHED", message = peripherals }), "update")
end
end
end
waitForEvent()
while true do
parallel.waitForAll(waitForEvent, peripheralUpdate)
end
end
local function peripheralDetached()
while true do
local _, side = os.pullEvent("peripheral_detach")
if not peripheral.isPresent(side) and ws then
if version >= 1.9 then
send(textutils.serializeJSON({ type = "PERIPHERAL_DETACHED", message = side }, {allow_repetitions = true}), "update")
else
send(textutils.serializeJSON({ type = "PERIPHERAL_DETACHED", message = side }), "update")
end
end
end
end
parallel.waitForAny(wrappedMain, inventoryUpdate, peripheralAttached, peripheralDetached)