Reply - Raw
This is a reply to VzUpgJYL
local pin = require("iopins")
spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, spi.DATABITS_8, 80, spi.FULLDUPLEX)

local NCS   = pin.GPIO0
local RESET = pin.GPIO4
local INT   = pin.GPIO5

local function pinToName(p)
    for k,v in pairs(pin) do
        if v == p then
            return k
        end
    end
end

local function onReceive(socket, data)
    local t = cjson.decode(data)
    if t.command == "ping" then
        socket:send(cjson.encode({data="pong"}))
    elseif t.command == "select" then
        if t.argument then
            -- SPI select chip
            gpio.mode(NCS, gpio.OUTPUT)
            gpio.write(NCS, gpio.LOW)
            socket:send(cjson.encode({data=true}))
        else
            -- SPI deselect chip
            gpio.write(NCS, gpio.HIGH)
            gpio.mode(NCS, gpio.INPUT)
            socket:send(cjson.encode({data=false}))
        end
    elseif t.command == "getconfig" then
        socket:send(cjson.encode({
            chipselect = pinToName(NCS),
            reset      = pinToName(RESET),
            interrupt  = pinToName(INT),
        }))
    elseif t.command == "write" then
        -- SPI write
        local res = {spi.send(1, encoder.fromBase64(t.argument))}
        
        socket:send(cjson.encode({
            bytes = res[1],
            data = encoder.toBase64(res[2]),
        }))
    elseif t.command == "read" then
        -- SPI read
        socket:send(cjson.encode({
            data = encoder.toBase64(spi.recv(1, t.argument or 1)),
        }))
    end
end


local function onConnect(socket)
    local ip, port = socket:getpeer()
    print("Connection from "..ip..":"..port)
    socket:on("receive", onReceive)
    socket:send(cjson.encode({connected=true}))
end


_G.server = net.createServer(net.TCP, 900) -- TCP socket, 15min timeout.
server:listen(1337, onConnect)