CCCPaste

Turbine control 2

-- Peripheral setup
local modem = peripheral.find("modem") or error("No modem found", 0)
local monitor = peripheral.wrap("front") or error("No monitor on front", 0)

-- Monitor setup
monitor.setTextScale(0.5)
monitor.setBackgroundColor(colors.cyan)
monitor.clear()

local function drawLabel(y, text)
    monitor.setCursorPos(1, y)
    monitor.clearLine()
    monitor.write(text)
end

local function drawUI()
    drawLabel(4, "Fuel Feed")
    drawLabel(5, "-=-=-=-=-=-=-=-")
    drawLabel(8, "Clutch")
    drawLabel(9, "-=-=-=-=-=-=-=-")
    drawLabel(12, "Output")
    drawLabel(13, "-=-=-=-=-=-=-=-")
    monitor.setCursorPos(4, 1)
    monitor.write("Turbine #1")
end

drawUI()

term.clear()
term.setCursorPos(1, 1)
print("Running...")

-- Core Functions
local function transmitAndDisplay(channelOut, channelIn, mode, yPos, bgColor, side, pulse)
    if side then rs.setOutput(side, true) end
    modem.transmit(channelOut, channelIn, mode)
    monitor.setCursorPos(1, yPos)
    monitor.clearLine()
    monitor.blit(mode, ("0"):rep(#mode), bgColor)
    if pulse then sleep(1); if side then rs.setOutput(side, false) end end
end

local function fuelFeed(side, mode, bgColor)
    transmitAndDisplay(3, 4, mode, 6, bgColor, side, true)
end

local function shift(side, mode, bgColor)
    rs.setOutput("left", false)
    transmitAndDisplay(2, 3, mode, 10, bgColor, side, true)
end

local function modemCall(channel, callback)
    modem.open(channel)
    local _, _, _, _, message = os.pullEvent("modem_message")
    modem.close(channel)
    if callback then callback(message) end
    return message
end

local function battCall()
    return tonumber(modemCall(4, function(msg)
        term.setCursorPos(1, 2)
        term.clearLine()
        print(msg)
    end)) or 0
end

local function outputCall()
    modemCall(5, function(msg)
        monitor.setCursorPos(1, 14)
        monitor.clearLine()
        monitor.write(msg)
    end)
end

-- Main control loop
local inject, delay = 0, 0

while not rs.getInput("front") do
    local batt = battCall()
    local speed = rs.getAnalogInput("right")

    outputCall()

    if inject == 1 then delay = delay + 1 end
    if delay >= 280 then inject, delay = 0, 0 end

    if speed == 0 then
        shift("top", "Offline", "eeeeeee")
        if batt <= 30 and inject == 0 then
            fuelFeed("bottom", "Engaged", "ddddddd")
            inject = 1
        elseif batt >= 35 then
            fuelFeed("top", "Offline", "eeeeeee")
        end
    elseif speed <= 8 then
        shift("top", "Low RPM", "1111111")
        if batt >= 35 then
            fuelFeed("top", "Offline", "eeeeeee")
        end
    else
        shift("left", "Engaged", "ddddddd")
        if batt >= 35 then
            fuelFeed("top", "Offline", "eeeeeee")
        end
    end
end