opus/sys/modules/opus/peripheral.lua

127 lines
2.2 KiB
Lua
Raw Normal View History

local Util = require('opus.util')
2017-10-08 21:45:01 +00:00
local Peripheral = Util.shallowCopy(_G.peripheral)
2017-04-01 23:21:49 +00:00
2017-10-08 21:45:01 +00:00
function Peripheral.getList()
2018-01-24 22:39:38 +00:00
if _G.device then
return _G.device
end
2017-04-01 23:21:49 +00:00
2018-01-24 22:39:38 +00:00
local deviceList = { }
for _,side in pairs(Peripheral.getNames()) do
Peripheral.addDevice(deviceList, side)
end
2017-04-01 23:21:49 +00:00
2018-01-24 22:39:38 +00:00
return deviceList
2017-04-01 23:21:49 +00:00
end
function Peripheral.addDevice(deviceList, side)
2018-01-24 22:39:38 +00:00
local name = side
2019-04-07 14:09:47 +00:00
pcall(function()
local ptype = Peripheral.getType(side)
local dev = Peripheral.wrap(side)
2018-01-24 22:39:38 +00:00
2019-04-07 14:09:47 +00:00
if not ptype or not dev then
return
end
2018-01-24 22:39:38 +00:00
2019-04-07 14:09:47 +00:00
if ptype == 'modem' then
if not Peripheral.call(name, 'isWireless') then
-- ptype = 'wireless_modem'
-- else
ptype = 'wired_modem'
2019-04-18 15:13:28 +00:00
if dev.isAccessPoint then
2019-04-07 14:09:47 +00:00
-- avoid open computer relays being registered
-- as 'wired_modem'
ptype = dev.getMetadata().name or 'wired_modem'
end
end
2018-01-24 22:39:38 +00:00
end
2019-04-07 14:09:47 +00:00
local sides = {
front = true,
back = true,
top = true,
bottom = true,
left = true,
right = true
}
if sides[name] then
local i = 1
local uniqueName = ptype
while deviceList[uniqueName] do
uniqueName = ptype .. '_' .. i
i = i + 1
end
name = uniqueName
2018-01-24 22:39:38 +00:00
end
2019-04-07 14:09:47 +00:00
-- this can randomly fail
if not deviceList[name] then
deviceList[name] = dev
if deviceList[name] then
Util.merge(deviceList[name], {
name = name,
type = ptype,
side = side,
})
end
2018-12-02 00:09:24 +00:00
end
2019-04-07 14:09:47 +00:00
end)
2018-12-02 00:09:24 +00:00
return deviceList[name]
2016-12-11 19:24:52 +00:00
end
function Peripheral.getBySide(side)
2018-01-24 22:39:38 +00:00
return Util.find(Peripheral.getList(), 'side', side)
2016-12-11 19:24:52 +00:00
end
function Peripheral.getByType(typeName)
2018-01-24 22:39:38 +00:00
return Util.find(Peripheral.getList(), 'type', typeName)
2016-12-11 19:24:52 +00:00
end
function Peripheral.getByMethod(method)
2018-01-24 22:39:38 +00:00
for _,p in pairs(Peripheral.getList()) do
if p[method] then
return p
end
end
2016-12-11 19:24:52 +00:00
end
-- match any of the passed arguments
function Peripheral.get(args)
2018-01-24 22:39:38 +00:00
if type(args) == 'string' then
args = { type = args }
end
if args.name then
return _G.device[args.name]
end
if args.type then
local p = Peripheral.getByType(args.type)
if p then
return p
end
end
if args.method then
local p = Peripheral.getByMethod(args.method)
if p then
return p
end
end
if args.side then
local p = Peripheral.getBySide(args.side)
if p then
return p
end
end
2016-12-11 19:24:52 +00:00
end
return Peripheral