Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local modem = peripheral.find("modem")
- local state = "idle"
- local currentFloor = 1
- local lastUpDownTime = nil
- local computerID = os.getComputerID()
- -- Configuration
- local configFileName = "elevator_server_config.txt"
- local config = {channel = "69", computerID = "0"}
- -- Save Config to file
- local function saveConfig(config)
- local configData = textutils.serializeJSON(config)
- local file = fs.open(configFileName, "w")
- file.write(configData)
- file.close()
- end
- -- Load Config from file
- local function loadConfig()
- if fs.exists(configFileName) then
- local file = fs.open(configFileName, "r")
- local configData = file.readAll()
- file.close()
- local loadedConfig = textutils.unserializeJSON(configData)
- config = loadedConfig
- end
- end
- local function controlElevator(direction)
- if direction == "up" or direction == "down" then
- lastUpDownTime = os.epoch('utc')
- end
- if direction == "up" then
- redstone.setOutput("left", true)
- redstone.setOutput("right", false)
- elseif direction == "down" then
- redstone.setOutput("left", false)
- redstone.setOutput("right", false)
- elseif direction == "stop" then
- redstone.setOutput("left", false)
- redstone.setOutput("right", true)
- else
- print("Debug: Invalid direction")
- end
- end
- local function stateMachine()
- print("Current state: " .. state)
- if state == "idle" then
- controlElevator("stop")
- elseif state == "up" then
- controlElevator("up")
- elseif state == "down" then
- controlElevator("down")
- else
- print("Debug: Invalid state")
- end
- end
- local function handleModemMessages(config)
- local event, modemSide, senderChannel, replyChannel, message, senderDistance = os.pullEvent()
- if event == "modem_message" then
- if senderChannel == tonumber(config.channel) then
- if string.sub(message, 1, 5) == "idle:" then
- if lastUpDownTime == nil or (os.epoch('utc') - lastUpDownTime) >= 1000 then
- state = "idle"
- local newFloor = tonumber(string.sub(message, 6))
- print("Elevator floor: " .. newFloor)
- currentFloor = newFloor
- end
- else
- state = message
- end
- end
- end
- end
- -- Main Loop
- local function mainLoop(config)
- modem.open(tonumber(config.channel))
- while true do
- handleModemMessages(config)
- stateMachine()
- end
- end
- -- Initialization
- local function initializeClient()
- loadConfig()
- if not config.channel or config.channel == "" then
- print("Please enter the channel to use:")
- config.channel = tonumber(read())
- end
- if not config.computerID then
- config.computerID = computerID
- end
- saveConfig(config)
- mainLoop(config)
- end
- -- Entry Point
- initializeClient()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement