cc-stuff/farm_control.lua
2025-11-20 22:45:24 -05:00

109 lines
3.1 KiB
Lua

-- Program to control a farm made with the create mod
-- establish amounts of items to ensure
local LEVELS = {}
LEVELS["minecraft:oak_log"] = {4 * 64, "minecraft:oak_sapling"}
local STORAGE = ""
local HARVESTER = ""
local PLANTER = ""
-- format: `{relay_name}:{side}`
local HARVESTER_RELAY = ""
local PLANTER_RELAY = ""
local SLEEP_TIME = 40
local SIGNAL_TIME = 2
-------------------------------- PROGRAM --------------------------------------
function pull_items (src, dest)
local src = peripheral.wrap(src)
if src.size() < 1 then return nil end
for slot, _ in pairs(src.list()) do
src.pushItems(dest, slot)
end
end
-- need to return the sources for items that need farming
-- e.g. a sapling for wood
function check_levels (levels, src)
local src = peripheral.wrap(src)
local amounts = {}
for _, item in pairs(src.list()) do
if amounts[item.name] == nil then
amounts[item.name] = item.count
else
amounts[item.name] = amounts[item.name] + item.count
end
end
local needs_farming = {}
for item, data in pairs(levels) do
if amounts[item] == nil then amounts[item] = 0 end
if amounts[item] < data[1] then
if data[2] ~= nil then
table.insert(needs_farming, data[2])
else
table.insert(needs_farming, true)
end
end
end
if needs_farming[1] == nil then
return nil
else
return needs_farming
end
end
function empty_into (src, dest)
for slot, _ in pairs(peripheral.call(src, "list")) do
peripheral.call(src, "pushItems", dest, slot)
end
end
function load_stack(item_name, src, dest)
local src = peripheral.wrap(src)
for slot, item in pairs(src.list()) do
if item.name == item_name then
return src.pushItems(dest, slot)
end
end
end
function send_machine (relay_and_side)
local RELAY_COMMAND = "setOutput"
local relay, side = relay_and_side:match"(.+):(.+)"
peripheral.call(relay, RELAY_COMMAND, side, true)
os.sleep(SIGNAL_TIME)
peripheral.call(relay, RELAY_COMMAND, side, false)
end
-- if the first argument to this program is "replant", a separate machine will
-- be sent out to replant crops between harvests
if arg[1] == "replant" then
while true do
local needs_farming = check_levels(LEVELS, STORAGE)
if needs_farming ~= nil then
for _, item in ipairs(needs_farming) do
load_stack(item, STORAGE, PLANTER)
end
send_machine(PLANTER_RELAY)
os.sleep(SLEEP_TIME)
empty_into(PLANTER, STORAGE)
end
send_machine(HARVESTER_RELAY)
os.sleep(SLEEP_TIME)
pull_items(HARVESTER, STORAGE)
end
-- otherwise, the harvester will just be sent out when a crop's levels drop too
-- low
else
while true do
local needs_farming = check_levels(LEVELS, STORAGE)
if needs_farming ~= nil then
send_machine(HARVESTER_RELAY)
end
os.sleep(SLEEP_TIME)
pull_items(HARVESTER, STORAGE)
end
end