Advertisement
Fusion1227

Central Computer

Oct 27th, 2023 (edited)
648
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.22 KB | None | 0 0
  1. -- this is the startup script for the central cpu at spawn
  2.  
  3.  
  4. ----| config |----------------------------
  5.  
  6.  
  7. local MODEM_SIDE = "top"
  8.  
  9.  
  10. ----| setup |----------------------------
  11.  
  12.  
  13. os.loadAPI("TrainSignalNetwork")
  14.  
  15. local protocolEnum = {
  16.     GET_SIGNAL_STATE = "GET_SIGNAL_STATE",
  17.     SENSOR_CHANGE = "SENSOR_CHANGE",
  18. }
  19.  
  20. local sensorStateEnum = { -- compatible with bitwise operations
  21.     off = 0,
  22.     leftOn = 1,
  23.     rightOn = 2,
  24.     bothOn = 3,
  25. }
  26.  
  27.  
  28. ----| functions |----------------------------
  29.  
  30.  
  31. function onGetSignalState(id)
  32.     local trainSignalNetwork, thisSubNetwork, otherSubNetwork = TrainSignalNetwork.findFromComputerId(id)
  33.     if trainSignalNetwork then
  34.         local isOn = thisSubNetwork.signalState
  35.         rednet.send(thisSubNetwork.id, isOn, protocolEnum.GET_SIGNAL_STATE)
  36.     end
  37. end
  38.  
  39.  
  40. function onSensorChange(id, state)
  41.     local trainSignalNetwork, thisSubNetwork, otherSubNetwork = TrainSignalNetwork.findFromComputerId(id)
  42.     if trainSignalNetwork then
  43.         -- proceed based on state
  44.         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
  45.             otherSubNetwork.signalState = true
  46.             print(otherSubNetwork.id .. "'s signal set to true")
  47.         elseif state == sensorStateEnum.leftOn then -- a train is moving out of the single lane into the left lane; deactivate the signal on this side
  48.             thisSubNetwork.signalState = false
  49.             print(thisSubNetwork.id .. "'s signal set to false")
  50.         end
  51.     end
  52. end
  53.  
  54.  
  55. function receiveSignal() -- waits for commands from central cpu
  56.     while true do
  57.         local id, message, protocol = rednet.receive()
  58.         -- print("Received message from computer " .. id .. "\n\t> Protocol: " .. (protocol or "None"))
  59.  
  60.         -- proceed based on the protocol given in the message
  61.         if protocol == protocolEnum.SENSOR_CHANGE then
  62.             onSensorChange(id, message)
  63.         elseif protocol == protocolEnum.GET_SIGNAL_STATE then
  64.             onGetSignalState(id)
  65.         end
  66.     end
  67. end
  68.  
  69.  
  70. ----| main |----------------------------
  71.  
  72.  
  73. rednet.open(MODEM_SIDE)
  74. print("Rednet opened.")
  75.  
  76.  
  77. receiveSignal()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement