Advertisement
hhhzzzsss

worker.lua

Mar 23rd, 2025 (edited)
412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.38 KB | None | 0 0
  1. local component = require("component")
  2. local event = require("event")
  3. local computer = require("computer")
  4. local os = require("os")
  5. local term = require("term")
  6. local modem = component.modem
  7.  
  8. local CONTROLLER_PORT = 1
  9. local WORKER_PORT = 2
  10.  
  11. modem.open(1)
  12.  
  13. local function tickTime()
  14.     return os.time() * (1000/60/60)
  15. end
  16.  
  17. local function handle_ping(address)
  18.     modem.send(address, WORKER_PORT)
  19. end
  20.  
  21. local noteQueue = {}
  22.  
  23. local function handle_note(pitch, duration, time)
  24.     table.insert(noteQueue, {pitch = pitch, duration = duration, time = time})
  25. end
  26.  
  27. local function process_queue()
  28.     if #noteQueue == 0 then return end
  29.    
  30.     local currentTime = tickTime()
  31.     while #noteQueue > 0 and noteQueue[1].time <= currentTime do
  32.         local note = table.remove(noteQueue, 1)
  33.         computer.beep(note.pitch, note.duration)
  34.     end
  35. end
  36.  
  37. term.clear()
  38. print("Running worker...")
  39.  
  40. while true do
  41.     local id, _, remoteAddress, port, _, protocol, data1, data2, data3 = event.pullMultiple("modem_message", "interrupted")
  42.     if id == "interrupted" then
  43.         print("Interrupted. Exiting...")
  44.         break
  45.     end
  46.     if port == CONTROLLER_PORT then
  47.         if protocol == "ping" then
  48.             handle_ping(remoteAddress)
  49.         elseif protocol == "note" then
  50.             handle_note(data1, data2, data3)
  51.         end
  52.     end
  53.    
  54.     process_queue()
  55. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement