Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- this is the startup script for the central cpu at spawn
- ----| config |----------------------------
- local MODEM_SIDE = "top"
- ----| setup |----------------------------
- os.loadAPI("TrainSignalNetwork")
- 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,
- }
- ----| functions |----------------------------
- function onGetSignalState(id)
- local trainSignalNetwork, thisSubNetwork, otherSubNetwork = TrainSignalNetwork.findFromComputerId(id)
- if trainSignalNetwork then
- local isOn = thisSubNetwork.signalState
- rednet.send(thisSubNetwork.id, isOn, protocolEnum.GET_SIGNAL_STATE)
- end
- end
- function onSensorChange(id, state)
- local trainSignalNetwork, thisSubNetwork, otherSubNetwork = TrainSignalNetwork.findFromComputerId(id)
- if trainSignalNetwork then
- -- proceed based on state
- if state == sensorStateEnum.rightOn then -- a train in the right lane is entering the single lane; activate the signal on the far side relative to here
- otherSubNetwork.signalState = true
- print(otherSubNetwork.id .. "'s signal set to true")
- elseif state == sensorStateEnum.leftOn then -- a train is moving out of the single lane into the left lane; deactivate the signal on this side
- thisSubNetwork.signalState = false
- print(thisSubNetwork.id .. "'s signal set to false")
- end
- end
- end
- function receiveSignal() -- waits for commands from central cpu
- while true do
- local id, message, protocol = rednet.receive()
- -- print("Received message from computer " .. id .. "\n\t> Protocol: " .. (protocol or "None"))
- -- proceed based on the protocol given in the message
- if protocol == protocolEnum.SENSOR_CHANGE then
- onSensorChange(id, message)
- elseif protocol == protocolEnum.GET_SIGNAL_STATE then
- onGetSignalState(id)
- end
- end
- end
- ----| main |----------------------------
- rednet.open(MODEM_SIDE)
- print("Rednet opened.")
- receiveSignal()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement