-
Notifications
You must be signed in to change notification settings - Fork 2
/
swarm
621 lines (557 loc) · 13.4 KB
/
swarm
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
--[[
msg-header-bytes:
1 get value from worldMap by xyz
2 answer to 1, returning the requested value or nil
3 set value to worldMap by xyz
4 get area
5 get known path
6 set known path
7 get known response
9 chatter
10 position broadcast
100 PING
101 PING reply
109 shutdown drone reply
110 shutdown drone
255 are you there from drone to server
]]--
swarm = {}
os.loadAPI("debug")
debug.override()
swarm.debug = debug
os.loadAPI("map")
os.loadAPI("heap")
-- Returns integer tick-timestamp
function timestamp()
return (os.day()*24000)+(os.time()*1000)
end
CHANNEL_GPS = gps.CHANNEL_GPS
CHANNEL_DRONE_BROADCAST = 65533
CHANNEL_JOB_BROADCAST = 65532
CHANNEL_BROADCAST = 65535
modem = nil
version = "0.1"
label = os.getComputerLabel()
id = os.getComputerID()
configFileName = "config_"..id
logFileName = "log_"..id
guiUpdateInterval = 1
env = getfenv()
-- Constants that may be changed
activityIndicatorString = {"[Ooo]","[oOo]","[ooO]","[oOo]"}
-- Constants that may not be changed
activityCounter = 1
quit = false
startTime = timestamp()
statistics = {}
systemType = "[TYPE NOT SET]"
-- Direction-definitions, don't just change those, will mess up stuff elsewhere
-- These are so ugly cause i need them to start at 0 not 1
dirNames = {}
dirNames[0] = "north"
dirNames[1] = "east"
dirNames[2] = "south"
dirNames[3] = "west"
dirNames[4] = "up"
dirNames[5] = "down"
xDirs = { }
xDirs[0] = 0
xDirs[1] = 1
xDirs[2] = 0
xDirs[3] = -1
xDirs[4] = 0
xDirs[5] = 0
yDirs = { }
yDirs[0] = -1
yDirs[1] = 0
yDirs[2] = 1
yDirs[3] = 0
yDirs[4] = 0
yDirs[5] = 0
zDirs = { }
zDirs[0] = 0
zDirs[1] = 0
zDirs[2] = 0
zDirs[3] = 0
zDirs[4] = 1
zDirs[5] = -1
xReverseDirs = { }
xReverseDirs[0] = 0
xReverseDirs[1] = -1
xReverseDirs[2] = 0
xReverseDirs[3] = 1
xReverseDirs[4] = 0
xReverseDirs[5] = 0
yReverseDirs = { }
yReverseDirs[0] = 1
yReverseDirs[1] = 0
yReverseDirs[2] = -1
yReverseDirs[3] = 0
yReverseDirs[4] = 0
yReverseDirs[5] = 0
zReverseDirs = { }
zReverseDirs[0] = 0
zReverseDirs[1] = 0
zReverseDirs[2] = 0
zReverseDirs[3] = 0
zReverseDirs[4] = -1
zReverseDirs[5] = 1
reverseDirs = {}
reverseDirs[-1] = -1
reverseDirs[0] = 2
reverseDirs[1] = 3
reverseDirs[2] = 0
reverseDirs[3] = 1
reverseDirs[4] = 5
reverseDirs[5] = 4
--
-- Error Stuff
--
-- TODO: I am not sure if this makes sense - shouldn't all unknown errors be bugs?
unknownErrorString = "UNKOWN ERROR"
-- Th
fatalErrorString = "FATAL ERROR"
-- Hard errors/bugs, stuff that makes the stuff crash that keeps stuff from crashing
-- We don't really handle these, because this is what happens when error handling
-- goes down for example. And lets not get into error-handling-handling-handling...
-- quite so soon.
dieErrorString = "DIE"
_error = false
_errorDone = false
function die(msg)
_errorStart()
term.clear()
term.setCursorPos(1,1)
print(dieErrorString..": "..msg)
sleep(10)
shell.exit(1)
end
function log(msg)
local logfile = io.open(logFileName,"a")
if logfile == nil then
logfile = io.open(logFileName,"w")
end
if logfile ~= nil then
logfile:write(msg.."\n")
logfile:close()
else
die("Could not open logfile '"..logFileName.."' for writing or appending.\nPlease check permissions on ComputerCraft directories.\n")
end
end
function sortAssocTableCompare(a,b)
print("COMP "..textutils.serialize(a))
return tonumber(a[1]) < tonumber(b[1])
end
function sortAssocTable(t)
table.sort(t, sortAssocTableCompare)
return t
end
function pairsAssoc(t, f)
--if type(t) ~= "table" then err("this function can only handle tables") end
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then
return nil
else
return a[i], t[a[i]]
end
end
return iter
end
function _errorStart()
_error = true
quit = true
sleep(1)
end
function _errorEnd()
sleep(1)
_errorDone = true
os.shutdown()
end
function err(e)
_errorStart()
local msg = unknownErrorString
if type(e) ~= "string" then
e = textutils.serialize(e)
end
msg = fatalErrorString..":\n"..e.."\n"
--msg = msg..debug.currentFunction().."\n"
term.clear()
term.setCursorPos(1,1)
print(msg)
msg = msg.."\n"..debug.traceback("").."\n\n"
log(msg)
_errorEnd()
end
function softError(e)
--print(msg)
if type(e) ~= "string" then
e = textutils.serialize(e)
end
msg = e.."\n"..debug.traceback("").."\n\n"
log(msg)
return msg
end
function setSystemType(t)
systemType = t
end
function getSystemType(t)
return systemType
end
function countArray(array)
if type(array) ~= "table" then return nil end
local i,v
local count = 0
for i,v in pairs(array) do
count = count + 1
end
return count
end
function activityIndicator()
local r = activityIndicatorString[activityCounter]
activityCounter = activityCounter + 1
if activityCounter > #activityIndicatorString then activityCounter = 1 end
return r
end
function getInfoString()
return "SWARM "..systemType.." #"..id
end
function _gui()
local k,v,e,msg
while not quit do
sleep(guiUpdateInterval);
term.clear()
term.setCursorPos(1,1)
msg = getInfoString().." "..activityIndicator()
os.setComputerLabel(msg)
msg = msg.."\n"
msg = msg.."[uptime - sys.: "..formatTime(os.clock(),true).."]".."\n"
for k,v in pairsAssoc(statistics) do
msg = msg ..k..": "..v.."\n"
end
print(msg)
end
end
function wrapGui() return wrap(_gui,"gui") end
function formatTime(time,short)
short = short or false
local t = {}
t[1] = time % 60
time = (time - t[1]) / 60
t[2] = time % 60
time = (time - t[2]) / 60
t[3] = time % 24
time = (time - t[3]) / 24
t[4] = time % 7
time = (time - t[4]) / 7
t[5] = time % 4
time = (time - t[5]) / 4
t[6] = time % 12
local str = ""
t[1] = math.ceil(t[1]*100)/100
if short then
if #t < 6 then return "" end
if t[6] > 0 then str = str..t[6].." mnths, " end
if t[5] > 0 then str = str..t[5].." weeks, " end
if t[4] > 0 then str = str..t[4].." days, " end
if t[3] > 0 then str = str..t[3].." hours, " end
if t[2] > 0 then str = str..t[2].." mins, " end
if t[1] > 0 then str = str..t[1].." secs " end
else
if #t < 6 then return "" end
if t[6] > 0 then str = str..t[6].." months, " end
if t[5] > 0 then str = str..t[5].." weeks, " end
if t[4] > 0 then str = str..t[4].." days, " end
if t[3] > 0 then str = str..t[3].." hours, " end
if t[2] > 0 then str = str..t[2].." minutes, " end
if t[1] > 0 then str = str..t[1].." seconds " end
end
return str
end
__status = ""
_status = {}
function test()
_test()
end
function _test(i)
i = i or 0
print(i..": "..debug.depth())
if i < 10 then
_test(i+1)
end
end
function status(msg,doPrint,callDepth)
doPrint = doPrint or false
if doPrint then
print(msg)
end
callDepth = callDepth or (debug.depth() - 1)
if callDepth == nil or type(callDepth) ~= "number" then
err("BUG: nil callDepth to status() ! '"..textutils.serialize(callDepth).."'")
end
if callDepth >= 0 and type(_status) == "table" then
local change = true
while change do
change = false
for k,v in pairsAssoc(_status) do
if k > callDepth then
table.remove(_status,k)
change = true
break
end
end
end
end
__status = msg
_status[callDepth] = __status
-- log("["..callDepth.."]\n"..textutils.serialize(_status))
end
textutils.serializeMap = function( t )
if type(t) == "number" then return tostring(t) end
sleep(0)
local result = "{"
for k,v in pairs(t) do
result = result..("["..tostring(k).."]="..textutils.serializeMap(v)..",")
end
return result.."}"
end
function wrap(func,name)
--local r = xpcall(func,err)
local function ferr(e)
e = e or unknownErrorString
err(e)
end
--setfenv(ferr,env)
--setfenv(func,env)
local r = xpcall(func,ferr)
--[[
while r ~= true do
-- r ~= true and r~= false means that the function was a success, but still wants to be called again
print("wrap returned: "..textutils.serialize(r))
sleep(0)
r = xpcall(func,ferr)
end
--]]
while _error and not _errorDone do
sleep(1)
end
if quit then
return false
end
return r
end
-- Reverse a table, used to flip paths
function reverse(tab)
if #tab == 0 then
return {}
end
local out = {}
local i = 0
for i=#tab,1,-1 do
sleep(0)--
out[(#tab+1)-i] = tab[i]
end
return out
end
-- reverse table quickly in place
function reverseInplace(tab)
local l = #tab+1
for i=1, (l-1)*.5 do
t[i], t[l-i] = t[l-i], t[i]
end
end
-- compare tables quickly
function compare(a,b)
for i = 1,#a,1 do
if b[i] == nil or a[i] ~= b[i] then
return false
end
end
return true
end
-- Our heuristic distance functions, both for point-to-point and point-to-area distance
function manhattanDistance(pos1,pos2,pos3)
if pos3 == nil or compare(pos2,pos3) then
return math.abs(pos1[1]-pos2[1])+math.abs(pos1[2]-pos2[2])+math.abs(pos1[3]-pos2[3])
else
local closest = {}
if pos1[1] < pos2[1] then
closest[1] = pos2[1]
elseif pos1[1] > pos3[1] then
closest[1] = pos3[1]
else
closest[1] = pos1[1]
end
if pos1[2] < pos2[2] then
closest[2] = pos2[2]
elseif pos1[2] > pos3[2] then
closest[2] = pos3[2]
else
closest[2] = pos1[2]
end
if pos1[3] < pos2[3] then
closest[3] = pos2[3]
elseif pos1[3] > pos3[3] then
closest[3] = pos3[3]
else
closest[3] = pos1[3]
end
return manhattanDistance(pos1,closest)
end
end
function chebyshevDistance(pos1,pos2)
return math.max(math.max(math.abs(pos1[1]-pos2[1]),math.abs(pos1[2]-pos2[2])),math.abs(pos1[3]-pos2[3]))
end
function euclideanDistance(pos1,pos2)
return math.pow(pos1[1]-pos2[1],2)+math.pow(pos1[2]-pos2[2],2)+math.pow(pos1[3]-pos2[3],2)
end
-- A wrapper so it is easier to switch between heuristic functions
function heuristicDistance(pos1,pos2,pos3)
return manhattanDistance(pos1,pos2,pos3) --+ chebyshevDistance(pos1[1],pos1[2],pos1[3],pos2[1],pos2[2],pos2[3])
end
-- This reverses a path, so we can use known paths both ways more easily.
function reversePath(path)
local r = {}
for k,v in pairs(reverse(path)) do
sleep(0)--
r[k] = reverseDirs[v]
end
return r
end
function isWithin(target,posMin,posMax)
if target[1] < posMin[1] or target[1] > posMax[1] or target[2] < posMin[2] or target[2] > posMax[2] or target[3] < posMin[3] or target[3] > posMax[3] then
return false
end
return true
end
-- Encodes strings to be used as HTTP GET-params in urls.
-- url_encode from http://lua-users.org/wiki/StringRecipes -- with a few changes
function urlEncode(str)
if (str) then
str = string.gsub (str, "\n", " ")
str = string.gsub (str, "\t", " ")
str = string.gsub (str, " ", " ")
str = string.gsub (str, " ", " ")
str = string.gsub (str, "([^%w %-%_%.%~])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
end
return str
end
-- got this somewhere, too lazy
function openModem(channel)
if modem == nil then
for n,sSide in pairs(rs.getSides()) do
if peripheral.getType( sSide ) == "modem" then
modem = peripheral.wrap(sSide)
rednet.open(sSide) --? mjeh
end
end
end
if modem == nil then
err("No modem attached!")
return false
end
if channel == nil then
-- open default channels, just like rednet.open does
modem.open(id)
modem.open(CHANNEL_BROADCAST)
-- print("openened default channels "..id.." and "..CHANNEL_BROADCAST)
else
-- open specific channel
modem.open(channel)
end
return true
end
-- Loads the configuration from disk
function loadConfig()
local file = fs.open(configFileName , "r")
if file ~= nil then
print("Loading "..fs.getSize(configFileName).." bytes of config data...")
local config = textutils.unserialize(file.readAll())
if config == nil or type(config) ~= "table" then
status("WARN: Could not unserialize config file.",true,-100)
return false
end
file.close()
return config
else
status("WARN: Could not read config file.",true,-100)
--print(""..nil)
return nil
end
end
-- Write the configuration to disk
function saveConfig(configOverride)
if configOverride ~= nil then config = configOverride end
status("saving config ... ")
local file = fs.open(configFileName , "w")
if file ~= nil then
file.write(textutils.serialize(config))
file.close()
return true
else
err(fatalErrorString..": Could not write config '"..configFileName.."'.")
end
end
function numberFormat(num,precision)
if precision == nil then precision = 2 end
return math.ceil(num * math.pow(10,precision)) / math.pow(10,precision);
end
function diffRot(a,b)
if a > 3 or b > 3 or a < 0 or b < 0 then
return 0
end
local rot = (a - b)
if rot > 2 then
rot = rot - 4
elseif rot < -2 then
rot = rot + 4
end
return math.abs(rot)
end
function fail()
print(""..nil)
end
-- Returns direction-number from direction-coords
function getDirection(xDir , yDir , zDir)
--if xDir == nil or yDir == nil then
-- return -1
--end
--print("xDir "..textutils.serialize(xDir).." "..type(xDir))
--print("yDir "..textutils.serialize(yDir).." "..type(yDir))
if yDir > 0 then
return 2
elseif yDir < 0 then
return 0
elseif xDir > 0 then
return 1
elseif xDir < 0 then
return 3
elseif zDir ~= nil and zDir > 0 then
return 4
elseif zDir ~= nil and zDir < 0 then
return 5
else
err("bug: invalid direction "..xDir..","..yDir)
return -1
end
end
function replaceFile(src,dst)
if not fs.exists(src) then
err("Source file '"..textutils.serialize(src).."' does not exists.")
end
if fs.exists(dst) then
fs.delete(dst)
end
fs.copy(src,dst)
end
function installFiles(files)
for i = 1,#files,1 do
swarm.replaceFile(files[i],"/"..files[i])
end
end