78 lines
1.7 KiB
Lua
78 lines
1.7 KiB
Lua
local config = {}
|
|
|
|
function log(text)
|
|
--print("[" .. os.date("%H:%M:%S") .. "] " .. text)
|
|
end
|
|
|
|
|
|
-- 保存配置文件
|
|
local function saveConfig()
|
|
local file = fs.open(".key_config", "w")
|
|
file.write(textutils.serialize(config))
|
|
file.close()
|
|
end
|
|
|
|
-- 加载或创建配置文件
|
|
local function loadOrCreateConfig()
|
|
if fs.exists(".key_config") then
|
|
local file = fs.open(".key_config", "r")
|
|
local content = file.readAll()
|
|
file.close()
|
|
config = textutils.unserialize(content)
|
|
log("Config loaded")
|
|
else
|
|
log("Creating default config...")
|
|
config = {
|
|
protocol = "wireless_keyboard",
|
|
external_program = "shell", -- 默认外部程序
|
|
}
|
|
saveConfig()
|
|
log("Default config created")
|
|
end
|
|
end
|
|
|
|
|
|
|
|
-- 初始化 rednet
|
|
local function initRednet()
|
|
peripheral.find("modem", rednet.open)
|
|
end
|
|
|
|
-- 网络监听函数
|
|
local function networkListener()
|
|
while true do
|
|
local senderId, message, protocol = rednet.receive()
|
|
|
|
if protocol == config.protocol and message.type then
|
|
-- 注入事件到本机事件队列
|
|
|
|
os.queueEvent(message.type, table.unpack(message.args[1]))
|
|
|
|
log("Event from ID " .. senderId .. ": " .. message.type)
|
|
end
|
|
end
|
|
end
|
|
|
|
-- 外部程序运行函数
|
|
local function runExternalProgram()
|
|
shell.run(config.external_program)
|
|
end
|
|
|
|
-- 主函数
|
|
local function main()
|
|
loadOrCreateConfig()
|
|
initRednet()
|
|
|
|
log("=== Wireless Keyboard Server ===")
|
|
log("Protocol: " .. config.protocol)
|
|
log("External program: " .. config.external_program)
|
|
log("")
|
|
|
|
-- 并行执行网络监听和外部程序
|
|
parallel.waitForAny(networkListener, runExternalProgram)
|
|
|
|
log("Server stopped")
|
|
rednet.close()
|
|
end
|
|
|
|
main() |