Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local robot = require("robot")
- local event = require("event")
- local fs = require("filesystem")
- local port = 512
- local keyWord = "ECSGrief"
- local modem
- local redstoneState = false
- if component.isAvailable("modem") then
- modem = component.modem
- else
- error("Требуется беспроводной модем!")
- end
- local redstone = nil
- if component.isAvailable("redstone") then
- redstone = component.redstone
- end
- local crafting = nil
- if component.isAvailable("crafting") then
- crafting = component.crafting
- end
- local invController = nil
- if component.isAvailable("inventory_controller") then
- invController = component.inventory_controller
- end
- modem.open(port)
- -------------------------------------------------------------------------------------
- local function reportError(context, err)
- local msg = "ERROR: [" .. context .. "] " .. tostring(err)
- print(msg)
- pcall(function() modem.broadcast(port, keyWord, msg) end)
- end
- local function reportInfo(msg)
- print("[INFO] " .. msg)
- pcall(function() modem.broadcast(port, keyWord, "INFO: " .. msg) end)
- end
- local function safeCall(context, fn)
- local ok, err = pcall(fn)
- if not ok then
- reportError(context, err)
- end
- end
- -------------------------------------------------------------------------------------
- local moveCommands = {
- forward = robot.forward,
- back = robot.back,
- turnRight = robot.turnRight,
- turnLeft = robot.turnLeft,
- up = robot.up,
- down = robot.down,
- }
- local swingFuncs = {
- forward = robot.swing,
- up = robot.swingUp,
- down = robot.swingDown,
- }
- local useFuncs = {
- forward = robot.use,
- up = robot.useUp,
- down = robot.useDown,
- }
- local placeFuncs = {
- forward = robot.place,
- up = robot.placeUp,
- down = robot.placeDown,
- }
- local suckFuncs = {
- forward = robot.suck,
- up = robot.suckUp,
- down = robot.suckDown,
- }
- local function parseMessage(message)
- local action, rest = message:match("^([^:]+):(.+)$")
- if action and rest then
- return action, rest
- end
- return message, nil
- end
- local function redstoneControl()
- if not redstone then
- reportError("redstone", "компонент redstone не установлен")
- return
- end
- if redstoneState then
- for i = 0, 5 do redstone.setOutput(i, 0) end
- reportInfo("Редстоун-сигнал выключен.")
- redstoneState = false
- else
- for i = 0, 5 do redstone.setOutput(i, 15) end
- reportInfo("Редстоун-сигнал включён.")
- redstoneState = true
- end
- end
- local function doCraft()
- if not crafting then
- reportError("craft", "крафтинг-апгрейд не установлен")
- return
- end
- local ok, result = pcall(function() return crafting.craft() end)
- if not ok then
- reportError("craft", result)
- elseif result then
- reportInfo("Крафт успешен!")
- else
- reportInfo("Крафт не удался. Проверь ингредиенты в слотах 1-9.")
- end
- end
- -- Сканирует инвентарь и возвращает таблицу занятых слотов
- local function scanInventory()
- local found = {}
- local invSize = robot.inventorySize()
- for slot = 1, invSize do
- local count = robot.count(slot)
- if count > 0 then
- local name = "Слот " .. slot -- fallback без inventory_controller
- if invController then
- local ok, stack = pcall(function()
- return invController.getStackInInternalSlot(slot)
- end)
- if ok and stack and stack.label then
- name = stack.label
- elseif ok and stack and stack.name then
- name = stack.name
- end
- end
- table.insert(found, { slot = slot, count = count, name = name })
- end
- end
- return found
- end
- -- Обрабатывает команду placeQuery: сканирует и отвечает пульту
- local function handlePlaceQuery(dir)
- local items = scanInventory()
- if #items == 0 then
- modem.broadcast(port, keyWord, "INVEMPTY")
- print("[place] Инвентарь пуст.")
- return
- end
- if #items == 1 then
- -- Один предмет — сразу ставим
- local item = items[1]
- robot.select(item.slot)
- local fn = placeFuncs[dir]
- if fn then
- local ok, err = pcall(fn)
- if ok then
- reportInfo("Поставлен: " .. item.name .. " " .. dir)
- else
- reportError("place", tostring(err))
- end
- else
- reportError("place", "недопустимое направление: " .. tostring(dir))
- end
- modem.broadcast(port, keyWord, "INVONE:" .. item.name .. " x" .. item.count)
- return
- end
- -- Несколько предметов — шлём список пульту
- local parts = {}
- for i, item in ipairs(items) do
- table.insert(parts, i .. "=" .. item.name .. "(" .. item.count .. ")")
- end
- -- Сохраняем список в upvalue для handlePlaceChosen
- modem.broadcast(port, keyWord, "INVLIST:" .. table.concat(parts, "|"))
- print("[place] Отправлен список (" .. #items .. " предметов), ожидаю выбор...")
- end
- -- Когда пульт прислал выбранный слот
- local function handlePlaceChosen(rest)
- -- rest = "слот:dir"
- local slotStr, dir = rest:match("^(%d+):(.+)$")
- if not slotStr or not dir then
- reportError("placeChosen", "неверный формат: " .. tostring(rest))
- return
- end
- local slot = tonumber(slotStr)
- local fn = placeFuncs[dir]
- if not fn then
- reportError("placeChosen", "недопустимое направление: " .. tostring(dir))
- return
- end
- robot.select(slot)
- local ok, err = pcall(fn)
- if ok then
- reportInfo("Поставлен блок из слота " .. slot .. " " .. dir)
- else
- reportError("placeChosen", tostring(err))
- end
- end
- -------------------------------------------------------------------------------------
- local function handleMessage(message)
- local action, rest = parseMessage(message)
- if moveCommands[action] then
- safeCall(action, moveCommands[action])
- elseif action == "swing" then
- local fn = swingFuncs[rest]
- if fn then safeCall("swing:" .. rest, fn)
- else reportError("swing", "недопустимое направление: " .. tostring(rest)) end
- elseif action == "use" then
- local fn = useFuncs[rest]
- if fn then safeCall("use:" .. rest, fn)
- else reportError("use", "недопустимое направление: " .. tostring(rest)) end
- elseif action == "placeQuery" then
- safeCall("placeQuery", function() handlePlaceQuery(rest) end)
- elseif action == "placeChosen" then
- safeCall("placeChosen", function() handlePlaceChosen(rest) end)
- elseif action == "placeCancel" then
- print("[place] Установка отменена пультом.")
- elseif action == "suck" then
- local fn = suckFuncs[rest]
- if fn then safeCall("suck:" .. rest, fn)
- else reportError("suck", "недопустимое направление: " .. tostring(rest)) end
- elseif action == "craft" then
- safeCall("craft", doCraft)
- elseif action == "redstone" then
- safeCall("redstone", redstoneControl)
- elseif action == "ping" then
- pcall(function() modem.broadcast(port, keyWord, "pong") end)
- print("Получен ping, отправлен pong.")
- elseif action == "exit" then
- return true
- elseif action == "selfDestroy" then
- safeCall("selfDestroy", function()
- for file in fs.list("") do
- print("Уничтожаю \"" .. file .. "\"")
- fs.remove(file)
- end
- require("term").clear()
- require("computer").shutdown()
- end)
- else
- reportError("receive", "неизвестная команда: " .. tostring(message))
- end
- return false
- end
- -------------------------------------------------------------------------------------
- local function receive()
- while true do
- local ok, ev = pcall(function() return { event.pull() } end)
- if not ok then
- reportError("event.pull", tostring(ev))
- else
- if ev[1] == "modem_message"
- and ev[4] == port
- and ev[6] == keyWord then
- local shouldExit = false
- local ok2, err2 = pcall(function()
- shouldExit = handleMessage(ev[7])
- end)
- if not ok2 then
- reportError("handleMessage", err2)
- end
- if shouldExit then return end
- end
- end
- end
- end
- -------------------------------------------------------------------------------------
- local function main()
- print(" ")
- print("ECS Receiver v1.5 — ожидание команд...")
- if crafting then
- print("Крафтинг-апгрейд: OK")
- else
- print("Крафтинг-апгрейд: не найден")
- end
- if invController then
- print("Inventory Controller: OK (имена предметов доступны)")
- else
- print("Inventory Controller: не найден (будут показаны только номера слотов)")
- end
- print(" ")
- while true do
- local ok, err = pcall(receive)
- if not ok then
- reportError("receive_loop", err)
- print("Перезапуск через 2 сек...")
- os.sleep(2)
- else
- break
- end
- end
- print(" ")
- print("Программа завершена.")
- end
- main()
Add Comment
Please, Sign In to add comment