Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- wireless_turtle.lua
- local modem = peripheral.find("modem")
- if not modem then
- print("No modem found")
- return
- end
- local basePort = 2469
- modem.open(basePort)
- local currentTask = nil
- local shouldStop = false
- local turtleId = tostring(math.random(1000, 9999)) -- Generate a random 4-digit ID
- local function advertise()
- while true do
- modem.transmit(basePort, basePort, {command = "pong", id = turtleId})
- sleep(2) -- Advertise every 2 seconds
- end
- end
- local function checkStop()
- if shouldStop then
- error("Stopped")
- end
- end
- local function smartmine(length, width)
- currentTask = "Mining"
- shouldStop = false
- for w = 1, width do
- for l = 1, length do
- checkStop()
- turtle.dig()
- turtle.forward()
- turtle.digUp()
- end
- if w < width then
- turtle.turnLeft()
- turtle.dig()
- turtle.forward()
- turtle.turnLeft()
- for l = 1, length do
- checkStop()
- turtle.dig()
- turtle.forward()
- turtle.digUp()
- end
- turtle.turnRight()
- turtle.turnRight()
- end
- end
- currentTask = nil
- modem.transmit(basePort, basePort, {command = "miningComplete", id = turtleId})
- end
- local function handleCommands()
- while true do
- local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
- if channel == basePort and type(message) == "table" then
- if message.id == turtleId or message == "ping" then
- if message.command == "smartmine" then
- parallel.waitForAny(
- function() smartmine(message.length, message.width) end,
- handleCommands
- )
- elseif message.command == "stop" then
- shouldStop = true
- currentTask = "Stopped"
- modem.transmit(basePort, basePort, {command = "stopped", id = turtleId})
- elseif message.command == "stats" then
- modem.transmit(basePort, basePort, {command = "stats", id = turtleId, fuel = turtle.getFuelLevel(), task = currentTask or "Idle"})
- elseif message == "ping" then
- modem.transmit(basePort, basePort, {command = "pong", id = turtleId})
- end
- end
- end
- end
- end
- print("Turtle ID: " .. turtleId)
- parallel.waitForAll(advertise, handleCommands)
Advertisement
Add Comment
Please, Sign In to add comment