Advertisement
DevilTvLP

tracking

Apr 12th, 2025 (edited)
360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.92 KB | None | 0 0
  1. -- work in progress program to track turtle status remotely
  2.  
  3. local function initNetwork()
  4.     local bOpen, sFreeSide = false, nil
  5.     for n,sSide in pairs(rs.getSides()) do 
  6.         if peripheral.getType(sSide) == "modem" then
  7.             sFreeSide = sSide
  8.             if rednet.isOpen(sSide) then
  9.                 bOpen = true
  10.                 break
  11.             end
  12.         end
  13.     end
  14.    
  15.     if not bOpen then
  16.         if sFreeSide then
  17.             rednet.open(sFreeSide)
  18.             return true
  19.         else
  20.             return false
  21.         end
  22.     end
  23.     return true
  24. end
  25.  
  26. -- API export
  27. function setStatus(task, currentIteration, totalIterations, receiverId)
  28.     local isOnline = initNetwork()
  29.     if not isOnline then return end
  30.    
  31.     info = {
  32.         senderLabel = os.getComputerLabel(),
  33.         task = task or "unknown",
  34.         currentIteration = currentIteration,
  35.         totalIterations = totalIterations
  36.     }
  37.    
  38.     message = textutils.serialize(info)
  39.    
  40.     if receiverId == nil then
  41.         rednet.broadcast(message)
  42.     else
  43.         rednet.send(receiverId, message)
  44.     end
  45. end
  46.  
  47. function startHost()
  48.     local isOnline = initNetwork()
  49.     if not isOnline then
  50.         print("Can't establish network connection")
  51.         return
  52.     end
  53.    
  54.     while true do
  55.         senderId, message, _ = rednet.receive()
  56.         info = textutils.unserialize(message)
  57.        
  58.         if info.senderLabel ~= nil then
  59.             print("Statusupdate from " .. info.senderLabel .. " (" .. senderId .. ")")
  60.             print("\tTask: " .. info.task)
  61.            
  62.             if info.currentIteration ~= nil and info.totalIterations ~= nil then
  63.                 local progressPercent = math.floor((info.currentIteration / info.totalIterations) * 100)
  64.                 print("\tProgress: " .. progressPercent .. "% (" .. info.currentIteration .. " / " .. info.totalIterations .. ")")
  65.             end
  66.         end
  67.     end
  68. end
  69.  
  70. function startClient()
  71.     print("TODO: implement client")
  72. end
  73.  
  74. -- parse program args for non API calls
  75. local args={ ... }
  76. if #args >= 1 then
  77.     if args[1] == "host" then
  78.         startHost()
  79.     elseif args[1] == "client" then
  80.         startClient()
  81.     else
  82.         print("Usage: tracking <host|client>")
  83.     end
  84. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement