CCCPaste

Bouton et display data

local state = false
local modemSide = "back"
local modem = peripheral.wrap(modemSide)
local width, height = term.getSize()
local data = {"info","off","Temp",0,"Coolant",0,"Damage",0,"Waste",0}

local yh,yb = math.floor(height/2+3), height-1 
local xg,xd = 2, width-1

local buttonY = math.floor(3 * height / 4)

remoteID = 14

rednet.open(modemSide)

local function sendData(Data)
    rednet.send(remoteID, Data)
end

local function drawButton(state, text)
    --term.clear()
    term.setCursorPos(xg,yh)

    local bgColor = colors.red
    local fgColor = colors.white
    if state then
        bgColor = colors.green
        fgColor = colors.black
    end

    for y = yh, yb do
        term.setCursorPos(xg,y)
        term.setBackgroundColor(bgColor)
        term.write(string.rep(" ", xd - xg + 1))
    end

    local textLen = #text
    local x = math.floor((width - textLen) / 2) + 1
    local y = math.floor((yh + yb) / 2)

    term.setCursorPos(x, y)
    term.setTextColor(fgColor)
    term.write(text)
    -- Reset colors
    term.setBackgroundColor(colors.black)
    term.setTextColor(colors.white)
end

local function chState()
    while true do
        if state then
            drawButton(true, "ON")
        else
            drawButton(false, "OFF")
        end
        local event, button, x, y = os.pullEvent("mouse_click")
        if y >= yh and y <= yb and x >= xg and x <= xd then
            state = not state
            sendData(state)
        end
    end
end

local function dataDisplay()
    while true do
        -- Affichage simple des données sous forme clé-valeur
        term.setCursorPos(1,1)
        term.setBackgroundColor(colors.black)
        term.setTextColor(colors.white)
        term.clearLine()
        term.write("Données reçues :")
        local line = 2
        for i=1, #data, 2 do
            term.setCursorPos(1, line)
            term.clearLine()
            term.write(string.format("%s : %s", tostring(data[i]), tostring(data[i+1])))
            line = line + 1
        end
        sleep(1)  -- mettre à jour toutes les 1s
    end
end

local function dataUpdate()
    while true do
        local senderID, message = rednet.receive()
        if senderID == remoteID and type(message) == "table" then
            data = message
        end
    end
end

local function main()
    parallel.waitForAny(dataUpdate, chState, dataDisplay)
end

main()