DorianH935

Untitled

Jun 24th, 2024 (edited)
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. -- host.lua
  2.  
  3. -- Function to find and open the modem
  4. local function openModem()
  5. local sides = {"left", "right", "top", "bottom", "front", "back"}
  6. for _, side in ipairs(sides) do
  7. if peripheral.isPresent(side) and peripheral.getType(side) == "modem" then
  8. rednet.open(side)
  9. return true
  10. end
  11. end
  12. return false
  13. end
  14.  
  15. -- Open the modem
  16. if not openModem() then
  17. print("No modem found!")
  18. return
  19. end
  20.  
  21. local pairedClients = {}
  22.  
  23. -- Function to send command to a specific client
  24. local function sendCommand(pairingKey, command)
  25. local clientId = pairedClients[pairingKey]
  26. if clientId then
  27. rednet.send(clientId, command, "command")
  28. local senderId, response, protocol = rednet.receive("response")
  29. if senderId == clientId then
  30. print("Response from client " .. clientId .. ": " .. response)
  31. else
  32. print("Unexpected response from client " .. senderId)
  33. end
  34. else
  35. print("No client paired with this key.")
  36. end
  37. end
  38.  
  39. -- Function to pair with a new client
  40. local function pairClient(pairingKey)
  41. print("Waiting for client with key " .. pairingKey)
  42. local senderId, receivedKey, protocol = rednet.receive("pairing", 30)
  43. if protocol == "pairing" and receivedKey == pairingKey then
  44. pairedClients[pairingKey] = senderId
  45. print("Paired with client " .. senderId .. " using key " .. pairingKey)
  46. else
  47. print("Pairing failed or timed out.")
  48. end
  49. end
  50.  
  51. -- Main loop
  52. while true do
  53. print("Enter command (pair, send): ")
  54. local action = read()
  55. if action == "pair" then
  56. print("Enter pairing key (4-digit hex): ")
  57. local pairingKey = read()
  58. pairClient(pairingKey)
  59. elseif action == "send" then
  60. print("Enter pairing key: ")
  61. local pairingKey = read()
  62. print("Enter command: ")
  63. local command = read()
  64. sendCommand(pairingKey, command)
  65. else
  66. print("Invalid command.")
  67. end
  68. end
  69.  
Advertisement
Add Comment
Please, Sign In to add comment