Advertisement
melzneni

Turti lib dimension

Sep 24th, 2023 (edited)
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. local api = {}
  2. local storage
  3. local save
  4. local PROTOCOL = "TURTI_DIMENSION_PROTOCOL"
  5. local RESPONSE_EVENT = PROTOCOL .. "_RESPONSE_EVENT"
  6. local RESPONSE_TIMEOUT = 3
  7.  
  8. local function openRednet()
  9. local side
  10. peripheral.find("modem", function(name, modem)
  11. if modem.isWireless() then
  12. side = name
  13. end
  14. end)
  15. if not rednet.isOpen(side) then
  16. rednet.open(side)
  17. end
  18. end
  19.  
  20. local function listenerThread()
  21. openRednet()
  22. while true do
  23. local _, _, _, replyChannel, message, distance = os.pullEvent("modem_message")
  24. if type(message) == "table" and message["sProtocol"] == PROTOCOL and message["message"] then
  25. local msg = getTableFromSaveText(message["message"])
  26. if msg.type == "dimensionRequest" then
  27. if storage.dimension and distance then
  28. rednet.send(replyChannel, getTableSaveText({
  29. type = "dimensionResponse",
  30. dimension = storage.dimension,
  31. callId = msg.callId
  32. }), PROTOCOL)
  33. end
  34. elseif msg.type == "dimensionResponse" then
  35. storage.responses[msg.callId] = msg.dimension
  36. save()
  37. os.queueEvent(RESPONSE_EVENT)
  38. end
  39. end
  40. end
  41. end
  42.  
  43. function api.hostDimension(dimension)
  44. storage.dimension = dimension
  45. save()
  46. end
  47.  
  48. local function tryGetDimension()
  49. local callId = storage.currentCallId
  50. storage.currentCallId = storage.currentCallId + 1
  51. save()
  52. rednet.broadcast(getTableSaveText({
  53. type = "dimensionRequest",
  54. callId = callId
  55. }), PROTOCOL)
  56. local timer = os.startTimer(RESPONSE_TIMEOUT)
  57. while true do
  58. local event, arg = os.pullEvent()
  59. if event == RESPONSE_EVENT then
  60. local dimension = storage.responses[callId]
  61. storage.responses[callId] = nil
  62. save()
  63. return dimension
  64. elseif event == "timer" then
  65. if arg == timer then
  66. return nil
  67. end
  68. end
  69. end
  70. end
  71.  
  72. function api.getDimension()
  73. while true do
  74. local dimension = tryGetDimension()
  75. if dimension then
  76. return dimension
  77. end
  78. end
  79. end
  80.  
  81. return {
  82. name = "dimension",
  83. onSetup = function()
  84. ThreadManager.startThread(
  85. listenerThread, "dimension listener"
  86. )
  87. end,
  88. onInitStorage = function(_storage, _save)
  89. storage = _storage
  90. save = _save
  91. if not storage.responses then
  92. storage.responses = {}
  93. storage.currentCallId = 0
  94. end
  95. end,
  96. api = api
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement