Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- pastebin get PFC9cjHM network_util
- lua
- net = require("network_util.lua")
- net.example()
- ]]
- peripheral.find("modem", rednet.open)
- protocol = "strippy"
- function find_host(my_job, position)
- print("Looking for "..protocol.." Hosts!")
- local computers = {rednet.lookup(protocol)}
- print("\tFound "..tostring(#computers).." potential hosts!")
- local my_data = {
- job=my_job,
- pos=position
- }
- for _, computer in pairs(computers) do
- print("Pinging "..computer)
- rednet.send(computer, textutils.serialize(my_data), protocol)
- local id, response = rednet.receive(protocol, 10)
- if id == computer and response == "true" then
- print("Found Host!")
- return computer
- else
- print("Denied: ")
- print(response)
- end
- end
- print("Could not find Host!")
- return nil
- end
- function start_host(my_job, position)
- print("Hosting "..protocol.."!")
- rednet.host(protocol, tostring(os.computerID()))
- count = 1
- partners = {}
- partners[my_job] = os.computerID()
- repeat
- local id, message = rednet.receive(protocol)
- local partner = textutils.unserialize(message)
- print("Just received request from:", id, "\nWho is a:", partner.job, "\nWho is at:", partner.pos)
- local dist = partner.pos.x - position.x + partner.pos.y - position.y + partner.pos.z - position.z
- print(dist)
- if dist < 10 then
- print("Found Partner!")
- partners[partner.job] = id
- rednet.send(id, "true", protocol)
- count = count + 1
- else
- rednet.send(id, "false", protocol)
- end
- until count == 3
- rednet.unhost(protocol)
- print("Found All Partners!")
- for job, partner in pairs(partners) do
- rednet.send(partner, textutils.serialize(partners), protocol)
- end
- return partners
- end
- function wait_for_partners(partner_id)
- print("Waiting for Host!")
- while true do
- local id, message = rednet.receive(protocol)
- if id == partner_id then
- return textutils.unserialize(message) -- This should return the list of partners
- end
- end
- end
- function example(job)
- job = job or "chunker"
- local position = vector.new(gps.locate())
- local host = find_host(job, position)
- if host then
- return wait_for_partners(host)
- end
- return start_host(job, position)
- end
- return {
- find_host = find_host,
- start_host = start_host,
- wait_for_partners = wait_for_partners,
- example = example
- }
Advertisement
Add Comment
Please, Sign In to add comment