1
0
mirror of https://github.com/kepler155c/opus synced 2024-09-29 23:40:41 +00:00
opus/sys/network/peripheral.lua

87 lines
2.0 KiB
Lua
Raw Normal View History

2018-01-06 11:07:49 +00:00
--[[
2018-01-24 22:39:38 +00:00
Allow sharing of local peripherals.
2018-01-06 11:07:49 +00:00
]]--
local Event = require('event')
local Peripheral = require('peripheral')
local Socket = require('socket')
Event.addRoutine(function()
2018-01-24 22:39:38 +00:00
print('peripheral: listening on port 189')
while true do
local socket = Socket.server(189)
2018-01-06 11:07:49 +00:00
2018-01-24 22:39:38 +00:00
print('peripheral: connection from ' .. socket.dhost)
2018-01-06 11:07:49 +00:00
2018-01-24 22:39:38 +00:00
Event.addRoutine(function()
local uri = socket:read(2)
if uri then
local peripheral = Peripheral.lookup(uri)
2018-01-06 11:07:49 +00:00
-- only 1 proxy of this device can happen at one time
-- need to prevent multiple shares
2018-01-24 22:39:38 +00:00
if not peripheral then
print('peripheral: invalid peripheral ' .. uri)
socket:write('Invalid peripheral: ' .. uri)
else
print('peripheral: proxing ' .. uri)
local proxy = {
methods = { }
}
2018-01-06 11:07:49 +00:00
2018-01-24 22:39:38 +00:00
if peripheral.blit then
--peripheral = Util.shallowCopy(peripheral)
peripheral.fastBlit = function(data)
for _,v in ipairs(data) do
peripheral[v.fn](unpack(v.args))
end
end
end
2018-01-06 11:07:49 +00:00
2018-01-24 22:39:38 +00:00
for k,v in pairs(peripheral) do
if type(v) == 'function' then
table.insert(proxy.methods, k)
else
proxy[k] = v
end
end
2018-01-06 11:07:49 +00:00
2018-01-24 22:39:38 +00:00
socket:write(proxy)
2018-01-06 11:07:49 +00:00
2018-01-24 22:39:38 +00:00
if proxy.type == 'monitor' then
peripheral.eventChannel = function(...)
socket:write({
fn = 'event',
data = { ... }
})
end
end
2018-01-06 11:07:49 +00:00
2018-01-24 22:39:38 +00:00
while true do
local data = socket:read()
if not data then
print('peripheral: lost connection from ' .. socket.dhost)
break
end
if not _G.device[peripheral.name] then
print('periperal: detached')
socket:close()
break
end
if peripheral[data.fn] then
2018-02-06 13:45:43 +00:00
-- need to trigger an error on the other end
-- local s, m = pcall()
2018-01-24 22:39:38 +00:00
socket:write({ peripheral[data.fn](table.unpack(data.args)) })
2018-02-06 13:45:43 +00:00
else
socket:write({ false, "Invalid function: " .. data.fn })
2018-01-24 22:39:38 +00:00
end
end
2018-01-24 22:39:38 +00:00
peripheral.eventChannel = nil
peripheral.fastBlit = nil
end
end
end)
end
2018-01-06 11:07:49 +00:00
end)