Advertisement
gravitowl

Router

Mar 8th, 2021 (edited)
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. -- GLOBALS
  2. parent = -1
  3. myID = os.getComputerID()
  4.  
  5. -- Functions & Stuff
  6.  
  7. function processRequest(request, senderId)
  8. -- Standard responses for identifying and adding to networks.
  9. if request == "$HELLO" then
  10. print("Responding to network discovery.")
  11. rednet.send(senderId, "$HELLO")
  12. return
  13. elseif request == "$ADDME" then
  14. response = "$MASTER$ADDROUTER-"..senderId.."-"..myID
  15. print("Sending request to master, awaiting response.")
  16. rednet.send(parent, response)
  17. return
  18. end
  19.  
  20. -- If we find either a server or master request, we'll just immediatly send it to the next router in the chain.
  21. if string.find(request, "$SERVER") or string.find(request, "$MASTER") then
  22. print("Forwarding message to parent.")
  23. rednet.send(parent, request)
  24. return
  25. end
  26.  
  27. -- If we find that the request is targeted at an end-user, we'll find out which router to send it next to and send it.
  28. print("Finding - in "..request)
  29. local s, e, cap = request:find("(.-)".."-", 1)
  30. print("Found - at index "..s)
  31. if not cap or not tonumber(cap) then
  32. print("Invalid message.")
  33. return
  34. end
  35. print("Sending message to next router.")
  36. request = string.sub(request, e + 1)
  37. rednet.send(tonumber(cap), request)
  38. end
  39.  
  40. -- Main Logic
  41.  
  42. rednet.open("top")
  43.  
  44. local id, message
  45.  
  46. while true do
  47. print("Trying to connect...")
  48. rednet.broadcast("$HELLO")
  49. id, message = rednet.receive(5)
  50. if message then break end
  51. end
  52.  
  53. print("Received message: "..message.." from "..id)
  54. rednet.send(id, "$ADDME")
  55.  
  56. while true do
  57. id, message = rednet.receive(5)
  58. if not message then
  59. print("No network routers nearby, couldn't connect to network.")
  60. return
  61. end
  62.  
  63. if message == "$ACK" then break end
  64. end
  65.  
  66. print("Added to network, ID: "..myID)
  67. parent = id
  68. print("All messages are being sent to: "..parent)
  69. print("Check master server for confirmation.")
  70.  
  71. while true do
  72. print("Listening for messages...")
  73. id, message = rednet.receive()
  74. print("Received message: "..message.." from "..id)
  75. processRequest(message, id)
  76. end
  77.  
  78. rednet.close()
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement