Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Rednet Communication Test Program for Computer A and B
- -- This program runs in two modes based on the configuration in an INI file.
- -- Save INI Configuration File
- local function saveConfig(config)
- local file = fs.open("config.ini", "w")
- for key, value in pairs(config) do
- file.writeLine(key .. "=" .. value)
- end
- file.close()
- end
- -- Load INI Configuration File
- local function loadConfig()
- if not fs.exists("config.ini") then
- -- Create a default config.ini file with mode A
- local defaultConfig = { mode = "A" }
- saveConfig(defaultConfig)
- end
- local file = fs.open("config.ini", "r")
- local config = {}
- for line in file.readLine do
- local key, value = string.match(line, "(%w+)%s*=%s*(%w+)")
- if key and value then
- config[key] = value
- end
- end
- file.close()
- return config
- end
- -- Message Queue to hold incoming messages
- local messageQueue = {}
- -- Function to receive messages and append them to the queue
- local function messageListener()
- while true do
- local senderId, message = rednet.receive()
- table.insert(messageQueue, {senderId = senderId, message = message})
- end
- end
- -- Function to control the lamp based on received messages
- local function lampController()
- while true do
- if #messageQueue > 0 then
- local receivedMessage = table.remove(messageQueue, 1)
- local message = receivedMessage.message
- if message == "on" then
- redstone.setOutput("right", true)
- print("Lamp turned ON")
- elseif message == "off" then
- redstone.setOutput("right", false)
- print("Lamp turned OFF")
- end
- end
- sleep(0.1) -- Small delay to avoid busy waiting
- end
- end
- -- Main Program
- local config = loadConfig()
- if config["mode"] == "A" then
- -- Computer A: Operating the Switch
- rednet.open("back")
- print("Running as Computer A - Switch Controller")
- local previousState = nil
- while true do
- local switchState = redstone.getInput("left")
- if switchState ~= previousState then
- local message = switchState and "on" or "off"
- rednet.broadcast(message)
- print("Broadcasting switch state: " .. message)
- previousState = switchState
- end
- sleep(0.1) -- Small delay to reduce CPU usage
- end
- elseif config["mode"] == "B" then
- -- Computer B: Operating the Lamp
- rednet.open("back")
- print("Running as Computer B - Lamp Controller")
- -- Run both the message listener and the lamp controller in parallel
- parallel.waitForAll(messageListener, lampController)
- else
- error("Invalid mode in configuration file! Must be 'A' or 'B'")
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement