1
0
mirror of https://github.com/kepler155c/opus synced 2024-11-15 05:04:50 +00:00
opus/sys/apis/peripheral.lua

121 lines
2.0 KiB
Lua
Raw Normal View History

2018-01-06 11:07:49 +00:00
local Util = require('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
local ptype = Peripheral.getType(side)
if not ptype then
return
end
if ptype == 'modem' then
2018-11-11 19:45:04 +00:00
if not Peripheral.call(name, 'isWireless') then
-- ptype = 'wireless_modem'
-- else
2018-01-24 22:39:38 +00:00
ptype = 'wired_modem'
end
end
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
end
2018-02-24 14:38:02 +00:00
-- this can randomly fail
2018-12-02 00:09:24 +00:00
if not deviceList[name] then
pcall(function()
deviceList[name] = Peripheral.wrap(side)
end)
if deviceList[name] then
Util.merge(deviceList[name], {
name = name,
type = ptype,
side = side,
})
end
2018-01-24 22:39:38 +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