Advertisement
WhiteFire_Sondergaar

turtle slave

Apr 20th, 2013
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.23 KB | None | 0 0
  1. -- Turtle Slaves
  2. -- By Fenthis
  3.  
  4. slave_file = "/slave_id.txt"
  5. slave_channel = 6969
  6. status_channel = 2069
  7.  
  8. -- Set a reasonable name for a slave.
  9. l = "Slave_" .. os.getComputerID()
  10. print("Setting label to: " .. l)
  11. os.setComputerLabel(l)
  12.  
  13. -- Assign to group
  14. args = { ... }
  15. if #args > 0 then
  16.     group = args[1]
  17.     f = fs.open(slave_file, "w")
  18.     f.writeLine(group)
  19.     f.close()
  20. else
  21.     if fs.exists(slave_file) then
  22.         f = fs.open(slave_file, "r")
  23.         group = f.readLine()
  24.         f.close()
  25.     else
  26.         print("I don't know what slave group I am in.")
  27.         exit()
  28.     end
  29. end
  30. print("My group ID is: \""..group.."\"")
  31.  
  32. -- Connect to the model
  33. local modem = peripheral.wrap("right")
  34. modem.open(slave_channel)
  35.  
  36. -- Send a reply
  37. local function send_status(message)
  38.     x, y, z = gps.locate()
  39.     if x then
  40.         message.location = vector.new(x,y,z)
  41.     end
  42.     message.sender = os.getComputerLabel()
  43.     message.group = group
  44.     modem.transmit(status_channel, slave_channel,
  45.         textutils.serialize(message))
  46. end
  47.  
  48. -- The message handling
  49. local function run_command(message)
  50.     cmd = textutils.unserialize(message)
  51.     if not cmd then return end
  52.     if not cmd.group == group then return end
  53.  
  54.     if cmd.message_type == "slave_command" then
  55.         print("Recieved command: \"" .. cmd.command .. "\" from " .. cmd.sender)
  56.         send_status({["message_type"] = "running command",
  57.             ["command"] = cmd.command})
  58.         a = cmd.args or {}
  59.         shell.run(cmd.command, unpack(a))
  60.         send_status({["message_type"] = "finished command",
  61.             ["command"] = cmd.command})
  62.     end
  63. end
  64.  
  65. -- Announce us
  66. send_status({["message_type"] = "online"})
  67.  
  68. -- Main Loop
  69. print("Waiting for commands, press Q to quit.")
  70. while true do
  71.     local event, modemSide, senderChannel,
  72.         replyChannel, message, senderDistance = os.pullEvent()
  73.  
  74.     if event == "char" then
  75.         if (modemSide == "Q" or modemSide == "q") then
  76.             break
  77.         end
  78.     elseif event == "modem_message" then
  79.         -- print("Message: " .. message)
  80.         run_command(message)
  81.     end
  82. end
  83.  
  84. -- Exit!
  85. modem.close(slave_channel)
  86. send_status({["message_type"] = "offline"})
  87. print("Done!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement