change _debug to _syslog

This commit is contained in:
kepler155c@gmail.com
2019-05-03 15:30:37 -04:00
parent 074e0742d5
commit 731fc2c761
31 changed files with 264 additions and 204 deletions

View File

@@ -125,8 +125,6 @@ local assert = assert
local error = error local error = error
local ipairs = ipairs local ipairs = ipairs
local pairs = pairs local pairs = pairs
local print = print
local require = require
local tostring = tostring local tostring = tostring
local type = type local type = type
local setmetatable = setmetatable local setmetatable = setmetatable
@@ -136,30 +134,12 @@ local table_sort = table.sort
local math_max = math.max local math_max = math.max
local string_char = string.char local string_char = string.char
--[[
Requires the first module listed that exists, else raises like `require`.
If a non-string is encountered, it is returned.
Second return value is module name loaded (or '').
--]]
local function requireany(...)
local errs = {}
for i = 1, select('#', ...) do local name = select(i, ...)
if type(name) ~= 'string' then return name, '' end
local ok, mod = pcall(require, name)
if ok then return mod, name end
errs[#errs+1] = mod
end
error(table.concat(errs, '\n'), 2)
end
--local crc32 = require "digest.crc32lua" . crc32_byte --local crc32 = require "digest.crc32lua" . crc32_byte
--local bit, name_ = requireany('bit', 'bit32', 'bit.numberlua', nil) --local bit, name_ = requireany('bit', 'bit32', 'bit.numberlua', nil)
local bit local bit
local crc32 local crc32
local DEBUG = false
-- Whether to use `bit` library functions in current module. -- Whether to use `bit` library functions in current module.
-- Unlike the crc32 library, it doesn't make much difference in this module. -- Unlike the crc32 library, it doesn't make much difference in this module.
local NATIVE_BITOPS = (bit ~= nil) local NATIVE_BITOPS = (bit ~= nil)
@@ -176,12 +156,6 @@ local function warn(s)
io.stderr:write(s, '\n') io.stderr:write(s, '\n')
end end
local function debug(...)
print('DEBUG', ...)
end
local function runtime_error(s, level) local function runtime_error(s, level)
level = level or 1 level = level or 1
error({s}, level+1) error({s}, level+1)
@@ -198,7 +172,6 @@ end
local function output(outstate, byte) local function output(outstate, byte)
-- debug('OUTPUT:', s)
local window_pos = outstate.window_pos local window_pos = outstate.window_pos
outstate.outbs(byte) outstate.outbs(byte)
outstate.window[window_pos] = byte outstate.window[window_pos] = byte
@@ -240,28 +213,6 @@ local pow2 = memoize(function(n) return 2^n end)
-- weak metatable marking objects as bitstream type -- weak metatable marking objects as bitstream type
local is_bitstream = setmetatable({}, {__mode='k'}) local is_bitstream = setmetatable({}, {__mode='k'})
-- DEBUG
-- prints LSB first
--[[
local function bits_tostring(bits, nbits)
local s = ''
local tmp = bits
local function f()
local b = tmp % 2 == 1 and 1 or 0
s = s .. b
tmp = (tmp - b) / 2
end
if nbits then
for i=1,nbits do f() end
else
while tmp ~= 0 do f() end
end
return s
end
--]]
local function bytestream_from_file(fh) local function bytestream_from_file(fh)
local o = {} local o = {}
function o:read() function o:read()
@@ -288,18 +239,9 @@ end
local function bytestream_from_function(f) local function bytestream_from_function(f)
local i = 0
local buffer = ''
local o = {} local o = {}
function o:read() function o:read()
return f() return f()
-- i = i + 1
-- if i > #buffer then
-- buffer = f()
-- if not buffer then return end
-- i = 1
-- end
-- return buffer:byte(i,i)
end end
return o return o
end end
@@ -395,13 +337,11 @@ local function HuffmanTable(init, is_full)
for val,nbits in pairs(init) do for val,nbits in pairs(init) do
if nbits ~= 0 then if nbits ~= 0 then
t[#t+1] = {val=val, nbits=nbits} t[#t+1] = {val=val, nbits=nbits}
--debug('*',val,nbits)
end end
end end
else else
for i=1,#init-2,2 do for i=1,#init-2,2 do
local firstval, nbits, nextval = init[i], init[i+1], init[i+2] local firstval, nbits, nextval = init[i], init[i+1], init[i+2]
--debug(val, nextval, nbits)
if nbits ~= 0 then if nbits ~= 0 then
for val=firstval,nextval-1 do for val=firstval,nextval-1 do
t[#t+1] = {val=val, nbits=nbits} t[#t+1] = {val=val, nbits=nbits}
@@ -422,7 +362,6 @@ local function HuffmanTable(init, is_full)
nbits = s.nbits nbits = s.nbits
end end
s.code = code s.code = code
--debug('huffman code:', i, s.nbits, s.val, code, bits_tostring(code))
code = code + 1 code = code + 1
end end
@@ -433,12 +372,6 @@ local function HuffmanTable(init, is_full)
look[s.code] = s.val look[s.code] = s.val
end end
--for _,o in ipairs(t) do
-- debug(':', o.nbits, o.val)
--end
-- function t:lookup(bits) return look[bits] end
local msb = NATIVE_BITOPS and function(bits, nbits) local msb = NATIVE_BITOPS and function(bits, nbits)
local res = 0 local res = 0
for i=1,nbits do for i=1,nbits do
@@ -448,7 +381,7 @@ local function HuffmanTable(init, is_full)
return res return res
end or function(bits, nbits) end or function(bits, nbits)
local res = 0 local res = 0
for i=1,nbits do for _=1,nbits do
local b = bits % 2 local b = bits % 2
bits = (bits - b) / 2 bits = (bits - b) / 2
res = res * 2 + b res = res * 2 + b
@@ -470,14 +403,9 @@ local function HuffmanTable(init, is_full)
local b = noeof(bs:read()) local b = noeof(bs:read())
nbits = nbits + 1 nbits = nbits + 1
code = code * 2 + b -- MSB first code = code * 2 + b -- MSB first
--[[NATIVE_BITOPS
code = lshift(code, 1) + b -- MSB first
--]]
end end
--debug('code?', code, bits_tostring(code))
local val = look[code] local val = look[code]
if val then if val then
--debug('FOUND', val)
return val return val
end end
end end
@@ -505,15 +433,6 @@ local function parse_gzip_header(bs)
local xfl = bs:read(8) -- eXtra FLags local xfl = bs:read(8) -- eXtra FLags
local os = bs:read(8) -- Operating System local os = bs:read(8) -- Operating System
if DEBUG then
debug("CM=", cm)
debug("FLG=", flg)
debug("MTIME=", mtime)
-- debug("MTIME_str=",os.date("%Y-%m-%d %H:%M:%S",mtime)) -- non-portable
debug("XFL=", xfl)
debug("OS=", os)
end
if not os then runtime_error 'invalid header' end if not os then runtime_error 'invalid header' end
if hasbit(flg, FLG_FEXTRA) then if hasbit(flg, FLG_FEXTRA) then
@@ -545,9 +464,6 @@ local function parse_gzip_header(bs)
if not crc16 then runtime_error 'invalid header' end if not crc16 then runtime_error 'invalid header' end
-- IMPROVE: check CRC. where is an example .gz file that -- IMPROVE: check CRC. where is an example .gz file that
-- has this set? -- has this set?
if DEBUG then
debug("CRC16=", crc16)
end
end end
end end
@@ -607,7 +523,6 @@ local function parse_huffmantables(bs)
if codelen <= 15 then if codelen <= 15 then
nrepeat = 1 nrepeat = 1
nbits = codelen nbits = codelen
--debug('w', nbits)
elseif codelen == 16 then elseif codelen == 16 then
nrepeat = 3 + noeof(bs:read(2)) nrepeat = 3 + noeof(bs:read(2))
-- nbits unchanged -- nbits unchanged
@@ -645,7 +560,6 @@ local tdecode_dist_base
local tdecode_dist_nextrabits local tdecode_dist_nextrabits
local function parse_compressed_item(bs, outstate, littable, disttable) local function parse_compressed_item(bs, outstate, littable, disttable)
local val = littable:read(bs) local val = littable:read(bs)
--debug(val, val < 256 and string_char(val))
if val < 256 then -- literal if val < 256 then -- literal
output(outstate, val) output(outstate, val)
elseif val == 256 then -- end of block elseif val == 256 then -- end of block
@@ -660,7 +574,6 @@ local function parse_compressed_item(bs, outstate, littable, disttable)
end end
t[285] = 258 t[285] = 258
tdecode_len_base = t tdecode_len_base = t
--for i=257,285 do debug('T1',i,t[i]) end
end end
if not tdecode_len_nextrabits then if not tdecode_len_nextrabits then
local t = {} local t = {}
@@ -677,7 +590,6 @@ local function parse_compressed_item(bs, outstate, littable, disttable)
end end
t[285] = 0 t[285] = 0
tdecode_len_nextrabits = t tdecode_len_nextrabits = t
--for i=257,285 do debug('T2',i,t[i]) end
end end
local len_base = tdecode_len_base[val] local len_base = tdecode_len_base[val]
local nextrabits = tdecode_len_nextrabits[val] local nextrabits = tdecode_len_nextrabits[val]
@@ -692,7 +604,6 @@ local function parse_compressed_item(bs, outstate, littable, disttable)
if i ~= 1 then skip = skip * 2 end if i ~= 1 then skip = skip * 2 end
end end
tdecode_dist_base = t tdecode_dist_base = t
--for i=0,29 do debug('T3',i,t[i]) end
end end
if not tdecode_dist_nextrabits then if not tdecode_dist_nextrabits then
local t = {} local t = {}
@@ -708,7 +619,6 @@ local function parse_compressed_item(bs, outstate, littable, disttable)
end end
end end
tdecode_dist_nextrabits = t tdecode_dist_nextrabits = t
--for i=0,29 do debug('T4',i,t[i]) end
end end
local dist_val = disttable:read(bs) local dist_val = disttable:read(bs)
local dist_base = tdecode_dist_base[dist_val] local dist_base = tdecode_dist_base[dist_val]
@@ -716,7 +626,6 @@ local function parse_compressed_item(bs, outstate, littable, disttable)
local dist_extrabits = bs:read(dist_nextrabits) local dist_extrabits = bs:read(dist_nextrabits)
local dist = dist_base + dist_extrabits local dist = dist_base + dist_extrabits
--debug('BACK', len, dist)
for i=1,len do for i=1,len do
local pos = (outstate.window_pos - 1 - dist) % 32768 + 1 -- 32K local pos = (outstate.window_pos - 1 - dist) % 32768 + 1 -- 32K
output(outstate, assert(outstate.window[pos], 'invalid distance')) output(outstate, assert(outstate.window[pos], 'invalid distance'))
@@ -735,17 +644,12 @@ local function parse_block(bs, outstate)
local BTYPE_DYNAMIC_HUFFMAN = 2 local BTYPE_DYNAMIC_HUFFMAN = 2
local BTYPE_RESERVED_ = 3 local BTYPE_RESERVED_ = 3
if DEBUG then
debug('bfinal=', bfinal)
debug('btype=', btype)
end
if btype == BTYPE_NO_COMPRESSION then if btype == BTYPE_NO_COMPRESSION then
bs:read(bs:nbits_left_in_byte()) bs:read(bs:nbits_left_in_byte())
local len = bs:read(16) local len = bs:read(16)
local nlen_ = noeof(bs:read(16)) local nlen_ = noeof(bs:read(16))
for i=1,len do for _=1,len do
local by = noeof(bs:read(8)) local by = noeof(bs:read(8))
output(outstate, by) output(outstate, by)
end end
@@ -804,10 +708,7 @@ function M.gunzip(t)
local expected_crc32 = bs:read(32) local expected_crc32 = bs:read(32)
local isize = bs:read(32) -- ignored local isize = bs:read(32) -- ignored
if DEBUG then
debug('crc32=', expected_crc32)
debug('isize=', isize)
end
if not disable_crc and data_crc32 then if not disable_crc and data_crc32 then
if data_crc32 ~= expected_crc32 then if data_crc32 ~= expected_crc32 then
runtime_error('invalid compressed data--crc error') runtime_error('invalid compressed data--crc error')
@@ -853,9 +754,7 @@ function M.inflate_zlib(t)
local b1 = bs:read(8) local b1 = bs:read(8)
local b0 = bs:read(8) local b0 = bs:read(8)
local expected_adler32 = ((b3*256 + b2)*256 + b1)*256 + b0 local expected_adler32 = ((b3*256 + b2)*256 + b1)*256 + b0
if DEBUG then
debug('alder32=', expected_adler32)
end
if not disable_crc then if not disable_crc then
if data_adler32 ~= expected_adler32 then if data_adler32 ~= expected_adler32 then
runtime_error('invalid compressed data--crc error') runtime_error('invalid compressed data--crc error')

View File

@@ -128,7 +128,7 @@ function supplyPage:enable(builder)
self:sync() self:sync()
end) end)
if not s then -- not sure why it's erroring :( if not s then -- not sure why it's erroring :(
_G._debug(m) _G._syslog(m)
end end
end end
end) end)

View File

@@ -120,7 +120,7 @@ function swarm:onRemove(member, status, message)
member.snmp = nil member.snmp = nil
end end
if not status then if not status then
_G._debug(message) _G._syslog(message)
end end
end end

View File

@@ -13,9 +13,9 @@ mon.clear()
mon.setTextScale(.5) mon.setTextScale(.5)
mon.setCursorPos(1, 1) mon.setCursorPos(1, 1)
local oldDebug = _G._debug local oldDebug = _G._syslog
_G._debug = function(...) _G._syslog = function(...)
local oldTerm = term.redirect(mon) local oldTerm = term.redirect(mon)
Util.print(...) Util.print(...)
term.redirect(oldTerm) term.redirect(oldTerm)
@@ -30,4 +30,4 @@ repeat
end end
until e == 'terminate' until e == 'terminate'
_G._debug = oldDebug _G._syslog = oldDebug

View File

@@ -110,7 +110,7 @@ function ChestAdapter:listItems(throttle)
return items return items
end end
else else
_debug(m) _G._syslog(m)
end end
end end

View File

@@ -42,7 +42,6 @@ function ChestAdapter:getItemDetails(index, item)
if self.getItemMeta then if self.getItemMeta then
local s, detail = pcall(self.getItemMeta, index) local s, detail = pcall(self.getItemMeta, index)
if not s or not detail or detail.name ~= item.name then if not s or not detail or detail.name ~= item.name then
-- debug({ s, detail })
return return
end end
return detail return detail

View File

@@ -102,7 +102,7 @@ function MEAdapter:refresh()
itemDB:flush() itemDB:flush()
if not s and m then if not s and m then
_debug(m) _G._syslog(m)
end end
if s and not failed and hasItems and self.items and not Util.empty(self.items) then if s and not failed and hasItems and self.items and not Util.empty(self.items) then

View File

@@ -70,7 +70,7 @@ function RefinedAdapter:listItems(throttle)
end) end)
if not s and m then if not s and m then
_debug(m) _G._syslog(m)
end end
itemDB:flush() itemDB:flush()

View File

@@ -71,7 +71,7 @@ local function turtleCraft(recipe, qty, inventoryAdapter)
inventoryAdapter:provide(item, provideQty, k) inventoryAdapter:provide(item, provideQty, k)
if turtle.getItemCount(k) == 0 then -- ~= qty then if turtle.getItemCount(k) == 0 then -- ~= qty then
-- FIX: ingredients cannot be stacked -- FIX: ingredients cannot be stacked
--debug('failed ' .. v .. ' - ' .. provideQty) --_syslog('failed ' .. v .. ' - ' .. provideQty)
return false return false
end end
end end

View File

@@ -88,7 +88,6 @@ function page:runFunction(id, script)
local fn, msg = loadstring(script, 'script') local fn, msg = loadstring(script, 'script')
if not fn then if not fn then
self.notification:error('Error in script') self.notification:error('Error in script')
--debug(msg)
return return
end end

View File

@@ -120,10 +120,10 @@ table.sort(context.tasks, function(a, b)
return a.priority < b.priority return a.priority < b.priority
end) end)
_G._debug('Tasks\n-----') _G._syslog('Tasks\n-----')
for _, task in ipairs(context.tasks) do for _, task in ipairs(context.tasks) do
task.execTime = 0 task.execTime = 0
_G._debug('%d: %s', task.priority, task.name) _G._syslog('%d: %s', task.priority, task.name)
end end
Milo:clearGrid() Milo:clearGrid()
@@ -139,8 +139,8 @@ Event.on({ 'milo_cycle', 'milo_queue' }, function(e)
for _, entry in pairs(queue) do for _, entry in pairs(queue) do
local s, m = pcall(entry.callback, entry.request) local s, m = pcall(entry.callback, entry.request)
if not s and m then if not s and m then
_G._debug('callback crashed') _G._syslog('callback crashed')
_G._debug(m) _G._syslog(m)
end end
end end
end end
@@ -154,8 +154,8 @@ Event.on({ 'milo_cycle', 'milo_queue' }, function(e)
local timer = Util.timer() local timer = Util.timer()
local s, m = pcall(function() task:cycle(context) end) local s, m = pcall(function() task:cycle(context) end)
if not s and m then if not s and m then
_G._debug(task.name .. ' crashed') _G._syslog(task.name .. ' crashed')
_G._debug(m) _G._syslog(m)
end end
task.execTime = task.execTime + timer() task.execTime = task.execTime + timer()
end end
@@ -182,7 +182,7 @@ cycleHandle = Event.onInterval(5, function()
Event.trigger('milo_cycle') Event.trigger('milo_cycle')
if context.taskCounter > 0 then if context.taskCounter > 0 then
--local average = context.taskTimer / context.taskCounter --local average = context.taskTimer / context.taskCounter
--_debug('Interval: ' .. math.max(5, 2 + average * 3)) --_syslog('Interval: ' .. math.max(5, 2 + average * 3))
--cycleHandle.updateInterval(math.max(5, 2 + average * 3)) --cycleHandle.updateInterval(math.max(5, 2 + average * 3))
end end
end) end)
@@ -208,8 +208,8 @@ os.queueEvent(
context.storage:isOnline() and 'storage_online' or 'storage_offline', context.storage:isOnline() and 'storage_online' or 'storage_offline',
context.storage:isOnline()) context.storage:isOnline())
local oldDebug = _G._debug local oldDebug = _G._syslog
_G._debug = function(...) _G._syslog = function(...)
for _,v in pairs(context.loggers) do for _,v in pairs(context.loggers) do
v(...) v(...)
end end
@@ -220,5 +220,5 @@ local s, m = pcall(function()
UI:pullEvents() UI:pullEvents()
end) end)
_G._debug = oldDebug _G._syslog = oldDebug
if not s then error(m) end if not s then error(m) end

View File

@@ -148,7 +148,7 @@ local function turtleCraft(recipe, storage, request, count)
request.status = 'rescan needed ?' request.status = 'rescan needed ?'
request.statusCode = Craft.STATUS_ERROR request.statusCode = Craft.STATUS_ERROR
failed = true failed = true
_debug('failed to export: ' .. item.name) _G._syslog('failed to export: ' .. item.name)
end end
end) end)
end end
@@ -165,8 +165,8 @@ local function turtleCraft(recipe, storage, request, count)
local l = storage.turtleInventory.adapter.list() local l = storage.turtleInventory.adapter.list()
local crafted = l[1] local crafted = l[1]
if recipe.result ~= itemDB:makeKey(crafted) then if recipe.result ~= itemDB:makeKey(crafted) then
_debug('expected: ' .. recipe.result) _G._syslog('expected: ' .. recipe.result)
_debug('got: ' .. itemDB:makeKey(crafted)) _G._syslog('got: ' .. itemDB:makeKey(crafted))
request.aborted = true request.aborted = true
request.status = 'Failed to craft: ' .. recipe.result request.status = 'Failed to craft: ' .. recipe.result
request.statusCode = Craft.STATUS_ERROR request.statusCode = Craft.STATUS_ERROR
@@ -176,7 +176,7 @@ local function turtleCraft(recipe, storage, request, count)
request.statusCode = Craft.STATUS_SUCCESS request.statusCode = Craft.STATUS_SUCCESS
end end
else else
_debug('just failed') _G._syslog('just failed')
request.status = 'Failed to craft' request.status = 'Failed to craft'
request.statusCode = Craft.STATUS_ERROR request.statusCode = Craft.STATUS_ERROR
end end

View File

@@ -44,7 +44,7 @@ function Adapter:init(args)
end end
function self.pullItems(target, key, amount, slot) function self.pullItems(target, key, amount, slot)
_G._debug({target, key, amount, slot }) _G._syslog({target, key, amount, slot })
return 0 return 0
end end

View File

@@ -66,7 +66,7 @@ function Storage:init()
end end
Event.on({ 'device_attach', 'device_detach' }, function(e, dev) Event.on({ 'device_attach', 'device_detach' }, function(e, dev)
_G._debug('%s: %s', e, tostring(dev)) _G._syslog('%s: %s', e, tostring(dev))
self:initStorage() self:initStorage()
end) end)
Event.onInterval(60, function() Event.onInterval(60, function()
@@ -87,11 +87,11 @@ function Storage:showStorage()
end end
end end
if #t > 0 then if #t > 0 then
_G._debug('Adapter:') _G._syslog('Adapter:')
for _, k in pairs(t) do for _, k in pairs(t) do
_G._debug(' offline: ' .. k) _G._syslog(' offline: ' .. k)
end end
_G._debug('') _G._syslog('')
end end
end end
@@ -143,7 +143,7 @@ function Storage:initStorage()
self.storageOnline = online self.storageOnline = online
-- TODO: if online, then list items -- TODO: if online, then list items
os.queueEvent(self.storageOnline and 'storage_online' or 'storage_offline', online) os.queueEvent(self.storageOnline and 'storage_online' or 'storage_offline', online)
_G._debug('Storage: %s', self.storageOnline and 'online' or 'offline') _G._syslog('Storage: %s', self.storageOnline and 'online' or 'offline')
end end
self:listItems() self:listItems()
@@ -229,7 +229,7 @@ end
function Storage:refresh(throttle) function Storage:refresh(throttle)
self.dirty = true self.dirty = true
_G._debug('STORAGE: Forcing full refresh') _G._syslog('STORAGE: Forcing full refresh')
for _, adapter in self:onlineAdapters() do for _, adapter in self:onlineAdapters() do
adapter.dirty = true adapter.dirty = true
end end
@@ -280,7 +280,7 @@ function Storage:listItems(throttle)
end end
end end
itemDB:flush() itemDB:flush()
_G._debug('STORAGE: refresh ' .. #t .. ' inventories in ' .. Util.round(timer(), 2)) _G._syslog('STORAGE: refresh ' .. #t .. ' inventories in ' .. Util.round(timer(), 2))
self.dirty = false self.dirty = false
self.cache = cache self.cache = cache
@@ -300,7 +300,7 @@ function Storage:updateCache(adapter, item, count)
if not entry then if not entry then
if count < 0 then if count < 0 then
_G._debug('STORAGE: update cache - count < 0', 4) _G._syslog('STORAGE: update cache - count < 0', 4)
else else
entry = Util.shallowCopy(item) entry = Util.shallowCopy(item)
entry.count = count entry.count = count
@@ -315,7 +315,7 @@ function Storage:updateCache(adapter, item, count)
end end
if not entry then if not entry then
_G._debug('STORAGE: item missing details') _G._syslog('STORAGE: item missing details')
adapter.dirty = true adapter.dirty = true
self.dirty = true self.dirty = true
else else
@@ -401,7 +401,7 @@ local function rawExport(source, target, item, qty, slot)
end) end)
if not s and m then if not s and m then
_G._debug(m) _G._syslog(m)
end end
return total, m return total, m
@@ -424,7 +424,7 @@ function Storage:export(target, slot, count, item)
end end
if amount > 0 then if amount > 0 then
_G._debug('EXT: %s(%d): %s -> %s%s in %s', _G._syslog('EXT: %s(%d): %s -> %s%s in %s',
item.displayName or item.name, amount, self:_sn(adapter.name), self:_sn(target.name), item.displayName or item.name, amount, self:_sn(adapter.name), self:_sn(target.name),
slot and string.format('[%d]', slot) or '[*]', Util.round(timer(), 2)) slot and string.format('[%d]', slot) or '[*]', Util.round(timer(), 2))
end end
@@ -443,7 +443,7 @@ function Storage:export(target, slot, count, item)
end end
end end
_G._debug('STORAGE warning: %s(%d): %s%s %s failed to export', _G._syslog('STORAGE warning: %s(%d): %s%s %s failed to export',
item.displayName or item.name, count, self:_sn(target.name), item.displayName or item.name, count, self:_sn(target.name),
slot and string.format('[%d]', slot) or '[*]', key) slot and string.format('[%d]', slot) or '[*]', key)
@@ -460,15 +460,15 @@ local function rawInsert(source, target, slot, qty)
local s, m = pcall(function() local s, m = pcall(function()
if isValidTransfer(source, target.name) then if isValidTransfer(source, target.name) then
--_debug('pull %s %s %d %d', source.name, target.name, slot, qty) --_syslog('pull %s %s %d %d', source.name, target.name, slot, qty)
count = source.pullItems(target.name, slot, qty) count = source.pullItems(target.name, slot, qty)
else else
--_debug('push %s %s', target.name, source.name) --_syslog('push %s %s', target.name, source.name)
count = target.pushItems(source.name, slot, qty) count = target.pushItems(source.name, slot, qty)
end end
end) end)
if not s and m then if not s and m then
_G._debug(m) _G._syslog(m)
end end
if count > 0 then if count > 0 then
@@ -510,7 +510,7 @@ function Storage:import(source, slot, count, item)
if amount > 0 then if amount > 0 then
self:updateCache(adapter, item, amount) self:updateCache(adapter, item, amount)
_G._debug('INS: %s(%d): %s[%d] -> %s in %s', _G._syslog('INS: %s(%d): %s[%d] -> %s in %s',
item.displayName or item.name, amount, item.displayName or item.name, amount,
self:_sn(source.name), slot, self:_sn(adapter.name), Util.round(timer(), 2)) self:_sn(source.name), slot, self:_sn(adapter.name), Util.round(timer(), 2))
@@ -557,7 +557,7 @@ function Storage:import(source, slot, count, item)
end end
if count ~= 0 then if count ~= 0 then
_G._debug('STORAGE warning: %s(%d): %s -> INSERT failed', _G._syslog('STORAGE warning: %s(%d): %s -> INSERT failed',
item.displayName or item.name, count, item.displayName or item.name, count,
self:_sn(source.name)) self:_sn(source.name))
end end
@@ -579,17 +579,17 @@ function Storage:trash(source, slot, count, item)
amount = target.adapter.pullItems(source.name, slot, count) amount = target.adapter.pullItems(source.name, slot, count)
end end
_G._debug('TRA: %s(%d): %s%s -> %s in %s', _G._syslog('TRA: %s(%d): %s%s -> %s in %s',
item.displayName or item.name, amount, self:_sn(source.name), item.displayName or item.name, amount, self:_sn(source.name),
slot and string.format('[%d]', slot) or '[*]', self:_sn(target.name), Util.round(timer(), 2)) slot and string.format('[%d]', slot) or '[*]', self:_sn(target.name), Util.round(timer(), 2))
end) end)
if not s and m then if not s and m then
_G._debug(m) _G._syslog(m)
end end
end end
if amount ~= count then if amount ~= count then
_G._debug('STORAGE warning: %s(%d): %s -> TRASH failed', _G._syslog('STORAGE warning: %s(%d): %s -> TRASH failed',
item.displayName or item.name, count - amount, item.displayName or item.name, count - amount,
self:_sn(source.name)) self:_sn(source.name))
end end

View File

@@ -68,7 +68,7 @@ function TaskRunner:run()
end end
function TaskRunner:onError(msg) function TaskRunner:onError(msg)
_G._debug(msg.errorMsg .. msg) _G._syslog(msg.errorMsg .. msg)
end end
return TaskRunner return TaskRunner

View File

@@ -82,7 +82,7 @@ local function backupNode(node)
} }
local s, m = pcall(function() local s, m = pcall(function()
if not node.adapter.isDiskPresent() then if not node.adapter.isDiskPresent() then
_G._debug('BACKUP error: No media present') _G._syslog('BACKUP error: No media present')
else else
local dir = node.adapter.getMountPath() local dir = node.adapter.getMountPath()
for _, v in pairs(files) do for _, v in pairs(files) do
@@ -91,7 +91,7 @@ local function backupNode(node)
end end
end) end)
if not s and m then if not s and m then
_G._debug('BACKUP error:' .. m) _G._syslog('BACKUP error:' .. m)
end end
end end
@@ -105,7 +105,7 @@ function BackupTask:cycle()
for node in context.storage:filterActive('backup') do for node in context.storage:filterActive('backup') do
if not drives[node.name] then if not drives[node.name] then
drives[node.name] = Event.onInterval(DAY, function() drives[node.name] = Event.onInterval(DAY, function()
_G._debug('BACKUP: started') _G._syslog('BACKUP: started')
if node.adapter and node.adapter.online then if node.adapter and node.adapter.online then
backupNode(node) backupNode(node)
end end

View File

@@ -75,7 +75,7 @@ function ImportTask:cycle(context)
end end
function tasks:onError(msg) function tasks:onError(msg)
_G._debug('IMPORT error: ' .. msg) _G._syslog('IMPORT error: ' .. msg)
end end
tasks:run() tasks:run()
end end

View File

@@ -11,7 +11,7 @@ function RefreshTask:cycle(context)
for node, adapter in context.storage:onlineAdapters() do for node, adapter in context.storage:onlineAdapters() do
if node.refreshInterval then if node.refreshInterval then
if not adapter.lastRefresh or adapter.lastRefresh + node.refreshInterval < now then if not adapter.lastRefresh or adapter.lastRefresh + node.refreshInterval < now then
_G._debug('REFRESHER: ' .. (node.displayName or node.name)) _G._syslog('REFRESHER: ' .. (node.displayName or node.name))
context.storage.dirty = true context.storage.dirty = true
adapter.dirty = true adapter.dirty = true
adapter.lastRefresh = now adapter.lastRefresh = now

View File

@@ -13,7 +13,7 @@ local function getNameSafe(v)
name = v.getName() name = v.getName()
end) end)
if not s then if not s then
_G._debug(m) _G._syslog(m)
end end
return name return name
end end
@@ -35,7 +35,7 @@ local function compactList(list)
end end
local function client(socket) local function client(socket)
_G._debug('REMOTE: connection from ' .. socket.dhost) _G._syslog('REMOTE: connection from ' .. socket.dhost)
local user = socket:read(2) local user = socket:read(2)
if not user then if not user then
@@ -44,7 +44,7 @@ local function client(socket)
local manipulator = getManipulatorForUser(user) local manipulator = getManipulatorForUser(user)
if not manipulator then if not manipulator then
_G._debug('REMOTE: Manipulator with introspection module bound with user not found. Closing connection.') _G._syslog('REMOTE: Manipulator with introspection module bound with user not found. Closing connection.')
socket:write({ socket:write({
msg = 'Manipulator not found' msg = 'Manipulator not found'
}) })
@@ -52,7 +52,7 @@ local function client(socket)
return return
end end
_G._debug('REMOTE: all good') _G._syslog('REMOTE: all good')
socket:write({ socket:write({
data = 'ok', data = 'ok',
}) })
@@ -166,7 +166,7 @@ local function client(socket)
end end
until not socket.connected until not socket.connected
_G._debug('REMOTE: disconnected from ' .. socket.dhost) _G._syslog('REMOTE: disconnected from ' .. socket.dhost)
end end
local handler local handler
@@ -174,7 +174,7 @@ local handler
local function listen() local function listen()
if device.wireless_modem then if device.wireless_modem then
handler = Event.addRoutine(function() handler = Event.addRoutine(function()
_G._debug('REMOTE: listening on port 4242') _G._syslog('REMOTE: listening on port 4242')
while true do while true do
local socket = Socket.server(4242) local socket = Socket.server(4242)
Event.addRoutine(function() Event.addRoutine(function()
@@ -191,7 +191,7 @@ Event.on({ 'device_attach', 'device_detach' }, function(_, name)
if handler then if handler then
handler:terminate() handler:terminate()
handler = nil handler = nil
_G._debug('REMOTE: wireless modem disconnected') _G._syslog('REMOTE: wireless modem disconnected')
else else
listen() listen()
end end

View File

@@ -36,7 +36,7 @@ Event.addRoutine(function()
end end
end) end)
if not s and m then if not s and m then
_G._debug(m) _G._syslog(m)
end end
end end
end end

View File

@@ -92,7 +92,7 @@ Event.onInterval(5, function()
end end
end) end)
if not s and m then if not s and m then
_G._debug(m) _G._syslog(m)
end end
end) end)

View File

@@ -590,7 +590,7 @@ Event.addRoutine(function()
{ x = mining.x, y = 0, z = mining.z } { x = mining.x, y = 0, z = mining.z }
) )
_G._debug({ distance = distance, maxDistance = maxDistance }) _G._syslog({ distance = distance, maxDistance = maxDistance })
if distance > maxDistance + 16 then if distance > maxDistance + 16 then
term.clear() term.clear()

View File

@@ -46,20 +46,19 @@ function Neural.launchTo(pt, strength)
Neural.launch(yaw, 225, strength or 1) Neural.launch(yaw, 225, strength or 1)
end end
function Neural.walkTo(pt, speed) function Neural.walkTo(pt, speed, radius)
Neural.walk(pt.x, pt.y, pt.z, speed) local x, z = pt.x, pt.z
os.sleep(1) if radius then
repeat until not Neural.isWalking() local angle = math.atan2(pt.x, pt.z)
end x = pt.x - ((radius or 1) * math.sin(angle))
z = pt.z - ((radius or 1) * math.cos(angle))
end
function Neural.walkAgainst(pt, radius, speed) if Neural.walk(x, pt.y, z, speed) then
local angle = math.atan2(pt.x, pt.z) os.sleep(1)
local x = pt.x - ((radius or 1) * math.sin(angle)) repeat until not Neural.isWalking()
local z = pt.z - ((radius or 1) * math.cos(angle)) return true
end
Neural.walk(x, 0, z, speed)
os.sleep(1)
repeat until not Neural.isWalking()
end end
-- flatten equipment functions -- flatten equipment functions
@@ -118,9 +117,9 @@ function Neural.reload()
}) })
end end
function Neural.testWalk() function Neural.testWalk(name, speed, radius)
local e = Neural.getMetaByName('kepler155c') local e = Neural.getMetaByName(name)
Neural.walkAgainst(e) Neural.walkTo(e, speed, radius)
end end
return Neural.reload() return Neural.reload()

View File

@@ -20,14 +20,11 @@ neural.assertModules({
local function dropOff() local function dropOff()
print('dropping') print('dropping')
local blocks = neural.scan() local b = Util.find(neural.scan(), 'name', 'minecraft:hopper')
local b = Util.find(blocks, 'name', 'minecraft:hopper')
if b then if b then
neural.walkTo({ x = b.x, y = 0, z = b.z }) neural.walkTo({ x = b.x, y = 0, z = b.z }, 2)
blocks = neural.scan() b = Util.find(neural.scan(), 'name', 'minecraft:hopper')
b = Util.find(blocks, 'name', 'minecraft:hopper')
if b and math.abs(b.x) < 1 and math.abs(b.z) < 1 then if b and math.abs(b.x) < 1 and math.abs(b.z) < 1 then
print('dropped') print('dropped')
neural.getEquipment().drop(1) neural.getEquipment().drop(1)
@@ -40,7 +37,7 @@ end
local function pickup(id) local function pickup(id)
local b = neural.getMetaByID(id) local b = neural.getMetaByID(id)
if b then if b then
neural.walkTo(b) neural.walkTo(b, 2)
local amount = neural.getEquipment().suck() local amount = neural.getEquipment().suck()
print('sucked: ' .. amount) print('sucked: ' .. amount)
@@ -53,8 +50,7 @@ end
while true do while true do
local sensed = Util.reduce(neural.sense(), function(acc, s) local sensed = Util.reduce(neural.sense(), function(acc, s)
s.y = Util.round(s.y) if Util.round(s.y) == 0 and s.name == 'Item' then
if s.y == 0 and s.name == 'Item' then
acc[s.id] = s acc[s.id] = s
end end
return acc return acc

View File

@@ -9,7 +9,7 @@ local Util = require('util')
local os = _G.os local os = _G.os
local BREEDING = 'Cow' local BREEDING = 'Cow'
local WALK_SPEED = 1.5 local WALK_SPEED = 1.5
local MAX_GROWN = 12 local MAX_GROWN = 12
@@ -54,7 +54,7 @@ local function breed(entity)
entity.lastFed = os.clock() entity.lastFed = os.clock()
fed[entity.id] = entity fed[entity.id] = entity
neural.walkAgainst(entity, 1, WALK_SPEED) neural.walkTo(entity, WALK_SPEED, 1)
entity = neural.getMetaByID(entity.id) entity = neural.getMetaByID(entity.id)
if entity then if entity then
neural.lookAt(entity) neural.lookAt(entity)
@@ -65,7 +65,7 @@ end
local function kill(entity) local function kill(entity)
print('killing') print('killing')
neural.walkAgainst(entity, 2.5, WALK_SPEED) neural.walkTo(entity, WALK_SPEED, 2.5)
entity = neural.getMetaByID(entity.id) entity = neural.getMetaByID(entity.id)
if entity then if entity then
neural.lookAt(entity) neural.lookAt(entity)

171
neural/rabbitRancher.lua Normal file
View File

@@ -0,0 +1,171 @@
--[[
Breed rabbits with a rabbit.
]]
local neural = require('neural.interface')
local Point = require('point')
local Sound = require('sound')
local Util = require('util')
local os = _G.os
local BREEDING = 'Rabbit'
local WALK_SPEED = 2
local MAX_GROWN = 18
neural.assertModules({
'plethora:sensor',
'plethora:scanner',
'plethora:laser',
'plethora:kinetic',
'plethora:introspection',
})
local ID = neural.getID()
local fed = { }
local function resupply()
local slot = neural.getEquipment().list()[1]
if slot and slot.count > 32 then
return
end
print('resupplying')
local dispenser = Util.find(neural.scan(), 'name', 'minecraft:wooden_pressure_plate')
if dispenser then
if math.abs(dispenser.x) > 1 or math.abs(dispenser.z) > 1 then
neural.walkTo({ x = dispenser.x, y = 0, z = dispenser.z }, WALK_SPEED)
end
neural.lookAt(dispenser)
neural.getEquipment().suck(1, 64)
end
end
local function breed(entity)
print('breeding')
entity.lastFed = os.clock()
fed[entity.id] = entity
neural.walkTo(entity, WALK_SPEED, 1)
entity = neural.getMetaByID(entity.id)
if entity and not entity.isChild then
neural.lookAt(entity)
neural.use(1)
os.sleep(.1)
end
end
local function kill(entity)
print('killing')
neural.walkTo(entity, WALK_SPEED, 2.5)
entity = neural.getMetaByID(entity.id)
if entity and not entity.isChild then
neural.lookAt(entity)
neural.fireAt({ x = entity.x, y = 0, z = entity.z })
Sound.play('entity.firework.launch')
os.sleep(.2)
end
end
local function getEntities()
return Util.filter(neural.sense(), function(entity)
if entity.name == BREEDING and entity.y > -.5 and entity.id ~= ID then
return true
end
end)
end
local function getHungry(entities)
for _,v in pairs(entities) do
if not fed[v.id] or os.clock() - fed[v.id].lastFed > 90 then
return v
end
end
end
local function randomEntity(entities)
local r = math.random(1, Util.size(entities))
local i = 1
for _, v in pairs(entities) do
i = i + 1
if i > r then
return v
end
end
end
local function dropOff()
print('dropping')
if neural.getEquipment().list()[2] then
local b = Util.find(neural.scan(), 'name', 'minecraft:hopper')
if b then
neural.walkTo({ x = b.x, y = 0, z = b.z }, 2)
b = Util.find(neural.scan(), 'name', 'minecraft:hopper')
if b and math.abs(b.x) < 1 and math.abs(b.z) < 1 then
print('dropped')
neural.getEquipment().drop(2)
end
end
end
end
local function pickup(id)
local b = neural.getMetaByID(id)
if b then
neural.walkTo(b, 2)
local main = neural.getEquipment().list()[1]
local amount = neural.getEquipment().suck(not main and 2 or nil)
print('sucked: ' .. amount)
if amount > 0 then
Sound.play('entity.item.pickup')
return true
end
end
end
local function drops()
local sensed = Util.reduce(neural.sense(), function(acc, s)
if Util.round(s.y) == 0 and s.name == 'Item' then
acc[s.id] = s
end
return acc
end, { })
local pt = { x = 0, y = 0, z = 0 }
while true do
local b = Point.closest(pt, sensed)
if not b then
break
end
sensed[b.id] = nil
if pickup(b.id) then
pt = b
else
dropOff()
break
end
end
end
while true do
resupply()
local entities = getEntities()
if Util.size(entities) > MAX_GROWN then
kill(randomEntity(entities))
else
local entity = getHungry(entities)
if entity then
breed(entity)
else
print('sleeping')
os.sleep(5)
end
drops()
end
end

View File

@@ -294,7 +294,6 @@ local function craftItem(ikey, item, items, machineStatus)
local ingredient = itemDB:get(key) local ingredient = itemDB:get(key)
-- local c = item.craftable * qty -- local c = item.craftable * qty
-- while c > 0 do -- while c > 0 do
--debug(key)
inventoryAdapter:provide(ingredient, maxCount * qty, slot) inventoryAdapter:provide(ingredient, maxCount * qty, slot)
if turtle.getItemCount(slot) ~= maxCount * qty then if turtle.getItemCount(slot) ~= maxCount * qty then
item.status = 'Extract failed: ' .. (ingredient.displayName or itemDB:getName(ingredient)) item.status = 'Extract failed: ' .. (ingredient.displayName or itemDB:getName(ingredient))

View File

@@ -71,7 +71,7 @@ local function turtleCraft(recipe, qty, inventoryAdapter)
inventoryAdapter:provide(item, provideQty, k) inventoryAdapter:provide(item, provideQty, k)
if turtle.getItemCount(k) == 0 then -- ~= qty then if turtle.getItemCount(k) == 0 then -- ~= qty then
-- FIX: ingredients cannot be stacked -- FIX: ingredients cannot be stacked
--debug('failed ' .. v .. ' - ' .. provideQty) --_G._syslog('failed ' .. v .. ' - ' .. provideQty)
return false return false
end end
end end

View File

@@ -1208,8 +1208,8 @@ local function learnRecipe(page)
end end
if not recipe then if not recipe then
_debug(results) _G._syslog(results)
_debug(newRecipe) _G._syslog(newRecipe)
error('Failed - view system log') error('Failed - view system log')
end end
@@ -1437,7 +1437,7 @@ listingPage:setFocus(listingPage.statusBar.filter)
--[[ --[[
Event.on('modem_message', function(e, side, sport, dport, item) Event.on('modem_message', function(e, side, sport, dport, item)
debug({ e, side, sport, dport, item }) _syslog({ e, side, sport, dport, item })
if dport == 205 and type(item) == 'table' then if dport == 205 and type(item) == 'table' then
inventoryAdapter:provide( inventoryAdapter:provide(
item, item,

View File

@@ -22,7 +22,7 @@ local wizardPage = UI.WizardPage {
[2] = UI.TextEntry { [2] = UI.TextEntry {
formLabel = 'Password', formKey = 'password', formLabel = 'Password', formKey = 'password',
shadowText = 'password', shadowText = 'password',
limit = 64, limit = 256,
required = true, required = true,
help = 'Krist wallet password', help = 'Krist wallet password',
}, },

View File

@@ -32,8 +32,6 @@ end
local function findID(url) local function findID(url)
local found = gfind(url, idPatt) local found = gfind(url, idPatt)
local id = tonumber(found[#found]:sub(found[#found]:find("%d+"))) local id = tonumber(found[#found]:sub(found[#found]:find("%d+")))
--_debug('id: ')
--_debug(id)
return id return id
end end