Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- A complete train signal system has two on sensors (one per side), two off sensors (one per side),
- and two signal lights. Given a signal light A and a signal light B, this script handles
- the on sensor for B and the off sensor for A. Since these two sensors are close to A,
- it is efficient to link them and A to a single computer, and to link the rest of the components
- on the other side to another computer.
- Each train signal network should have two computers, and each computer should use this script
- and name it "startup".
- ]]
- ----| config |----------------------------
- local MODEM_SIDE = "top"
- local LEFT_SENSOR_SIDE = "left"
- local RIGHT_SENSOR_SIDE = "right"
- local SIGNAL_SIDE = "back"
- local CENTRAL_CPU_ID = 4 -- the id of the computer at spawn
- ----| setup |----------------------------
- local protocolEnum = {
- GET_SIGNAL_STATE = "GET_SIGNAL_STATE",
- SENSOR_CHANGE = "SENSOR_CHANGE",
- }
- local sensorStateEnum = { -- compatible with bitwise operations
- off = 0,
- leftOn = 1,
- rightOn = 2,
- bothOn = 3,
- }
- local lastSensorStates = sensorStateEnum.off
- ----| functions |----------------------------
- function getSensorStates()
- local leftValue = redstone.getInput(LEFT_SENSOR_SIDE) and sensorStateEnum.leftOn or sensorStateEnum.off -- 1 if on, 0 if off
- local rightValue = redstone.getInput(RIGHT_SENSOR_SIDE) and sensorStateEnum.rightOn or sensorStateEnum.off -- 2 if on, 0 if off
- return leftValue + rightValue -- corresponds to one of the sensorStateEnum values
- end
- function sendSensorStates()
- local states = getSensorStates()
- if states ~= lastSensorStates and states ~= sensorStateEnum.off and states ~= sensorStateEnum.bothOn then -- if the state changed and just one of the sensors is on
- rednet.send(CENTRAL_CPU_ID, states, protocolEnum.SENSOR_CHANGE)
- end
- lastSensorStates = states -- record the state change
- end
- function setSignalState()
- rednet.send(CENTRAL_CPU_ID, nil, protocolEnum.GET_SIGNAL_STATE)
- local id, signalState = rednet.receive(protocolEnum.GET_SIGNAL_STATE)
- print("Received message from computer " .. id .. "\n\t> Message: " .. tostring(signalState))
- if id ~= CENTRAL_CPU_ID then return end
- if signalState == true then -- activate signal
- print("Activating signal...")
- redstone.setOutput(SIGNAL_SIDE, true)
- elseif signalState == false then -- deactivate signal
- redstone.setOutput(SIGNAL_SIDE, false)
- print("Deactivating signal...")
- end
- end
- ----| main |----------------------------
- rednet.open(MODEM_SIDE)
- print("Rednet opened.")
- while true do
- sendSensorStates()
- setSignalState()
- sleep(1)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement