Ewgeniy

receive

Feb 10th, 2023 (edited)
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 10.29 KB | None | 0 0
  1. local component = require("component")
  2. local robot = require("robot")
  3. local event = require("event")
  4. local fs = require("filesystem")
  5. local port = 512
  6. local keyWord = "ECSGrief"
  7. local modem
  8. local redstoneState = false
  9.  
  10. if component.isAvailable("modem") then
  11.     modem = component.modem
  12. else
  13.     error("Требуется беспроводной модем!")
  14. end
  15.  
  16. local redstone = nil
  17. if component.isAvailable("redstone") then
  18.     redstone = component.redstone
  19. end
  20.  
  21. local crafting = nil
  22. if component.isAvailable("crafting") then
  23.     crafting = component.crafting
  24. end
  25.  
  26. local invController = nil
  27. if component.isAvailable("inventory_controller") then
  28.     invController = component.inventory_controller
  29. end
  30.  
  31. modem.open(port)
  32.  
  33. -------------------------------------------------------------------------------------
  34.  
  35. local function reportError(context, err)
  36.     local msg = "ERROR: [" .. context .. "] " .. tostring(err)
  37.     print(msg)
  38.     pcall(function() modem.broadcast(port, keyWord, msg) end)
  39. end
  40.  
  41. local function reportInfo(msg)
  42.     print("[INFO] " .. msg)
  43.     pcall(function() modem.broadcast(port, keyWord, "INFO: " .. msg) end)
  44. end
  45.  
  46. local function safeCall(context, fn)
  47.     local ok, err = pcall(fn)
  48.     if not ok then
  49.         reportError(context, err)
  50.     end
  51. end
  52.  
  53. -------------------------------------------------------------------------------------
  54.  
  55. local moveCommands = {
  56.     forward   = robot.forward,
  57.     back      = robot.back,
  58.     turnRight = robot.turnRight,
  59.     turnLeft  = robot.turnLeft,
  60.     up        = robot.up,
  61.     down      = robot.down,
  62. }
  63.  
  64. local swingFuncs = {
  65.     forward = robot.swing,
  66.     up      = robot.swingUp,
  67.     down    = robot.swingDown,
  68. }
  69.  
  70. local useFuncs = {
  71.     forward = robot.use,
  72.     up      = robot.useUp,
  73.     down    = robot.useDown,
  74. }
  75.  
  76. local placeFuncs = {
  77.     forward = robot.place,
  78.     up      = robot.placeUp,
  79.     down    = robot.placeDown,
  80. }
  81.  
  82. local suckFuncs = {
  83.     forward = robot.suck,
  84.     up      = robot.suckUp,
  85.     down    = robot.suckDown,
  86. }
  87.  
  88. local function parseMessage(message)
  89.     local action, rest = message:match("^([^:]+):(.+)$")
  90.     if action and rest then
  91.         return action, rest
  92.     end
  93.     return message, nil
  94. end
  95.  
  96. local function redstoneControl()
  97.     if not redstone then
  98.         reportError("redstone", "компонент redstone не установлен")
  99.         return
  100.     end
  101.     if redstoneState then
  102.         for i = 0, 5 do redstone.setOutput(i, 0) end
  103.         reportInfo("Редстоун-сигнал выключен.")
  104.         redstoneState = false
  105.     else
  106.         for i = 0, 5 do redstone.setOutput(i, 15) end
  107.         reportInfo("Редстоун-сигнал включён.")
  108.         redstoneState = true
  109.     end
  110. end
  111.  
  112. local function doCraft()
  113.     if not crafting then
  114.         reportError("craft", "крафтинг-апгрейд не установлен")
  115.         return
  116.     end
  117.     local ok, result = pcall(function() return crafting.craft() end)
  118.     if not ok then
  119.         reportError("craft", result)
  120.     elseif result then
  121.         reportInfo("Крафт успешен!")
  122.     else
  123.         reportInfo("Крафт не удался. Проверь ингредиенты в слотах 1-9.")
  124.     end
  125. end
  126.  
  127. -- Сканирует инвентарь и возвращает таблицу занятых слотов
  128. local function scanInventory()
  129.     local found = {}
  130.     local invSize = robot.inventorySize()
  131.     for slot = 1, invSize do
  132.         local count = robot.count(slot)
  133.         if count > 0 then
  134.             local name = "Слот " .. slot  -- fallback без inventory_controller
  135.             if invController then
  136.                 local ok, stack = pcall(function()
  137.                     return invController.getStackInInternalSlot(slot)
  138.                 end)
  139.                 if ok and stack and stack.label then
  140.                     name = stack.label
  141.                 elseif ok and stack and stack.name then
  142.                     name = stack.name
  143.                 end
  144.             end
  145.             table.insert(found, { slot = slot, count = count, name = name })
  146.         end
  147.     end
  148.     return found
  149. end
  150.  
  151. -- Обрабатывает команду placeQuery: сканирует и отвечает пульту
  152. local function handlePlaceQuery(dir)
  153.     local items = scanInventory()
  154.  
  155.     if #items == 0 then
  156.         modem.broadcast(port, keyWord, "INVEMPTY")
  157.         print("[place] Инвентарь пуст.")
  158.         return
  159.     end
  160.  
  161.     if #items == 1 then
  162.         -- Один предмет — сразу ставим
  163.         local item = items[1]
  164.         robot.select(item.slot)
  165.         local fn = placeFuncs[dir]
  166.         if fn then
  167.             local ok, err = pcall(fn)
  168.             if ok then
  169.                 reportInfo("Поставлен: " .. item.name .. " " .. dir)
  170.             else
  171.                 reportError("place", tostring(err))
  172.             end
  173.         else
  174.             reportError("place", "недопустимое направление: " .. tostring(dir))
  175.         end
  176.         modem.broadcast(port, keyWord, "INVONE:" .. item.name .. " x" .. item.count)
  177.         return
  178.     end
  179.  
  180.     -- Несколько предметов — шлём список пульту
  181.     local parts = {}
  182.     for i, item in ipairs(items) do
  183.         table.insert(parts, i .. "=" .. item.name .. "(" .. item.count .. ")")
  184.     end
  185.     -- Сохраняем список в upvalue для handlePlaceChosen
  186.     modem.broadcast(port, keyWord, "INVLIST:" .. table.concat(parts, "|"))
  187.     print("[place] Отправлен список (" .. #items .. " предметов), ожидаю выбор...")
  188. end
  189.  
  190. -- Когда пульт прислал выбранный слот
  191. local function handlePlaceChosen(rest)
  192.     -- rest = "слот:dir"
  193.     local slotStr, dir = rest:match("^(%d+):(.+)$")
  194.     if not slotStr or not dir then
  195.         reportError("placeChosen", "неверный формат: " .. tostring(rest))
  196.         return
  197.     end
  198.     local slot = tonumber(slotStr)
  199.     local fn = placeFuncs[dir]
  200.     if not fn then
  201.         reportError("placeChosen", "недопустимое направление: " .. tostring(dir))
  202.         return
  203.     end
  204.     robot.select(slot)
  205.     local ok, err = pcall(fn)
  206.     if ok then
  207.         reportInfo("Поставлен блок из слота " .. slot .. " " .. dir)
  208.     else
  209.         reportError("placeChosen", tostring(err))
  210.     end
  211. end
  212.  
  213. -------------------------------------------------------------------------------------
  214.  
  215. local function handleMessage(message)
  216.     local action, rest = parseMessage(message)
  217.  
  218.     if moveCommands[action] then
  219.         safeCall(action, moveCommands[action])
  220.  
  221.     elseif action == "swing" then
  222.         local fn = swingFuncs[rest]
  223.         if fn then safeCall("swing:" .. rest, fn)
  224.         else reportError("swing", "недопустимое направление: " .. tostring(rest)) end
  225.  
  226.     elseif action == "use" then
  227.         local fn = useFuncs[rest]
  228.         if fn then safeCall("use:" .. rest, fn)
  229.         else reportError("use", "недопустимое направление: " .. tostring(rest)) end
  230.  
  231.     elseif action == "placeQuery" then
  232.         safeCall("placeQuery", function() handlePlaceQuery(rest) end)
  233.  
  234.     elseif action == "placeChosen" then
  235.         safeCall("placeChosen", function() handlePlaceChosen(rest) end)
  236.  
  237.     elseif action == "placeCancel" then
  238.         print("[place] Установка отменена пультом.")
  239.  
  240.     elseif action == "suck" then
  241.         local fn = suckFuncs[rest]
  242.         if fn then safeCall("suck:" .. rest, fn)
  243.         else reportError("suck", "недопустимое направление: " .. tostring(rest)) end
  244.  
  245.     elseif action == "craft" then
  246.         safeCall("craft", doCraft)
  247.  
  248.     elseif action == "redstone" then
  249.         safeCall("redstone", redstoneControl)
  250.  
  251.     elseif action == "ping" then
  252.         pcall(function() modem.broadcast(port, keyWord, "pong") end)
  253.         print("Получен ping, отправлен pong.")
  254.  
  255.     elseif action == "exit" then
  256.         return true
  257.  
  258.     elseif action == "selfDestroy" then
  259.         safeCall("selfDestroy", function()
  260.             for file in fs.list("") do
  261.                 print("Уничтожаю \"" .. file .. "\"")
  262.                 fs.remove(file)
  263.             end
  264.             require("term").clear()
  265.             require("computer").shutdown()
  266.         end)
  267.  
  268.     else
  269.         reportError("receive", "неизвестная команда: " .. tostring(message))
  270.     end
  271.  
  272.     return false
  273. end
  274.  
  275. -------------------------------------------------------------------------------------
  276.  
  277. local function receive()
  278.     while true do
  279.         local ok, ev = pcall(function() return { event.pull() } end)
  280.         if not ok then
  281.             reportError("event.pull", tostring(ev))
  282.         else
  283.             if ev[1] == "modem_message"
  284.                and ev[4] == port
  285.                and ev[6] == keyWord then
  286.  
  287.                 local shouldExit = false
  288.                 local ok2, err2 = pcall(function()
  289.                     shouldExit = handleMessage(ev[7])
  290.                 end)
  291.                 if not ok2 then
  292.                     reportError("handleMessage", err2)
  293.                 end
  294.  
  295.                 if shouldExit then return end
  296.             end
  297.         end
  298.     end
  299. end
  300.  
  301. -------------------------------------------------------------------------------------
  302.  
  303. local function main()
  304.     print(" ")
  305.     print("ECS Receiver v1.5 — ожидание команд...")
  306.     if crafting then
  307.         print("Крафтинг-апгрейд: OK")
  308.     else
  309.         print("Крафтинг-апгрейд: не найден")
  310.     end
  311.     if invController then
  312.         print("Inventory Controller: OK (имена предметов доступны)")
  313.     else
  314.         print("Inventory Controller: не найден (будут показаны только номера слотов)")
  315.     end
  316.     print(" ")
  317.  
  318.     while true do
  319.         local ok, err = pcall(receive)
  320.         if not ok then
  321.             reportError("receive_loop", err)
  322.             print("Перезапуск через 2 сек...")
  323.             os.sleep(2)
  324.         else
  325.             break
  326.         end
  327.     end
  328.  
  329.     print(" ")
  330.     print("Программа завершена.")
  331. end
  332.  
  333. main()
Add Comment
Please, Sign In to add comment