Advertisement
Fusion1227

Central CPU

Oct 26th, 2023 (edited)
575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.02 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("TrainSignalSystem")
  14.  
  15. local actionEnum = {
  16.     GET_SIGNAL_STATE = "GET_SIGNAL_STATE",
  17.     SENSOR_CHANGE = "SENSOR_CHANGE",
  18. }
  19.  
  20.  
  21. ----| functions |----------------------------
  22.  
  23.  
  24. function onGetSignalState(id)
  25.     local trainSignalSystem = TrainSignalSystem.findFromComputerId(id)
  26.     if trainSignalSystem then
  27.         local isOn = trainSignalSystem.isOn
  28.         rednet.send(trainSignalSystem.signalId, isOn)
  29.     end
  30. end
  31.  
  32.  
  33. function onSensorChange(id)
  34.     local trainSignalSystem = TrainSignalSystem.findFromComputerId(id)
  35.     if trainSignalSystem then
  36.         if id == trainSignalSystem.onSensorId and trainSignalSystem.isOn == false then -- activate the signal
  37.             print("Activating signal...")
  38.             trainSignalSystem.isOn = true
  39.             rednet.send(trainSignalSystem.signalId, true) -- send a message to the computer that handles the signal light
  40.         elseif id == trainSignalSystem.offSensorId and trainSignalSystem.isOn == true then -- deactivate the signal
  41.             print("Deactivating signal...")
  42.             trainSignalSystem.isOn = false
  43.             rednet.send(trainSignalSystem.signalId, false) -- send a message to the computer that handles the signal light
  44.         end
  45.     end
  46. end
  47.  
  48.  
  49. function receiveSignal() -- waits for commands from central cpu
  50.     while true do
  51.         print("Waiting for a message...")
  52.         local id, message = rednet.receive()
  53.         print("Received message from computer " .. id)
  54.  
  55.         -- proceed based on the action given in the message
  56.         if message == actionEnum.SENSOR_CHANGE then
  57.             onSensorChange(id)
  58.         elseif message == actionEnum.GET_SIGNAL_STATE then
  59.             onGetSignalState(id)
  60.         end
  61.     end
  62. end
  63.  
  64.  
  65. ----| main |----------------------------
  66.  
  67.  
  68. rednet.open(MODEM_SIDE)
  69. print("Rednet opened.")
  70.  
  71.  
  72. receiveSignal()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement