Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions server/bluetooth/registry.lua
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,10 @@ end

---Runs an owning script's callback without letting it take the caller down with it. A third-party
---handler that errors must never stall the reconnect tick or abort a pairing.
---@param fn function|nil
---@param fn function|table|nil
---@param ... any
local function safely(fn, ...)
if type(fn) ~= 'function' then return end
if not bt.isCallable(fn) then return end
local ok, err = pcall(fn, ...)
if not ok then
print(('^1[sd-phone:bluetooth]^0 device callback errored: %s'):format(tostring(err)))
Expand Down
15 changes: 13 additions & 2 deletions shared/bluetooth.lua
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ function bluetooth.merge(device, patch)
return def
end

---Whether a value can be called. A function handed over through an export arrives as a function
---reference: a table with a __call metamethod, not a Lua function.
---@param value any
---@return boolean
function bluetooth.isCallable(value)
if type(value) == 'function' then return true end
if type(value) ~= 'table' then return false end
local meta = getmetatable(value)
return type(meta) == 'table' and meta.__call ~= nil
end

---Validates a registration, returning the fields worth keeping. Rejects rather than repairs, so a
---script learns its device is wrong instead of finding it silently unreachable.
---@param def table registration passed to registerBluetoothDevice
Expand Down Expand Up @@ -106,8 +117,8 @@ function bluetooth.validate(def)
entity = entity,
range = range,
maxConnections = max,
onConnect = type(def.onConnect) == 'function' and def.onConnect or nil,
onDisconnect = type(def.onDisconnect) == 'function' and def.onDisconnect or nil,
onConnect = bluetooth.isCallable(def.onConnect) and def.onConnect or nil,
onDisconnect = bluetooth.isCallable(def.onDisconnect) and def.onDisconnect or nil,
}
end

Expand Down
Loading