<--- Cannot embed stylesheet: [Errno 2] No such file or directory: '../../../aros.css' --->

bluetooth

Index


btAbortChannel() btAddCfgEntry() btAddClass() btAddErrorMsgA()
btAddFirmwareLoader() btAddHardware() btAddServiceRecordA() btAddStringChunk()
btAllocCfgForm() btAllocChannel() btAllocDevice() btAllocVec()
btBorrowLocksWait() btChannelSetup() btCheckChannel() btClaimAppBindingA()
btClassScan() btConnectDevice() btCopyStr() btCopyStrFmtA()
btDebugSemaphores() btDelayMS() btDisconnectDevice() btDoChannel()
btEnumerateServices() btFindCfgForm() btFindDeviceA() btFindEndpointA()
btFindServiceA() btFreeChannel() btFreeDevice() btFreeVec()
btGetAttrsA() btGetCfgChunk() btGetChannelActual() btGetChannelError()
btGetClsCfg() btGetDevCfg() btGetForcedBinding() btGetNextDevice()
btGetServiceValue() btGetStringChunk() btLoadCfgFromDisk() btLockReadBase()
btLockReadDevice() btLockWriteBase() btLockWriteDevice() btMatchStringChunk()
btNextCfgForm() btPairDeviceA() btPairingReplyA() btParseCfg()
btReadCfg() btRegisterDevice() btReleaseAppBinding() btReleaseDevBinding()
btReleaseSvcBinding() btRemCfgChunk() btRemCfgForm() btRemClass()
btRemErrorMsg() btRemEventHandler() btRemHardware() btRemServiceRecord()
btSafeRawDoFmtA() btSaveCfgToDisk() btSendChannel() btSendEvent()
btSetAttrsA() btSetClsCfg() btSetDevCfg() btSetForcedBinding()
btSetServiceValue() btSpawnSubTask() btStartDiscoveryA() btStopDiscovery()
btUnbindAll() btUnlockBase() btUnlockDevice() btUnpairDevice()
btUnregisterDevice() btWaitChannel() btWriteCfg()  

btAbortChannel()

Synopsis

VOID btAbortChannel(
   APTR pp)

Function

Ask the hardware task to cancel a pending channel request.

Inputs

pp - Live channel. A channel that is not pending needs no action.

Result

None. The call does not report whether cancellation was requested or succeeded.

Notes

Call from the reply-port owner task, never the hardware task.
The call waits for a separate cancellation reply, using the same
port, but does not consume the original request's reply. Finish
with btWaitChannel(pp), or receive that original reply through the
existing message loop, before reusing its buffer or channel.

Completion can win the race with cancellation; do not require
IOERR_ABORTED as the result. Cancellation does not undo remote
effects already performed. Keep the hardware task and port alive
through this operation; there is no timeout.

Bugs

If allocation of the cancellation message fails, the call returns
without requesting cancellation and without reporting failure.

btAddCfgEntry()

Synopsis

APTR btAddCfgEntry(
   APTR bic, APTR formdata)

Function

Copy an IFF chunk or FORM into a configuration context. A plain
chunk replaces the first chunk with the same ID, then appends the
new data. A FORM is appended as a new child; existing FORMs of that
type are retained.

Inputs

bic - Destination context, or NULL for the global root.
formdata - Complete serialized chunk or FORM, including its header
    and even-byte padding.

Result

For a plain chunk, the destination context. For a FORM, the new
child context. NULL if the root is absent, allocation fails or a
FORM cannot be consumed completely.

Notes

Supply a complete, valid IFF buffer with consistent nested lengths
and a padding byte after each odd-length chunk. No buffer length
is passed to this API; malformed input is not safely rejected.
The buffer must not alias storage in the destination tree.

The input is not retained. Returned contexts belong to the tree.
Failure is not atomic: replacement can remove the old chunk before
allocation fails, and failed FORM import can leave a partial child.
Call from task context. Change detection is requested; no file is
saved and no hardware configuration is applied.

Bugs

Replacing a chunk can reach the overlapping-copy defect described
under btRemCfgChunk().

btAddClass()

Synopsis

APTR btAddClass(
   STRPTR name, ULONG version)

Function

Open a Bluetooth class library and register it in binding-priority order.

Inputs

name - Non-NULL, NUL-terminated library name or path.
version - Minimum library version accepted by OpenLibrary().

Result

Class handle, or NULL if no library can be opened, the opened
library name is already registered, or class allocation fails.

Notes

The exact name is tried first. On failure, leading path components
are removed at slash or colon boundaries and the remaining suffixes
are tried in turn. Supply a library implementing the btclass API;
opening an arbitrary library does not validate that interface.

The library remains open until btRemClass(). Higher class priorities
are offered bindings first; priority is stored as the node's signed
byte. Addition sends BEHMB_ADDCLASS, allowing the event handler to
schedule a scan; return does not mean any device has been bound.
Event allocation can fail independently.

Call from task context and serialize class addition, removal and
scans. Keep bluetooth.library open while the class is registered.
Release the handle with btRemClass(), not btFreeVec().

Bugs

Name and path copy failures are not checked before registration.
A non-NULL result can therefore contain missing metadata. Duplicate
checking and insertion are separate operations; concurrent additions
are not guaranteed to reject the same class.

btAddErrorMsgA()

Synopsis

APTR btAddErrorMsgA(
   UWORD level, STRPTR origin, STRPTR fmtstr, RAWARG fmtdata)

Function

Format and append a message to the Bluetooth error-message list,
subject to the configured severity filters.

Inputs

level - Severity. Values below RETURN_WARN are informational;
    RETURN_WARN to below RETURN_ERROR are warnings; RETURN_ERROR
    to below RETURN_FAIL are errors; RETURN_FAIL and above are
    failures.
origin - Non-NULL, NUL-terminated origin name; copied.
fmtstr - Non-NULL, NUL-terminated RawDoFmt format.
fmtdata - Matching RawDoFmt argument stream; referenced data must
    remain unchanged while the message is formatted.

Result

Message handle, or NULL if filtered out or allocation fails. NULL
does not distinguish suppression from failure.

Notes

The message and copied strings belong to the library list. Remove
the message with btRemErrorMsg(), not btFreeVec(). Coordinate with
other message-list users; the handle is not a retained reference.
Inputs are not retained after formatting.

Call from task context. A successful append sends BEHMB_ADDERRORMSG,
but event delivery can fail independently. With btdebug enabled,
output is also sent to the kernel log and, from a DOS process with
DOS available, appended to SYS:BluetoothLog.txt. Output failures
do not change the returned handle.

btAddFirmwareLoader()

Synopsis

VOID btAddFirmwareLoader(
   struct BtFirmwareLoader *loader)

Function

Register a controller-firmware loader and notify matching active adapters.

Inputs

loader - Naturally aligned BtFirmwareLoader with an unlinked node,
    persistent name, callbacks and user data. NULL performs no operation.

Result

None. Registration does not report firmware-loading success.

Notes

The supplied structure is linked directly; it is not copied. Register
it once and keep it, its name, callback code and referenced data valid
until btRemFirmwareLoader() has completed and concurrent registration
or matching calls have ended. The library does not retain the module
that owns the callbacks.

fwl_Match(self, ctx) returns zero for no match or a nonzero priority.
The highest priority wins; ties keep the first registered match.
Matching must use only the identity fields and must not issue HCI
commands. During registration, ctx has no command, log or private
callback state. Matching can run in the registering task or in hardware
tasks; callbacks must tolerate concurrent invocation and must not
register or remove loaders from within a callback.

The selected fwl_Load(self, ctx) runs synchronously in the adapter's
hardware task under a shared firmware-list lock. Return zero for
success or no required download, nonzero for failure. During this
callback ctx supplies synchronous fwc_HciCommand and fwc_Log. Do not retain ctx or invoke its callbacks after fwl_Load returns.
Do not use the channel from another task or nest command operations.
Command parameter length must fit the HCI one-byte length field.
Firmware data is to be read from disk, not fetched from the network.

Registration checks existing adapters that have not been marked
handled and signals matching hardware tasks. Actual loading selects
the best loader again; the newly registered loader need not win.
Loading can occur during initial bring-up or later, when successful
loading triggers controller reinitialization. Return is not a barrier
for either download or reinitialization.

Call from task context with bluetooth.library open. Registration can
wait for active loads. Serialize changes to a given loader's lifetime;
the existing-adapter match pass runs outside the firmware-list lock
while holding the base read lock.

Bugs

Duplicate registration is not checked and can corrupt the loader list.
After selecting a loader, the adapter is marked handled even if the
load fails or fwl_Load is NULL. Registering a replacement does not retry
that adapter; a fresh adapter instance is needed. A handled flag is
not proof of a successful firmware download.

btAddHardware()

Synopsis

APTR btAddHardware(
   STRPTR name, ULONG unit)

Function

Open and initialize a Bluetooth HCI adapter, or return an existing adapter.

Inputs

name - Non-NULL, NUL-terminated HCI device name or path.
unit - Device unit passed to OpenDevice().

Result

Hardware handle after successful initial startup, an existing
matching handle, or NULL if allocation, task creation, device opening
or controller initialization fails. No new ownership reference is
acquired when an existing handle is returned.

Notes

Lookup tries the supplied name, then suffixes following slash or
colon separators. Device opening uses the same fallback order.
A newly started hardware task completes controller bring-up before
the call returns; this can include an installed firmware loader.
An existing handle is returned without rechecking its ready state.

Call from task context with bluetooth.library open. Startup clears
SIGF_SINGLE and waits for the worker using btBorrowLocksWait(); no
caller timeout is provided. The name is copied for a new adapter.
Serialize adapter addition and removal: duplicate lookup and insertion
are not one atomic operation, and returned handles are shared.

A new adapter sends BEHMB_ADDHARDWARE. Event allocation can fail
independently. Use btEnumerateHardware() to restore configured devices
and apply scan settings, and btStartDiscoveryA() for radio discovery.
Remove the shared adapter only after coordinating its users.

btAddServiceRecordA()

Synopsis

APTR btAddServiceRecordA(
   struct TagItem *taglist)

Function

Register a local SDP or GATT service record.

Inputs

taglist - Service definition. NULL lacks the required service UUID.

Tags

BSRA_Protocol - BSVP_RFCOMM (default), BSVP_L2CAP or BSVP_ATT.
BSRA_UUID16 - Nonzero 16-bit service UUID for SDP. For GATT, use
    this or BSRA_UUID128; a supplied UUID128 takes precedence.
BSRA_UUID128 - GATT service UUID: 16 bytes, most significant first.
BSRA_RFCOMMChannel - Required RFCOMM server channel, from 1 to 30.
BSRA_PSM - Required nonzero 16-bit PSM for BSVP_L2CAP. The value
    is encoded without further protocol-validity checks.
BSRA_Name - Optional NUL-terminated service name. SDP publishes at
    most its first 64 bytes; the stored name is copied in full.
BSRA_ProfileUUID16 - SDP profile UUID; defaults to BSRA_UUID16.
BSRA_ProfileVersion - SDP profile version; defaults to 0x0102.
BSRA_Owner - Optional NUL-terminated owner name. Defaults to the
    calling task's name; the string is copied.
BSRA_Characteristics - Array of BtGattCharDef for GATT. Required
    when BSRA_NumCharacteristics is nonzero.
BSRA_NumCharacteristics - GATT array length, from 0 to 64; default 0.
BSRA_LEConnInterval - GATT preferred connection interval in 1.25 ms
    units. Default 0 adds no preference; values above 1199 are
    limited to 1199. This is not a negotiated-interval guarantee.

Result

Service-record handle, or NULL for an invalid required definition,
allocation failure or exhausted GATT attribute-handle space.
A successful result does not guarantee remote availability.

Notes

Each GATT characteristic needs a nonzero bgd_UUID16 or a 16-byte
bgd_UUID128; the 16-bit form takes precedence for characteristics.
Both bgd_Len and bgd_MaxLen must be at most BGATT_MAXVALUE (512).
A nonzero initial length requires bgd_Value. Capacity is the larger
of those lengths. UUIDs, definitions and value bytes are copied.

bgd_Properties uses BGDP_READ, BGDP_WRITENR, BGDP_WRITE, BGDP_NOTIFY
and BGDP_INDICATE. BGDP_STREAM marks an event stream whose remote
reads are empty; writes and notifications remain available. Properties
are not comprehensively validated and do not establish a security
policy. Supply only properties supported by the service.

SDP records start enabled; GATT records start disabled. Registered
server classes receive BCM_ServiceRecordEvent synchronously and may
apply their policy before return. BSRA_Enabled is not a creation tag;
use btSetAttrsA(BGA_SERVICERECORD, ...) to change it. Creating a record
does not create a listening application or prove that a class can
serve the advertised protocol.

Call from task context, keep bluetooth.library open and serialize
record removal with all users. Class callbacks run with the base read
lock held; avoid incompatible locks or reentrant record removal.
Input storage is not retained. Release with btRemServiceRecord().

Bugs

Failure to copy the name or owner is not checked, so a non-NULL
record may have missing metadata. Duplicate service UUIDs and transport
endpoints are not rejected. SDP UUIDs, PSM and profile fields are
encoded as 16-bit values; out-of-range ULONG values are not rejected.

btAddStringChunk()

Synopsis

BOOL btAddStringChunk(
   APTR bic, ULONG chunkid, CONST_STRPTR contents)

Function

Copy a terminated string into a plain chunk, replacing the first
chunk with the same ID. The stored length includes the terminator.

Inputs

bic - Live context; NULL is not a root shorthand here.
chunkid - Plain-chunk ID in host byte order; do not use ID_FORM.
contents - Non-NULL, NUL-terminated string.

Result

TRUE if stored; FALSE if allocation fails.

Notes

The string is copied before replacement and is not retained.
Failure after replacement begins can remove the old chunk. Call
from task context. This function does not request change detection,
apply the configuration or save it to disk.

Bugs

Replacing an existing chunk can reach the overlapping-copy defect
described under btRemCfgChunk().

btAllocCfgForm()

Synopsis

APTR btAllocCfgForm(
   ULONG formid)

Function

Create an empty, independent configuration FORM. It is not attached
to the global configuration tree.

Inputs

formid - FORM type in host byte order.

Result

New context, or NULL on allocation failure.

Notes

Release the context and its descendants with btRemCfgForm(), not
btFreeVec(). Keep bluetooth.library open until it is released.
Populate it with btAddCfgEntry() or btReadCfg(). To add its contents
to another tree, serialize it with btWriteCfg() and add that buffer;
a context pointer is not a serialized FORM. Call from task context.

btAllocChannel()

Synopsis

APTR btAllocChannel(
   APTR bd, struct MsgPort *mp, APTR bep)

Function

Allocate a reusable request channel for a device or one of its endpoints.

Inputs

bd - Live device handle; NULL returns NULL.
mp - Initialized reply port; NULL returns NULL. Use a signal port
    owned by the task that will call the channel wait functions.
bep - Endpoint belonging to bd, or NULL for device control requests.

Result

Channel handle, or NULL for invalid arguments or allocation failure.

Notes

Call from task context. Keep the library, reply port, hardware and
endpoint valid until btFreeChannel(). The channel holds a device
usage count, but does not independently retain its endpoint across
service refresh. Coordinate refresh and removal with the channel
owner. Do not free the channel with btFreeVec().

An endpoint channel starts with BTPR_READ. Configure a control
channel with btChannelSetup() before submission. Auto-connect is
copied from the device policy; it is not a live link to that policy.
Allocation may wait for the hardware task using SIGB_SINGLE. A
returned handle does not establish that a remote channel is open;
the internal open request's error is not returned.

btAllocDevice()

Synopsis

APTR btAllocDevice(
   APTR bth)

Function

Allocate a remote-device object and append it to an adapter's device list.

Inputs

bth - Live hardware handle. NULL is invalid.

Result

Device handle, or NULL if the device allocation fails.

Notes

The object starts without an address, name, services, registration
or connection. RSSI is initialized to 127; automatic connection uses
the current global default. The adapter device count is incremented.
No radio operation, duplicate-address check or add-device event occurs.

This is an object-construction operation, not device discovery.
Coordinate initialization with list readers: the object is already
visible when returned. Keep the adapter and bluetooth.library valid,
call from task context and serialize with adapter removal. Release
with btFreeDevice(), not btFreeVec().

btAllocVec()

Synopsis

APTR btAllocVec(
   ULONG size)

Function

Allocate cleared public memory from the Bluetooth library pool.
The returned address meets AROS_WORSTALIGN.

Inputs

size - Requested byte count.

Result

Allocated memory, or NULL if allocation fails.

Notes

Release the exact returned address with btFreeVec(), not FreeVec().
Keep bluetooth.library open until all allocations are released.
A zero-size request may return a pointer, but provides no usable
bytes. Call from task context.

Bugs

Allocation overhead is added without overflow checking. Requests
near the ULONG limit can return a block smaller than requested;
do not use this function to validate externally supplied sizes.

btBorrowLocksWait()

Synopsis

ULONG btBorrowLocksWait(
   struct Task *task, ULONG signals)

Function

Temporarily lend the calling task's tracked Bluetooth locks to
another task while waiting for a signal, then restore the caller's
acquisitions. A target already waiting for a lock may be allowed
to acquire it instead of receiving its ownership directly.

Inputs

task - Live, cooperating target task, distinct from the caller.
signals - Nonzero Exec signal mask to wait for in the calling task.

Result

Signal mask returned by Wait(). Restoring the locks may delay
return beyond receipt of the signal.

Notes

Call from task context. This applies only to locks registered with
bluetooth.library, not arbitrary Exec semaphores. With no tracked
locks held, it is equivalent to Wait(signals).

Arrange a completion handshake before calling. The target must
balance its own acquisitions, leave borrowed acquisitions intact
and keep the protected objects and locks alive until restoration.
The target and entry code must remain valid through the handshake.
There is no timeout or cancellation result. Do not use a stale
signal as evidence that the target has finished.

Bugs

Allocation failure can leave some locks with the caller while it
waits, without an error result. A target needing those locks can
then deadlock. Lending is not an atomic all-or-nothing operation.

btChannelSetup()

Synopsis

VOID btChannelSetup(
   APTR pp, UWORD rq, UWORD val, UWORD idx)

Function

Set the request and its two 16-bit parameters for the next submission.

Inputs

pp - Idle channel whose preceding reply has been consumed.
rq - BTPR_* request from libraries/bluetooth.h.
val, idx - Request parameters described below; use zero when unused.

Result

None.

Notes

Endpoint channels use BTPR_READ to receive one SDU or notification,
or BTPR_WRITE to send data. val and idx are unused. A GATT endpoint
read waits for a notification or indication; it is not an ATT read.

Control channels have no endpoint and support these requests:
BTPR_REMOTENAME - Receive a NUL-terminated remote name; buffer
    capacity includes the terminator. Actual excludes that terminator.
BTPR_SDPSEARCH - val is the 16-bit service UUID. Receive consecutive
    four-byte, big-endian record handles; Actual is a byte count.
BTPR_SDPATTRIBUTES - val is the low half and idx the high half of
    a record handle. Receive the attribute sequence's nested bytes.
BTPR_GATTREAD - val is the remote attribute handle; receive its value.
BTPR_GATTWRITE - val is the handle; send a value with a response.
BTPR_GATTWRITENORSP - val is the handle; send without a response.
BTPR_READRSSI - Receive one signed BYTE from the cached inquiry or
    advertising result; 127 means unknown.

Setup performs no I/O or validation. The settings remain until
changed. Keep the channel idle while changing them. Payload buffers
are supplied to btSendChannel() or btDoChannel().

Bugs

BTPR_L2CAPECHO is declared but is not handled; it returns BTIOERR_NOTSUPPORTED.

btCheckChannel()

Synopsis

APTR btCheckChannel(
   APTR pp)

Function

Check whether a channel is still pending without waiting.

Inputs

pp - Live channel handle; NULL is invalid.

Result

NULL while pending; otherwise pp, including for a newly allocated channel.

Notes

A non-NULL result is neither a success status nor proof that a
request was submitted. It does not remove a reply from the port.
Consume the reply before resubmitting or freeing the channel, then
inspect Error and Actual. Serialize access with submitters and
consumers; this call does not lock the channel.

btClaimAppBindingA()

Synopsis

APTR btClaimAppBindingA(
   struct TagItem *taglist)

Function

Claim exclusive application ownership of a device's binding slot.

Inputs

taglist - Application-binding tags. NULL lacks the required device and hook.

Tags

BABA_Device - Required live device handle.
BABA_ReleaseHook - Required Hook pointer, retained until release.
BABA_UserData - IPTR passed to the release hook as its message
    argument. Supply explicitly, using zero if no data is needed.
BABA_ForceRelease - FALSE by default. TRUE releases an existing
    device binding, or existing service bindings when no device
    binding exists, before attempting the claim.
BABA_Task - Replaced by the calling task on successful allocation;
    it cannot assign ownership to another task.

Result

Application-binding handle, or NULL if required inputs are absent,
a device or service binding remains, or allocation fails.

Notes

Call from task context. A successful claim excludes class bindings
through the device's application-binding flag; it does not establish
a connection, register the device or retain its lifetime. Serialize
claims with scans, device removal and other binding changes.

The release hook is called synchronously in the releasing task,
which need not be the claimant. Its object is the binding handle;
its message is BABA_UserData converted to APTR. The device write
lock is held and the device's binding pointer has already been
cleared. The hook result is ignored. Finish application cleanup
before returning; the binding is then freed by the library.

Keep the hook, its code, referenced user data, claimant task and
bluetooth.library valid until release finishes. Do not free the
binding yourself or claim a replacement from within its release
hook. Avoid waiting for work that needs the held device lock.
Release a live claim with btReleaseAppBinding().

Bugs

Omitting BABA_UserData leaves the callback argument uninitialized.
Forced release is destructive: failure to allocate the new binding
does not restore the old bindings. It is not an atomic replacement.

btClassScan()

Synopsis

VOID btClassScan(
   )

Function

Offer eligible known devices and services to registered Bluetooth classes.

Inputs

None.

Result

None. Individual binding failures are not returned.

Notes

A device must be registered, have known services, permit class
binding and have no device or application binding. Existing service
bindings are preserved. Classes are visited in priority order;
forced class configuration restricts which class is offered a
binding. A successful binding sends BEHMB_ADDBINDING.

This is a synchronous scan of existing objects, not radio discovery
or remote service enumeration. Class methods can start workers and
wait for I/O. Call from task context outside the hardware task and
serialize scans with class changes and application claims. The base
read lock remains held across the scan; callbacks must not wait for
another task that needs exclusive base access.

At most 16 unbound, eligible services per device are selected in one
scan. Device-binding methods are called with the device write lock
held on the normal fallback path; service-binding attempts release
that lock. Do not assume every service is attempted in one call.

Bugs

The scan's service-binding status is not initialized before it is
tested. Forced-device selection and device-binding fallback can
therefore depend on an indeterminate value. The implementation does
not provide reliable device-binding selection when no service has
set that status.

btConnectDevice()

Synopsis

BOOL btConnectDevice(
   APTR bd)

Function

Establish a connection to a known Bluetooth device.

Inputs

bd - Live device handle.

Result

TRUE when the selected transport is connected, including an already
connected transport. FALSE for NULL, unavailable hardware, an
unsupported transport, resource failure or connection failure.
Detailed errors are not returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

Selects classic Bluetooth when supported by both device and adapter;
otherwise selects LE. For a dual-mode device, an additional connection
is attempted on the other transport without waiting for its result.
TRUE does not establish that both transports, pairing, service
enumeration or class binding have completed.

Explicit connection clears the device's temporary reconnect hold.
The configured automatic-connection policy is not changed.

Call from a task other than the adapter's hardware task. Keep the
device, adapter and bluetooth.library valid until return. The call
uses SIGF_SINGLE and waits without a caller timeout or cancellation
parameter. Do not hold locks needed by the hardware task.

btCopyStr()

Synopsis

STRPTR btCopyStr(
   CONST_STRPTR name)

Function

Allocate a copy of a NUL-terminated string, including its terminator.

Inputs

name - Non-NULL source string, valid for the duration of the call.

Result

Independent string copy, or NULL on allocation failure.

Notes

Release with btFreeVec(). Keep the library open until the copy is
freed. The source is not retained. Call from task context. The
string length and allocation overhead must fit the allocator's
ULONG size range.

btCopyStrFmtA()

Synopsis

STRPTR btCopyStrFmtA(
   CONST_STRPTR fmtstr, RAWARG fmtdata)

Function

Allocate a string containing formatted RawDoFmt output.

Inputs

fmtstr - Non-NULL, NUL-terminated RawDoFmt format.
fmtdata - Matching RawDoFmt argument stream; NULL is valid only
    when no arguments are consumed.

Result

Allocated terminated string, or NULL on allocation failure.

Notes

The format is evaluated twice, first to measure and then to write.
Keep the argument stream and all referenced data unchanged through
both passes. The result is independent of those inputs. Release it
with btFreeVec() before closing the library. Call from task context.
Output length, terminators and allocation overhead must fit ULONG;
length arithmetic is not checked for overflow.

btDebugSemaphores()

Synopsis

VOID btDebugSemaphores(
   )

Function

Append diagnostic records for registered Bluetooth locks to the
Bluetooth error-message list. Include owners, nesting counts,
waiting tasks and reader records.

Inputs

None.

Result

None. Individual message allocation failures are not reported.

Notes

Call from task context. Records use RETURN_OK and can be suppressed
by the information-log setting. Logging can allocate memory, emit
events and perform configured debug output. This does not acquire
the reported locks, resolve a deadlock or validate lock ownership.

See also

btAddErrorMsgA()


btDelayMS()

Synopsis

VOID btDelayMS(
   ULONG milli)

Function

Submit a timer.device delay and wait for its completion.

Inputs

milli - Requested delay in milliseconds.

Result

None. Timer errors are not returned.

Notes

Call from task context with bluetooth.library open. The wait uses
SIGB_SINGLE in the calling task; do not use that signal concurrently
for another protocol. Scheduling may extend the elapsed delay.
Zero still submits a zero-duration timer request; this is not a
precision timing or cancellation interface.

btDisconnectDevice()

Synopsis

BOOL btDisconnectDevice(
   APTR bd)

Function

Request disconnection of both transports of a Bluetooth device.

Inputs

bd - Live device handle.

Result

TRUE if the request was processed, including when no connection
exists. FALSE for NULL or a missing hardware task. Detailed errors
are not returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

Requests disconnection of established links and cancellation of
connection attempts. Return does not wait for controller completion;
command-submission and controller failures are not returned. Monitor
BEHMB_DEVICEDISCONNECTED and current device state for completion.
Registration, stored keys and the configured automatic-connection
policy remain unchanged. A locally terminated link can enter a
temporary reconnect hold, cleared by an explicit connection request.

Call from a task other than the adapter's hardware task. Keep the
device, adapter and bluetooth.library valid during the call. It uses
SIGF_SINGLE and waits for the hardware task without a caller timeout.
Do not hold locks that task needs.

btDoChannel()

Synopsis

LONG btDoChannel(
   APTR pp, APTR data, ULONG len)

Function

Submit a channel request and wait for its reply.

Inputs

pp - Idle channel with no unconsumed previous reply.
data - Request buffer, with the direction and lifetime required by
    btSendChannel().
len - Read capacity or write length in bytes.

Result

Zero on success, or an IOERR_* or BTIOERR_* completion code.

Notes

This combines btSendChannel() and btWaitChannel(). Call from the
reply-port owner task, never the hardware task servicing the channel.
The reply is consumed before return; do not wait for it again.
Use btGetChannelActual() for the byte count or request-specific
error detail. Keep all request storage valid until return.

No overall timeout is enforced. The call can wait indefinitely;
holding a lock needed by the hardware task can deadlock it.

btEnumerateServices()

Synopsis

BOOL btEnumerateServices(
   APTR bd)

Function

Refresh remote services on the selected transport of a Bluetooth device.

Inputs

bd - Live device handle.

Result

TRUE when enumeration completes successfully, including an empty
result. FALSE for NULL, unavailable hardware, unsupported transport,
connection or enumeration failure, or another explicit enumeration
request already waiting. Detailed errors are not returned through
IoErr().
Hardware shutdown also returns FALSE.

Notes

Connects if necessary, preferring classic Bluetooth when supported
by both device and adapter; otherwise uses LE. Enumerates SDP on
classic Bluetooth or GATT on LE. It does not explicitly refresh both
transports. An active enumeration without an explicit waiter is
joined; otherwise a new refresh is started.

Refresh closes endpoint state and can free unbound service and
endpoint objects on that transport. Bound services and services being
bound are retained for refresh in place. Quiesce endpoint users and
release channels referring to unbound endpoints before calling;
reacquire service and endpoint handles afterward. Keeping a device
handle or an allocated channel does not pin those endpoint objects.
Failure can leave partially refreshed results; the old list is not
restored.

Success marks services known and sends BEHMB_SERVICESCHG. The return
value is not a service count and does not wait for class binding.

Call from a task other than the adapter's hardware task. Keep the
device, adapter and bluetooth.library valid until return. The call
uses SIGF_SINGLE and waits without a caller timeout or cancellation
parameter. Do not hold locks needed by the hardware task.

btFindCfgForm()

Synopsis

APTR btFindCfgForm(
   APTR bic, ULONG formid)

Function

Find the first immediate child FORM of the requested type. The
search does not descend into grandchildren or test the parent itself.

Inputs

bic - Parent context, or NULL for the global root.
formid - FORM type to find, in host byte order.

Result

Borrowed child context, or NULL if no match or no root exists.

Notes

The context is borrowed, not a snapshot. Do not free it directly.
Prevent concurrent removal or replacement while using it; internal
locking does not extend its lifetime after this call returns.
Call from task context. Use btNextCfgForm() to find later siblings
of the same type.

btFindDeviceA()

Synopsis

APTR btFindDeviceA(
   APTR bd, struct TagItem *taglist)

Function

Find the next known device that satisfies all supplied supported filters.

Inputs

bd - Previous active device, excluded from the search; NULL starts
    at the first device across all radios.
taglist - Filter tags, or NULL for no filtering.

Tags

BDA_Address - Pointer to six address bytes in BD_ADDR order.
BDA_AddressString - Address text in XX:XX:XX:XX:XX:XX form;
    comparison ignores case.
BDA_AddressType, BDA_ClassOfDevice, BDA_VendorID, BDA_ProductID -
    Exact numeric values.
BDA_Hardware, BDA_Binding - Exact handle values; NULL can match
    an absent binding.
BDA_Name, BDA_IDString - NUL-terminated, case-sensitive strings.
    A missing device string does not match.
BDA_IsRegistered, BDA_IsConnected - Boolean tests; nonzero means TRUE.
BDA_ConnHandle - Exact handle; the device must also be connected.

Result

Borrowed device handle, or NULL if no later device matches.

Notes

This searches existing objects, not the air. Unknown filter tags
are ignored, including device attribute tags not listed above.
Only the first occurrence of each filter is used; standard TagItem
control tags are honored. Pointer-valued filter data must remain
valid throughout the call and is not retained.

No lock is acquired or lifetime extended. Exclude list and attribute
changes during the search and preserve the returned object's
lifetime while using it. Continue with the returned handle to find
later matches.

btFindEndpointA()

Synopsis

APTR btFindEndpointA(
   APTR bsv, APTR bep, struct TagItem *taglist)

Function

Find the next matching endpoint in a known service.

Inputs

bsv - Service whose endpoints are searched; NULL returns NULL.
bep - Previous endpoint in that service, excluded from the search;
    NULL starts at the first endpoint.
taglist - Filter tags, or NULL for no filtering.

Tags

BEA_CanRead, BEA_CanWrite - Boolean tests; nonzero means TRUE.
BEA_Type, BEA_PSM, BEA_CID, BEA_RFCOMMChannel, BEA_Handle,
BEA_UUID16, BEA_ReportType, BEA_ReportID - Exact numeric values.
BEA_UUID - Pointer to 16 UUID bytes in big-endian order; exact match.
BEA_Properties - Required property bits. All supplied bits must be
    present; extra endpoint bits are allowed. Zero matches any value.

Result

Borrowed endpoint handle, or NULL if no later endpoint matches.

Notes

All supplied supported filters must match. Unknown tags are ignored;
only the first occurrence of each filter is used. Standard TagItem
control tags are honored. Filter data is not retained.

No channel is opened and no lock is acquired. Keep the service and
cursor valid and exclude endpoint changes during traversal, using
the owning device's read lock where required. The result is not a
retained reference: service refresh can free unbound endpoints.
A capability match does not establish a connection or guarantee I/O.

btFindServiceA()

Synopsis

APTR btFindServiceA(
   APTR bd, APTR bsv, struct TagItem *taglist)

Function

Find the next matching service already known for a device.

Inputs

bd - Device whose service list is searched; NULL returns NULL.
bsv - Previous service in that device's list, excluded from the
    search; NULL starts at the first service.
taglist - Filter tags, or NULL for no filtering.

Tags

BSVA_UUID16 - Exact primary 16-bit UUID or an entry in the service's
    zero-terminated service-class ID list.
BSVA_UUID - Pointer to 16 UUID bytes in big-endian order; exact match
    against the primary UUID, without service-class ID expansion.
BSVA_Protocol, BSVA_PSM, BSVA_RFCOMMChannel, BSVA_RecordHandle -
    Exact numeric values.
BSVA_Name, BSVA_IDString - NUL-terminated, case-sensitive strings;
    a missing service string does not match.
BSVA_Binding - Exact binding handle; NULL matches no binding.

Result

Borrowed service handle, or NULL if no later service matches.

Notes

All supplied supported filters must match. Unknown tags are ignored;
only the first occurrence of each filter is used. Standard TagItem
control tags are honored. Filter data is not retained.

This does not enumerate remote services or acquire a lock. Keep the
device and cursor valid and exclude service-list changes during
traversal. A device read lock protects traversal against service
replacement; it does not retain a service after unlocking. Service
refresh or device removal can invalidate returned handles.

btFreeChannel()

Synopsis

APTR btFreeChannel(
   APTR pp)

Function

Release a channel and its device usage count.

Inputs

pp - Channel handle, or NULL for no operation.

Result

No defined return value. Ignore the public APTR result.

Notes

Call from the reply-port owner task. Complete and consume the last
reply before freeing the channel. Keep the library, port and hardware
valid through the call. No other task may use the channel afterward.
The reply port and caller's data buffer are not freed.

A pending request triggers an abort followed by a wait. Closing an
endpoint channel can also wait for the hardware task. There is no
bounded completion guarantee. Releasing the last device usage count
can finish deferred device cleanup.

Bugs

The public declaration returns APTR, but the implementation returns
void. It does not produce a valid pointer result. A reply already
queued on the port is not removed when freeing a completed channel;
consume it first to avoid leaving a freed message in the queue.

btFreeDevice()

Synopsis

VOID btFreeDevice(
   APTR bd)

Function

Remove a device from active enumeration and release its bindings and resources.

Inputs

bd - Live device on its adapter's active list. NULL is invalid.

Result

None. Outstanding channel use can defer resource cleanup.

Notes

Complete connection shutdown and outstanding I/O, release channels
and quiesce all device users before calling. The function moves the
device to the adapter's dead-device list and decrements the active
count. Class and application release callbacks run synchronously
under the device write lock. Do not call from a worker they must stop
or wait for another task that needs that lock.

A nonzero device use count defers final cleanup until the last channel
is released. Otherwise services, endpoints and selected device metadata
are released and the device is unlinked. Treat the handle and all
child handles as invalid after this call; do not call it twice or
free the returned storage yourself.

Call from task context with the adapter and bluetooth.library valid.
The call does not request a controller disconnect, delete persistent
registration or emit BEHMB_REMDEVICE. It has no callback timeout.

Bugs

Final cleanup deliberately leaves the device allocation resident.
That allocation is not a usable retained handle: its semaphore and
child resources have been dismantled. Retention does not make calls
through stale device pointers safe.

btFreeVec()

Synopsis

VOID btFreeVec(
   APTR memptr)

Function

Release memory allocated by btAllocVec() or an API that specifies
btFreeVec() as its release function.

Inputs

memptr - Exact allocation address, or NULL for no operation.

Result

None.

Notes

Release each allocation once, through the same library instance.
Interior pointers and memory from other allocators are invalid.
The allocation must no longer be in use. Call from task context.

btGetAttrsA()

Synopsis

LONG btGetAttrsA(
   ULONG type, APTR btstruct, struct TagItem *taglist)

Function

Read attributes of a Bluetooth object into caller-provided result storage.

Inputs

type - BGA_* object type listed under TAGS.
btstruct - Live object of that type. Ignored for BGA_STACK and
    BGA_STACKCFG, which use the library's current objects.
taglist - Query tags, or NULL. Each ti_Data is a result address,
    not the value to retrieve.

Tags

Supported tags follow, grouped by object type. Enum and flag values
are defined in <libraries/bluetooth.h>. All table results use IPTR
storage, including pointer-valued and narrow numeric attributes.

BGA_STACK:

    Pointer or IPTR values:
        BSA_GlobalConfig.

    Unsigned values and booleans:
        BSA_ConfigRead, BSA_MemPoolUsage, BSA_CurrConfigHash,
        BSA_SavedConfigHash, BSA_ReleaseVersion, BSA_OSVersion,
        BSA_LEAdvertising, BSA_EIRServices, BSA_LEConnInterval.

    BSA_HardwareList, BSA_ClassList, BSA_ErrorMsgList,
    BSA_ServiceRecordList - borrowed struct List pointers.
    BSA_LENotifyPayload - ULONG result; minimum nonzero cached adapter
        payload, with a floor of 20 bytes. A snapshot, not a reservation.

BGA_BTCLASS:

    Pointer or IPTR values:
        BCA_ClassBase, BCA_ClassName, BCA_FullPath.

    Unsigned values and booleans:
        BCA_UseCount.

BGA_HARDWARE:

    Pointer or IPTR values:
        BHA_DeviceName, BHA_ProductName, BHA_Manufacturer,
        BHA_Description, BHA_Copyright, BHA_LocalName.

    Unsigned values and booleans:
        BHA_DeviceUnit, BHA_Version, BHA_Revision,
        BHA_DriverVersion, BHA_NumDevices, BHA_State,
        BHA_ClassOfDevice, BHA_HCIVersion, BHA_HCIRevision,
        BHA_LMPVersion, BHA_LMPSubversion, BHA_ManufacturerID,
        BHA_ACLMaxPktSize, BHA_ACLNumPkts, BHA_SCOMaxPktSize,
        BHA_SCONumPkts, BHA_LEACLMaxPktSize, BHA_LEACLNumPkts,
        BHA_ErrorCount, BHA_LastHCIError, BHA_IsClassic, BHA_IsLE,
        BHA_IsDiscovering, BHA_Discoverable, BHA_Connectable.

    BHA_DeviceList - borrowed struct List pointer.
    BHA_Address - borrowed BD_ADDR pointer.
    BHA_AddressString, BHA_ManufacturerName - borrowed strings.
    BHA_Features, BHA_LEFeatures - borrowed eight-byte feature arrays.
    BHA_LECaps, BHA_AcceptListSize, BHA_ResolvingListSize,
    BHA_LEReconnect, BHA_IsReady - IPTR results.

BGA_DEVICE:

    Pointer or IPTR values:
        BDA_Name, BDA_OrigName, BDA_Hardware, BDA_Binding,
        BDA_BindingClass, BDA_IDString.

    Signed values:
        BDA_RSSI.

    Unsigned values and booleans:
        BDA_AddressType, BDA_ClassOfDevice, BDA_Appearance,
        BDA_ConnHandle, BDA_Role, BDA_LinkType, BDA_BondFlags,
        BDA_NumServices, BDA_VendorID, BDA_ProductID,
        BDA_ProductVersion, BDA_VendorIDSource, BDA_LMPVersion,
        BDA_ManufacturerID, BDA_AdvDataLength, BDA_PairingState,
        BDA_PairingRequest, BDA_PairingPasskey, BDA_IsNewToMe,
        BDA_InhibitPopup, BDA_InhibitClassBind, BDA_AutoConnect,
        BDA_Trusted, BDA_IsClassic, BDA_IsLE, BDA_IsDiscovered,
        BDA_IsRegistered, BDA_IsBonded, BDA_IsConnected,
        BDA_IsEncrypted, BDA_IsDead, BDA_HasAppBinding,
        BDA_ServicesKnown.

    BDA_ServiceList - borrowed struct List pointer.
    BDA_Address - borrowed BD_ADDR pointer.
    BDA_AddressString - borrowed string.
    BDA_AdvData - borrowed byte array; length is BDA_AdvDataLength.
    BDA_LastSeen, BDA_FirstSeen - borrowed DateStamp pointers.

BGA_SERVICE:

    Pointer or IPTR values:
        BSVA_Device, BSVA_Name, BSVA_Binding, BSVA_BindingClass,
        BSVA_IDString, BSVA_ServiceClassIDs, BSVA_HIDDescriptor.

    Unsigned values and booleans:
        BSVA_UUID16, BSVA_Protocol, BSVA_PSM, BSVA_RFCOMMChannel,
        BSVA_RecordHandle, BSVA_StartHandle, BSVA_EndHandle,
        BSVA_Version, BSVA_IsPrimary, BSVA_NumEndpoints,
        BSVA_HIDDescriptorLen, BSVA_Incoming.

    BSVA_EndpointList - borrowed struct List pointer.
    BSVA_UUID - borrowed 16-byte UUID.
    BSVA_UUIDString - the borrowed service ID string, also returned
        by BSVA_IDString; not a separately formatted UUID string.

BGA_ENDPOINT:

    Pointer or IPTR values:
        BEA_Service, BEA_Name.

    Unsigned values and booleans:
        BEA_CanRead, BEA_CanWrite, BEA_Type, BEA_PSM, BEA_CID,
        BEA_RFCOMMChannel, BEA_Handle, BEA_UUID16, BEA_Properties,
        BEA_MaxPktSize, BEA_ReportID, BEA_ReportType,
        BEA_CCCDHandle, BEA_ReportRefHandle.

    BEA_UUID - borrowed 16-byte UUID.
    BEA_IsOpen - IPTR boolean; tests the endpoint's channel pointer.

BGA_ERRORMSG:

    Pointer or IPTR values:
        BEMA_Origin, BEMA_Msg.

    Unsigned values and booleans:
        BEMA_Level.

    BEMA_DateStamp - borrowed DateStamp pointer.

BGA_CHANNEL:

    Pointer or IPTR values:
        BCHA_Endpoint, BCHA_Device.

    Signed values:
        BCHA_Error.

    Unsigned values and booleans:
        BCHA_Actual, BCHA_Timeout, BCHA_AutoConnect, BCHA_NoWait.

    BCHA_MaxPktSize - IPTR result from the endpoint, or zero for a
        channel without an endpoint.

BGA_APPBINDING:

    Pointer or IPTR values:
        BABA_ReleaseHook, BABA_Device, BABA_UserData, BABA_Task.

    Unsigned values and booleans:
        BABA_ForceRelease.

BGA_EVENTNOTE:

    Pointer or IPTR values:
        BENA_Param1, BENA_Param2, BENA_Data, BENA_Device.

    Unsigned values and booleans:
        BENA_EventID, BENA_DataLength.

BGA_STACKCFG:

    Signed values:
        BGCA_SubTaskPri.

    Unsigned values and booleans:
        BGCA_LogInfo, BGCA_LogWarning, BGCA_LogError,
        BGCA_LogFailure, BGCA_BootDelay, BGCA_PopupDeviceNew,
        BGCA_PopupDeviceGone, BGCA_PopupPairing,
        BGCA_PopupCloseDelay, BGCA_PopupActivateWin,
        BGCA_PopupWinToFront, BGCA_Discoverable, BGCA_Connectable,
        BGCA_DiscoveryTime, BGCA_AutoConnect, BGCA_PrefsVersion.

    BGCA_LocalName - borrowed string in the global configuration.

BGA_SERVICERECORD:

    Pointer or IPTR values:
        BSRA_Name, BSRA_Owner.

    Unsigned values and booleans:
        BSRA_UUID16, BSRA_Protocol, BSRA_RFCOMMChannel, BSRA_PSM,
        BSRA_NumCharacteristics, BSRA_LEConnInterval, BSRA_Enabled,
        BSRA_FirstHandle, BSRA_LastHandle.

    BSRA_UUID128 - borrowed 16-byte UUID, or NULL when the record
        does not use a 128-bit UUID.

Result

Number of recognized attributes written, or -1 for an unsupported
type. Zero means no requested attribute was handled. Unknown tags
leave their destination untouched. Only the first occurrence of each
recognized tag is used; the count is not the tag-list length.

Notes

Use an aligned IPTR slot for each table-derived result, even when
the underlying value is a byte, word or ULONG. Signed fields are
sign-extended; interpret their result as SIPTR when needed. For the
explicit pointer results listed under TAGS, supply the address of a
pointer of the stated type. BSA_LENotifyPayload is the exception
among scalar results: its destination must be ULONG storage.

No destination may be NULL for a recognized query. For types other
than STACK and STACKCFG, the object must match type and remain live;
there is no runtime handle validation. Pointer-valued attributes may return NULL.

Returned strings, arrays, lists and object pointers are borrowed.
Do not modify or free them. Coordinate object lifetime and updates;
return does not acquire a reference or copy pointed-to data. Traverse
base-owned lists under the base read lock and device-owned lists under
the appropriate device lock. Event data is valid only until ReplyMsg().

Call from task context with bluetooth.library open. Apart from the
payload calculation's internal base lock, this function does not lock
objects or provide an atomic snapshot across attributes. Copy needed
data while its owner is protected. Service and endpoint pointers can
be invalidated by remote service refresh.

btGetCfgChunk()

Synopsis

APTR btGetCfgChunk(
   APTR bic, ULONG chnkid)

Function

Copy the first plain chunk with a matching ID. Only the supplied
context is searched. A root query also refreshes its stored global
settings from the running stack.

Inputs

bic - Live context, or NULL for the global root.
chnkid - Chunk ID in host byte order.

Result

Allocated chunk including its eight-byte header, or NULL if no
match or root exists, or allocation fails. Release with btFreeVec().

Notes

The returned size is eight plus the big-endian payload length in
the header. An odd-length payload has no extra padding byte in this
copy. Add padding before passing such a copy to btAddCfgEntry().

The copy is independent of later configuration changes. Its payload
is opaque and may contain native structures. Keep bluetooth.library
open until it is freed. Call from task context and serialize root
queries with other configuration access.

btGetChannelActual()

Synopsis

ULONG btGetChannelActual(
   APTR pp)

Function

Read the channel's stored transfer count or request-specific error detail.

Inputs

pp - Live channel handle; NULL is invalid.

Result

On successful data transfer, the number of bytes transferred.
For BTIOERR_OVERFLOW, the number of bytes copied, not the full
required capacity. For BTIOERR_REMOTEERROR, this may instead be
an HCI status, ATT error code or SDP client result.

Notes

Check completion and Error before interpreting this value. A new
channel and each submission start with zero. This call neither
waits nor consumes a reply; a value read while pending is not a
completion indication. Remote-name counts exclude the terminating
NUL; SDP search counts are bytes, not record counts.

btGetChannelError()

Synopsis

LONG btGetChannelError(
   APTR pp)

Function

Read the channel's stored error code without waiting or consuming a reply.

Inputs

pp - Live channel handle; NULL is invalid.

Result

Zero for a successful completed request; otherwise an IOERR_* or
BTIOERR_* code from exec/errors.h, devices/bluetoothhci.h or
libraries/bluetooth.h.

Notes

A new channel and each submission start with zero. Establish
completion before treating zero as success. btGetChannelActual()
can contain a partial byte count or remote error detail. Reading
the status does not update device reachability history.

btGetClsCfg()

Synopsis

APTR btGetClsCfg(
   STRPTR owner)

Function

Find private class data for the first matching owner entry.

Inputs

owner - Non-NULL, NUL-terminated class owner name. Case-sensitive.

Result

Borrowed GCPD context, or NULL if the owner or its data is absent.

Notes

The context is borrowed, not a snapshot. Do not free it directly.
Prevent concurrent removal or replacement while using it; internal
locking does not extend its lifetime after this call returns.
The search does not continue past a matching owner whose data FORM
is missing. Call from task context.

btGetDevCfg()

Synopsis

APTR btGetDevCfg(
   STRPTR owner, STRPTR devid, STRPTR svcid)

Function

Find an owner-specific data FORM under the first matching device
entry, optionally selecting a service within that device.

Inputs

owner - Non-NULL, NUL-terminated class owner name.
devid - Non-NULL, NUL-terminated device ID.
svcid - Non-NULL service ID, or NULL for device-wide data.
    Comparisons are case-sensitive.

Result

Borrowed DCPD or SCPD context, or NULL if the selected data is absent.

Notes

The context is borrowed, not a snapshot. Do not free it directly.
Prevent concurrent removal or replacement while using it; internal
locking does not extend its lifetime after this call returns.
Later duplicate device entries are not searched. Call from task
context; no context is created by this query.

btGetForcedBinding()

Synopsis

STRPTR btGetForcedBinding(
   STRPTR devid, STRPTR svcid)

Function

Find the recorded class owner for a device or service. Search only
the first matching device entry.

Inputs

devid - Non-NULL, NUL-terminated device ID.
svcid - Service ID, or NULL for the device-wide choice.
    Comparisons are case-sensitive.

Result

Borrowed owner string, or NULL if no matching choice exists.

Notes

Do not modify or free the string. Copy it while configuration
changes are excluded if it must survive another configuration call.
Chunk replacement, buffer growth or form removal can invalidate it.
Internal locking ends before return. A service query does not fall
back to the device-wide choice. Call from task context.

btGetNextDevice()

Synopsis

APTR btGetNextDevice(
   APTR bd)

Function

Return the next device in hardware-list order, skipping empty radios.

Inputs

bd - Previous device in the active device list, or NULL to start.

Result

Borrowed device handle, or NULL at the end of the list.

Notes

This enumerates known devices, including disconnected devices; it
does not perform discovery. No lock is acquired and no reference is
retained. Exclude list changes throughout traversal and keep each
handle valid while using it. Do not pass a removed device as the
cursor or free a returned handle merely to end iteration.

btGetServiceValue()

Synopsis

LONG btGetServiceValue(
   APTR record, ULONG index, APTR buf, ULONG len)

Function

Read the current local value of a GATT characteristic.

Inputs

record - Live GATT service-record handle.
index - Zero-based index in the record's characteristic array.
buf - Destination buffer, or NULL to query the current length.
len - Available bytes in buf; zero performs no copy.

Result

Full current value length, which may exceed len. Returns -1 for a
NULL or non-GATT record or an invalid index. Copies at most len bytes
when buf is non-NULL; no terminator is appended.

Notes

Length and copied bytes are read under the GATT lock as one snapshot.
A separate length query and read can observe different values; size
the buffer or handle truncation accordingly. Values can change through
btSetServiceValue() or permitted remote writes. A disabled record and
a BGDP_STREAM characteristic can still be read locally.

Call from task context. Keep the record and bluetooth.library valid
and serialize with removal. The lock protects value access, not record
lifetime. The destination is caller-owned and is not retained.

btGetStringChunk()

Synopsis

STRPTR btGetStringChunk(
   APTR bic, ULONG chunkid)

Function

Copy the payload of the first matching plain chunk into a new
string buffer, adding a trailing NUL byte.

Inputs

bic - Live context; NULL is invalid.
chunkid - Chunk ID in host byte order.

Result

Allocated string, or NULL if the chunk is absent or allocation
fails. Release it with btFreeVec().

Notes

Copies the complete payload, including bytes after an embedded NUL.
An ordinary string consumer sees only the prefix before that NUL.
The copy is independent of the configuration tree. Keep the library
open until the buffer is freed. Call from task context.

btLoadCfgFromDisk()

Synopsis

BOOL btLoadCfgFromDisk(
   STRPTR filename)

Function

Read an IFF preference file into the global configuration and apply
it to the running stack.

Inputs

filename - NUL-terminated filename, or NULL to try
    ENV:Sys/bluetooth.prefs first and ENVARC:Sys/bluetooth.prefs
    only if the first attempt returns FALSE.

Result

TRUE if a matching root header and its declared payload were read.
FALSE for library, open, header, allocation or incomplete-read
failures. TRUE does not establish successful configuration parsing.

Notes

The root must use the current target's IFFFORM_BTCFG: BTBC on
big-endian systems, BTLC on little-endian systems. Payloads contain
native structures and are not converted between target formats.

Call from process context with DOS available. Applying the file can
remove hardware and release bindings. The filename is borrowed only
during the call. Successful file reading updates the saved-state
marker even when applying the configuration fails.

Bugs

The parser result is ignored; TRUE can describe a partially replaced
or rejected configuration. Such a result prevents the default-path
fallback. Declared lengths are not adequately validated before
allocation and parsing. Load only complete, trusted preference files.

btLockReadBase()

Synopsis

VOID btLockReadBase(
   )

Function

Acquire shared access to the Bluetooth library base. The calling task
may nest acquisitions.

Inputs

None.

Result

None. Return indicates that access has been acquired.

Notes

Call from task context. The call may wait indefinitely and uses
SIGB_SINGLE while waiting. Balance every acquisition with one
btUnlockBase() in the same task. A read acquisition made by the
exclusive owner increases its exclusive nesting count.

If a reader record cannot be allocated, the call acquires exclusive
access instead. Do not depend on another reader entering while this
lock is held. No reader/writer fairness guarantee is provided.

btLockReadDevice()

Synopsis

VOID btLockReadDevice(
   APTR bd)

Function

Acquire shared access to a Bluetooth device. The calling task
may nest acquisitions.

Inputs

bd - Live device object. NULL is invalid.

Result

None. Return indicates that access has been acquired.

Notes

Call from task context. The call may wait indefinitely and uses
SIGB_SINGLE while waiting. Balance every acquisition with one
btUnlockDevice() in the same task. A read acquisition made by the
exclusive owner increases its exclusive nesting count.

If a reader record cannot be allocated, the call acquires exclusive
access instead. Do not depend on another reader entering while this
lock is held. No reader/writer fairness guarantee is provided.
Keep the device alive until the matching unlock; acquiring a lock
does not validate an expired device pointer.

btLockWriteBase()

Synopsis

VOID btLockWriteBase(
   )

Function

Acquire exclusive access to the Bluetooth library base. Repeated
acquisitions by the owner increase the nesting count.

Inputs

None.

Result

None. Return indicates that exclusive access has been acquired.

Notes

Call from task context. The call may wait indefinitely and uses
SIGB_SINGLE while waiting. Balance every acquisition with one
btUnlockBase() in the same task.

An existing read lock can be promoted when this task is the only
reader. The read acquisition remains and needs its own unlock after
the exclusive acquisition is released. Do not attempt concurrent
read-to-write upgrades: waiting while retaining shared access can
deadlock with another upgrading reader.

btLockWriteDevice()

Synopsis

VOID btLockWriteDevice(
   APTR bd)

Function

Acquire exclusive access to a Bluetooth device. Repeated
acquisitions by the owner increase the nesting count.

Inputs

bd - Live device object. NULL is invalid.

Result

None. Return indicates that exclusive access has been acquired.

Notes

Call from task context. The call may wait indefinitely and uses
SIGB_SINGLE while waiting. Balance every acquisition with one
btUnlockDevice() in the same task.

An existing read lock can be promoted when this task is the only
reader. The read acquisition remains and needs its own unlock after
the exclusive acquisition is released. Do not attempt concurrent
read-to-write upgrades: waiting while retaining shared access can
deadlock with another upgrading reader.
Keep the device alive until the matching unlock; acquiring a lock
does not validate an expired device pointer.

btMatchStringChunk()

Synopsis

BOOL btMatchStringChunk(
   APTR bic, ULONG chunkid, CONST_STRPTR contents)

Function

Compare a string with the first matching plain chunk in a context.
Comparison is case-sensitive and bounded by the stored chunk length.

Inputs

bic - Live context; NULL is invalid.
chunkid - Chunk ID in host byte order.
contents - Non-NULL, NUL-terminated comparison string.

Result

TRUE if the strings match; FALSE for a missing chunk or a mismatch.

Notes

The comparison stops at the stored NUL or the end of the payload.
It also accepts an unterminated payload when its full byte sequence
matches the comparison string. No data is retained or allocated.
Call from task context.

btNextCfgForm()

Synopsis

APTR btNextCfgForm(
   APTR bic)

Function

Find the next sibling with the same FORM type as the supplied
context, skipping siblings of other types.

Inputs

bic - Live context in a context list, or NULL.

Result

Borrowed matching sibling, or NULL at the end of the list or for
a NULL input.

Notes

The context is borrowed, not a snapshot. Do not free it directly.
Prevent concurrent removal or replacement while using it; internal
locking does not extend its lifetime after this call returns.
Call from task context. Do not remove the current context before
using it to locate its successor.

btPairDeviceA()

Synopsis

BOOL btPairDeviceA(
   APTR bd, struct TagItem *taglist)

Function

Connect to a device if necessary and wait for pairing to finish.

Inputs

bd - Live device handle.
taglist - Pairing tag list, or NULL. See BUGS.

Result

TRUE when pairing reports success. FALSE for NULL, unavailable
hardware, an unsupported transport or role, pairing already in
progress, or connection or pairing failure. Detailed errors are not
returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

Prefers classic Bluetooth when both device and adapter support it;
otherwise uses LE. Initiated LE pairing requires the central role
and waits for any active service enumeration on that connection.

User interaction is reported through BEHMB_PAIRINGREQUEST and the
BDA_PairingRequest and BDA_PairingPasskey attributes. Arrange for
another task or the library's enabled pairing popup to answer with
btPairingReplyA(); the calling task remains blocked. Completion
updates BDA_PairingState and sends BEHMB_PAIRINGDONE.

Success marks the device bonded and registered and requests a
configuration save. It does not confirm that preferences reached
disk or that class binding completed. Failure does not roll back
connection establishment or all intermediate state.

Call from a task other than the adapter's hardware task. Keep the
device, adapter, library and tag list valid until return. The call
uses SIGF_SINGLE and has no caller timeout or cancellation parameter.
Do not hold locks needed by the hardware task.

Bugs

BPRA_Bond, BPRA_MITM, BPRA_IOCapability, BPRA_PINCode, BPRA_Passkey
and BPRA_Confirm are read but not used to configure this operation.
They cannot disable bonding, enforce MITM protection, select an I/O
capability or pre-answer a prompt. Supply responses separately with
btPairingReplyA(). Do not infer authentication strength from TRUE.

btPairingReplyA()

Synopsis

BOOL btPairingReplyA(
   APTR bd, struct TagItem *taglist)

Function

Answer a pending pairing prompt for a Bluetooth device.

Inputs

bd - Live device handle with a pending pairing prompt.
taglist - Response tags, or NULL. Supply the response explicitly;
    omission can accept some prompts and reject others.

Tags

BPRA_Confirm - BOOL response to consent or numeric comparison.
    A held incoming LE pairing request requires explicit TRUE.
    Other supported confirmation prompts default to acceptance
    when this tag is absent.
BPRA_Passkey - ULONG from 0 through 999999 for passkey entry.
    Zero is a valid passkey. Omitting the tag rejects the request.
BPRA_PINCode - NUL-terminated string for classic legacy PIN entry.
    NULL or an empty string rejects it; at most 16 bytes are used.
BPRA_Bond, BPRA_MITM, BPRA_IOCapability - Ignored by this operation.

Result

TRUE if a supported response was processed, including rejection or
an immediate pairing failure. FALSE for NULL, a missing hardware
task, no waiting pairing operation, or an unsupported prompt.
Detailed errors are not returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

Read BDA_PairingRequest before choosing response tags. For numeric
comparison, display BDA_PairingPasskey and obtain the user's decision.
A passkey-display prompt requires display on this host and entry on
the peer, not a passkey response. If both transports await input,
the classic connection is selected first.

Return does not wait for pairing completion. Observe
BEHMB_PAIRINGDONE or BDA_PairingState for the outcome. Controller
reply-submission failures and invalid passkey rejection are not
reliably reflected in the BOOL result.

Call from a task other than the adapter's hardware task and serialize
responders for the device. Keep the device, adapter, library, tag list
and PIN string valid until return; the input storage is not retained.
The call uses SIGF_SINGLE and waits for the hardware task without a
caller timeout. Do not hold locks that task needs.

btParseCfg()

Synopsis

VOID btParseCfg(
   )

Function

Apply the in-memory stack configuration to running hardware and
classes, restore registered devices and scan for class bindings.

Inputs

None.

Result

None. Individual hardware, class and binding failures are not
returned to the caller.

Notes

Call from task context; hardware changes and class initialization
can block. If STKC is absent, no hardware reconciliation occurs.
If STKC contains BHWD entries, remove radios that have no matching
online entry, then add and enumerate missing online radios. Without
any BHWD entries, retain existing radios. Legacy BCLS entries add
missing classes; omission from that list does not remove a class.

This call can disconnect devices and release bindings. On the first
process-context application after an earlier task-context load, it
performs AfterDOS class handling. Before DOS, the configured boot
delay can postpone return. It marks the resulting configuration as
read and updates its saved-state marker without writing a file.
Serialize configuration replacement with this operation.

Bugs

Opening a class while holding the configuration lock can deadlock
if its initialization waits for another task that needs that lock.

btReadCfg()

Synopsis

BOOL btReadCfg(
   APTR bic, APTR formdata)

Function

Replace the contents of an existing configuration FORM. Its type
and context remain; old child FORMs are freed and chunks replaced.

Inputs

bic - Context to replace, or NULL for the global root.
formdata - Serialized FORM, including its header and type. The type
    must match the destination context. The buffer is copied.

Result

TRUE if the input is consumed successfully. FALSE if the root is
absent, the header or type differs, allocation fails, or parsing
leaves unconsumed data.

Notes

Supply a complete, valid IFF buffer with consistent nested lengths
and a padding byte after each odd-length chunk. No buffer length
is passed to this API; malformed input is not safely rejected.
The buffer must not alias storage in the destination tree.

Call from task context. A type mismatch leaves the tree unchanged.
Once replacement starts, failure can leave partial contents; there
is no rollback. Earlier child-context and string references become
invalid. This call requests change detection but does not mount
hardware or save a file.

btRegisterDevice()

Synopsis

BOOL btRegisterDevice(
   APTR bd)

Function

Register a known Bluetooth device for persistent use and class binding.

Inputs

bd - Live device handle.

Result

TRUE after registration, including when already registered. FALSE
for NULL or a missing hardware task. Detailed errors are not
returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

A new registration clears the temporary reconnect hold, requests a
configuration save and sends BEHMB_DEVICEREGISTERED. An already
registered device is left unchanged. Pairing and connection are not
required and are not performed by this call.

Class scanning follows asynchronously when services are known.
Return confirms neither binding completion nor disk persistence;
configuration-allocation and save failures are not returned. Automatic
saving requires an initialized disk configuration and DOS support.
The device remains library-owned.

Call from a task other than the adapter's hardware task. Keep the
device, adapter and bluetooth.library valid until return and serialize
registration changes. The call uses SIGF_SINGLE and waits without a
caller timeout. Do not hold locks needed by the hardware task,
including configuration locks.

btReleaseAppBinding()

Synopsis

APTR btReleaseAppBinding(
   APTR bab)

Function

Release the device binding associated with an application-binding handle.

Inputs

bab - Live application-binding handle, or NULL for no operation.

Result

No defined return value. Ignore the public APTR result.

Notes

The release hook runs synchronously through btReleaseDevBinding().
It can run in a task other than the claimant and under the device
write lock. The library frees the binding after the hook returns.
Do not use or release the handle again, including after an external
removal has already invoked the hook.

Serialize release with claims and device removal. The function uses
the handle's device; it does not verify that the device still points
to this exact binding. Call from task context and preserve the
callback's code and data until completion.

Bugs

The public declaration returns APTR, but the implementation returns void.

btReleaseDevBinding()

Synopsis

VOID btReleaseDevBinding(
   APTR bd)

Function

Detach a device-level class or application binding and invoke its release callback.

Inputs

bd - Live device handle, or NULL for no operation.

Result

None. An unbound device requires no action; callback results are ignored.

Notes

Call from task context. The device binding pointer is cleared before
the callback. The device write lock is held throughout release.
For an application binding, CallHookPkt() receives the binding as
object and its user data as message; the library then frees it and
clears the application-binding flag. For a class binding, the class
receives BCM_ReleaseDeviceBinding and its usage count is decremented.

Callbacks must complete cleanup before returning. They must not
install a replacement binding or wait for another task that needs
the held lock. Serialize release with claims, scans and device
removal. This call does not release service-level bindings or remove
the device. A removal event refers to the device, not the released
binding.

btReleaseSvcBinding()

Synopsis

VOID btReleaseSvcBinding(
   APTR bsv)

Function

Detach a service-level class binding and invoke its release method.

Inputs

bsv - Live service handle, or NULL for no operation.

Result

None. An unbound service requires no action; the class method result is ignored.

Notes

Call from task context. The service binding pointer is cleared
before BCM_ReleaseServiceBinding is called. The owning device's
write lock is held throughout the callback; the class usage count
is then decremented. Keep the service, device and class valid until
release completes and serialize with scans and service replacement.

The callback must finish cleanup before returning and must not wait
for another task that needs the held device lock. Do not call from
a worker that the callback must stop. The service remains present,
but its old binding is no longer valid. BEHMB_REMBINDING identifies
the owning device; it does not carry the service handle.

btRemCfgChunk()

Synopsis

BOOL btRemCfgChunk(
   APTR bic, ULONG chnkid)

Function

Remove the first plain chunk with a matching ID. If the ID is zero,
clear all chunks and child FORMs while retaining the context itself.

Inputs

bic - Context to modify, or NULL for the global root.
chnkid - Chunk ID in host byte order; zero clears the contents.

Result

TRUE if a chunk or child FORM was removed; FALSE if nothing matched
or the global root is absent.

Notes

A nonzero ID does not remove child FORMs; use btRemCfgForm() for
those. Clearing the context invalidates all descendant references.
Chunk removal can invalidate borrowed strings within the context.
Call from task context. Change detection is requested.

Bugs

Removing a chunk before later chunks uses memcpy() on potentially
overlapping storage. The remaining data is not reliably preserved
on that path.

btRemCfgForm()

Synopsis

BOOL btRemCfgForm(
   APTR bic)

Function

Unlink and free a configuration FORM, all descendant FORMs and
their stored chunks.

Inputs

bic - Live context to remove, or NULL to remove the global root.
    If no global root exists, NULL has no effect.

Result

No usable result. Although the public declaration returns BOOL,
the implementation returns no value; do not test the result.

Notes

All references to the removed tree become invalid. Removing the
global root does not create a replacement root or stop running
hardware. Call from task context and prevent concurrent users from
accessing the context. Change detection is requested after removal.

btRemClass()

Synopsis

VOID btRemClass(
   APTR bc)

Function

Remove a class from binding selection, release its bindings and close its library.

Inputs

bc - Live registered class handle. NULL is invalid.

Result

None. Binding-release failures are not returned.

Notes

Call from task context. Quiesce scans, class callbacks and competing
class operations before removal. Release callbacks run synchronously
and can wait; do not call from a worker whose termination they await.
The class handle and copied metadata are invalid on return.

The removal event carries the freed handle as an identifier only.
Recipients must not dereference it. Removing a class does not remove
the Bluetooth devices or unload other registered classes.

Bugs

If the usage count remains nonzero after attempted release, the
function logs the condition but still closes the class library and
frees the class object. It does not refuse an unsafe unload; ensure
all bindings and in-flight class operations have ended first.

btRemErrorMsg()

Synopsis

VOID btRemErrorMsg(
   APTR bem)

Function

Unlink an error message, free its copied strings and storage, then
send BEHMB_REMERRORMSG.

Inputs

bem - Live message handle in this library's error list. NULL and
    previously removed handles are invalid.

Result

None.

Notes

The handle and its strings are invalid after removal. The removal
event carries the old address only as an identifier: recipients
must not dereference it. Earlier queued add events do not keep the
message alive. Serialize removal with message readers and other
removers. Call from task context.

btRemEventHandler()

Synopsis

VOID btRemEventHandler(
   APTR beh)

Function

Unregister an event hook, reply to every message currently queued
on its port and free the hook.

Inputs

beh - Live hook returned by btAddEventHandler(), or NULL for
    no operation.

Result

None.

Notes

Use a dedicated message port: queued messages are replied without
checking their type or which hook delivered them. The port itself
is not deleted. Keep it alive through this call. Messages already
removed from the port by a consumer are not reclaimed here; reply
to them before ending the consumer's use of the library.

Call from task context. Serialize removal with consumers and other
removers; the hook is invalid afterward. Unregister all hooks and
complete outstanding replies before closing bluetooth.library.

btRemHardware()

Synopsis

VOID btRemHardware(
   APTR bth)

Function

Release an adapter's devices, stop its hardware task and remove the adapter.

Inputs

bth - Live hardware handle. NULL is invalid.

Result

None. Shutdown or binding-release failures are not returned.

Notes

Stop discovery, connections and new I/O, complete outstanding requests
and release channels before removal. Quiesce all users of the adapter
and its devices. This call releases class and application bindings;
their callbacks run synchronously and may wait for workers.

Call from task context outside the hardware task and any worker that
a release callback must stop. Keep bluetooth.library open until return.
The call waits on SIGF_SINGLE for hardware-task termination and has
no bounded completion guarantee. Do not hold locks needed by workers
or release callbacks.

The adapter handle and all device, service and endpoint handles owned
by it become invalid. Removal events carry old pointers as identifiers;
they do not retain objects and must not be dereferenced. Saved adapter
and device configuration is not removed by this call.

Bugs

Binding release starts while the hardware task may still run. The
task is then stopped before dead-device cleanup, but outstanding
connection use is not protected by the shutdown sequence.
After repeated waits for device use counts, removal forcibly clears
a remaining count and continues. It does not safely refuse removal
while channels are in use; callers must establish quiescence first.

btRemServiceRecord()

Synopsis

VOID btRemServiceRecord(
   APTR record)

Function

Remove a local service record and discard its queued GATT value updates.

Inputs

record - Live service-record handle, or NULL for no operation.

Result

None. Class callback results are ignored.

Notes

Unlinks the record, removes its pending notification snapshots and
requests advertising and preferred-interval updates. Every registered
class receives BCM_ServiceRecordEvent synchronously before the record
and its copied metadata, characteristics and values are freed.
The callback runs under the base read lock and must not retain the
record or recursively remove it.

BEHMB_REMSERVICEREC carries the old handle without retaining the
record. An asynchronous recipient must treat it as an identifier,
not dereference it. Remote caches are not invalidated synchronously,
and previously transmitted updates are not recalled. GATT attribute
handles are not recycled during the library instance's lifetime.

Call from task context with bluetooth.library open. Quiesce all record
users, including value access and class operations, before removal.
Do not call twice. The base and GATT locks protect internal list work;
they do not validate a stale caller handle.

btSafeRawDoFmtA()

Synopsis

VOID btSafeRawDoFmtA(
   STRPTR buf, ULONG len, CONST_STRPTR fmtstr, RAWARG fmtdata)

Function

Format a RawDoFmt argument stream into a bounded buffer. Retain
at most len - 1 output bytes and terminate the result when len
is nonzero.

Inputs

buf - Writable buffer of at least len bytes.
len - Capacity including the terminating NUL; zero writes nothing
    and does not inspect the format or arguments.
fmtstr - NUL-terminated RawDoFmt format, not a printf format.
fmtdata - Argument stream in the target's RawDoFmt layout. It may
    be NULL only when the format consumes no arguments.

Result

None. Truncation and the required output length are not reported.

Notes

For nonzero len, the format and all referenced arguments must remain
valid throughout formatting. Filling the buffer does not stop
format processing or argument access. Do not overlap the output
with the format, argument stream or referenced strings. Inputs are
not retained. A one-byte buffer receives only a NUL.

btSaveCfgToDisk()

Synopsis

BOOL btSaveCfgToDisk(
   STRPTR filename, BOOL mode)

Function

Serialize the running configuration to a preference file. First
replace stored radio entries with the currently registered radios;
class configurations remain, but no loaded-class list is generated.

Inputs

filename - NUL-terminated filename, or NULL to attempt both
    ENVARC:Sys/bluetooth.prefs and ENV:Sys/bluetooth.prefs, in that
    order, even if the first attempt fails.
mode - Ignored. Only a data file is written.

Result

TRUE if serialization succeeds and the destination opens. For NULL,
both destinations must meet those conditions. FALSE otherwise.
Write and close failures are not reflected in this result.

Notes

Call from process context with DOS available. An existing file is
truncated when opened; no temporary-file replacement or rollback is
provided. The in-memory radio list is rewritten even if opening the
file later fails. The filename is not retained. A NULL-path success
also permits subsequent automatic registration and bond saves.
Files use the current target's IFFFORM_BTCFG and native payloads.

Bugs

A short write or close failure can leave a damaged file while the
function returns TRUE and marks the configuration saved. Failure
to rebuild every in-memory radio entry is also not reported.

btSendChannel()

Synopsis

VOID btSendChannel(
   APTR pp, APTR data, ULONG len)

Function

Submit a channel request and return without waiting for its reply.

Inputs

pp - Idle channel with no unconsumed previous reply.
data - Request buffer: writable for reads, readable for writes.
    Supply storage for len bytes when the request transfers data.
len - Read capacity or write length in bytes.

Result

None. Obtain completion status with btWaitChannel() or after receiving the reply.

Notes

Call from task context. The buffer is borrowed until completion;
do not modify a write buffer or inspect a read buffer while pending.
Keep the channel, endpoint, hardware, port and library valid. Submit
only one request at a time per channel. Submission clears Actual
and Error; neither zero value proves completion.

Completion replies the channel message to its allocation port, even
when submission immediately detects unavailable hardware. Consume
each reply once: use btWaitChannel(), or receive it with GetMsg()
and query the result. Do not call btWaitChannel() after GetMsg() has
removed that reply. Do not ReplyMsg() the returned channel message.

Endpoint reads consume one queued SDU or notification. An undersized
buffer receives a prefix with BTIOERR_OVERFLOW; the remainder is
discarded. Successful writes need not imply remote application
receipt. BCHA_NoWait does not bypass connection setup and is not
implemented for GATT notification reads.

Bugs

BCHA_Timeout is stored but not enforced by channel dispatch. Do not
rely on it to bound a pending request.

btSendEvent()

Synopsis

VOID btSendEvent(
   ULONG behmt, APTR param1, APTR param2)

Function

Queue a separate event note for each registered hook whose mask
selects the event. Reclaim previously replied notes first.

Inputs

behmt - Event number (BEHMB_*), not a BEHMF_* bit mask. Use a
    defined event number from libraries/bluetooth.h.
param1, param2 - Event-specific values copied into each note;
    pointed-to objects and data are not copied or retained.

Result

None. Allocation failure can omit delivery to any individual hook
without reporting an error; delivery is not all-or-nothing.

Notes

Call from task context; this can wait for the event-list semaphore
but does not wait for recipients. Keep referenced objects valid for
asynchronous use, or define them as identifiers only. Removal events
can carry already-invalid object addresses.

Recipients must ReplyMsg() each note exactly once and must not free
it themselves. ben_Data and ben_Device are NULL; ben_DataLength is
zero. This generic call does not construct the copied value payload
of a service-write notification.

btSetAttrsA()

Synopsis

LONG btSetAttrsA(
   ULONG type, APTR btstruct, struct TagItem *taglist)

Function

Set writable attributes of a Bluetooth object.

Inputs

type - BGA_* object type.
btstruct - Live object of that type. Ignored for BGA_STACK and
    BGA_STACKCFG, which use the library's current objects.
taglist - Assignment tags, or NULL. ti_Data contains the value;
    string and object values are pointers, not output addresses.

Tags

BGA_STACK:
    BSA_ConfigRead - Stored UWORD configuration-loaded flag.
    BSA_SavedConfigHash - Stored ULONG saved-configuration hash.
    BSA_LEAdvertising - Boolean LE advertising policy.
    BSA_EIRServices - Boolean classic service-advertising policy.
    BSA_LEConnInterval - Preferred peripheral connection interval
        in 1.25 ms units; 0 leaves selection to the central, and
        values above 1199 are limited to 1199.

BGA_HARDWARE:
    BHA_LocalName - NUL-terminated name; NULL requests an empty name.
    BHA_ClassOfDevice - ULONG class-of-device value.
    BHA_Discoverable, BHA_Connectable - Boolean classic scan modes.
        An omitted mode keeps its current flag value.

BGA_DEVICE:
    BDA_Name - Nonempty NUL-terminated custom name, copied. NULL,
        empty and identical names are counted without replacing it.
    BDA_InhibitPopup, BDA_InhibitClassBind, BDA_AutoConnect,
    BDA_Trusted - Stored UWORD policy fields; use zero or one.
    BDA_Binding, BDA_BindingClass - Direct binding pointers. No claim,
        release callback or usage-count adjustment is performed.

BGA_SERVICE:
    BSVA_Binding, BSVA_BindingClass - Direct binding pointers, with
        no binding lifecycle management.

BGA_CHANNEL:
    BCHA_Timeout - Stored ULONG timeout in milliseconds; setting it
        does not establish that a request path enforces the timeout.
    BCHA_AutoConnect, BCHA_NoWait - Boolean channel flags. Their
        effect depends on the request and transport.

BGA_APPBINDING:
    BABA_ReleaseHook, BABA_Device, BABA_Task - Borrowed pointers.
    BABA_UserData - IPTR callback data.
    BABA_ForceRelease - Stored UWORD flag. Assigning it does not
        release anything. Use btClaimAppBindingA() to make a claim.

BGA_STACKCFG:
    BGCA_LogInfo, BGCA_LogWarning, BGCA_LogError, BGCA_LogFailure,
    BGCA_PopupDeviceNew, BGCA_PopupDeviceGone, BGCA_PopupPairing,
    BGCA_PopupActivateWin, BGCA_PopupWinToFront, BGCA_Discoverable,
    BGCA_Connectable, BGCA_AutoConnect - UWORD flags; use zero or one.
    BGCA_SubTaskPri - Signed WORD priority for subsequently spawned
        subtasks; values are not validated against scheduler limits.
    BGCA_BootDelay - ULONG delay in seconds used during stack startup.
    BGCA_PopupCloseDelay - ULONG popup close-delay setting.
    BGCA_DiscoveryTime - ULONG default discovery duration in seconds.
    BGCA_LocalName - Copied into the 64-byte global name buffer;
        supply at most 63 bytes plus NUL. NULL clears the name.

BGA_SERVICERECORD:
    BSRA_Enabled - Boolean local service availability. Updates the
        relevant advertising sequence and, for GATT, interval policy.

BGA_BTCLASS, BGA_ENDPOINT, BGA_ERRORMSG and BGA_EVENTNOTE have no
writable attributes. Other tags, including read-only fields and
creation-only service-record tags, are ignored.

Result

Number of recognized assignments, or -1 for an unsupported type.
Zero means no writable tag was handled. Only the first occurrence of
each recognized tag is used. The count does not confirm allocation,
controller-command success, persistence or completion of side effects.

Notes

Assignments are not transactional or processed in tag-list order.
Manual handlers run before table assignments. Numeric table values
are narrowed to their stored field width without range checks.
Pointer fields are assigned directly, without copying or retaining
objects; only the documented string setters copy their input.

Coordinate object lifetime and concurrent writers. No general object
lock is taken. Change channel attributes only while the channel is
idle. Direct binding setters are for code that already owns the
binding protocol; use claim/release APIs for normal binding changes.

Hardware assignments wait for the hardware task using SIGF_SINGLE;
call from another task without locks that worker needs. No caller
timeout is provided. Device and global configuration updates can
also acquire configuration locks. Keep all input pointers and the
library valid until return.

Device name/policy changes update in-memory configuration, without a
disk save. STACKCFG updates its configuration chunk and checks for
changes even with an empty tag list. Applying global defaults does
not synchronously reconfigure every adapter. Advertising and interval
changes are consumed later; no negotiated radio setting is promised.

Bugs

Hardware command errors are discarded although their tags are counted.
Device-name replacement frees the old name before allocating its copy;
failure loses the old value. A replacement must not alias that storage.
BGCA_LocalName copies at most 63 bytes without explicitly writing the
last byte of the buffer. A short terminated input avoids depending on
that byte's prior contents; truncation is not reported.

btSetClsCfg()

Synopsis

BOOL btSetClsCfg(
   STRPTR owner, APTR form)

Function

Store private class configuration under the specified owner.
Replace existing class-data contents, or create a class entry.

Inputs

owner - Non-NULL, NUL-terminated class owner name. Case-sensitive.
form - Complete IFFFORM_BTCLASSDATA (GCPD) FORM, or NULL to store
    empty class data.

Result

TRUE if the requested update is accepted; FALSE on failure.

Notes

For a non-NULL form, supply a complete, valid IFF buffer with consistent nested lengths
and a padding byte after each odd-length chunk. No buffer length
is passed to this API; malformed input is not safely rejected.
The buffer must not alias storage in the destination tree.

Owner and FORM data are copied. NULL clears data rather than removing
the owner entry. Updates are not transactional: a failed replacement
can leave partial data and fall back to creating another owner
entry. Call from task context. Change detection runs before return;
no preference file is written.

btSetDevCfg()

Synopsis

BOOL btSetDevCfg(
   STRPTR owner, STRPTR devid, STRPTR svcid, APTR form)

Function

Store owner-specific configuration for a device or one of its
services, creating missing containers as needed.

Inputs

owner - Non-NULL, NUL-terminated class owner name.
devid - Non-NULL, NUL-terminated device ID.
svcid - Service ID, or NULL for device-wide configuration.
form - Complete DCPD FORM for device-wide data or SCPD FORM for
    service data; NULL stores empty data. Names and IDs are
    case-sensitive.

Result

TRUE if the selected data was replaced or cleared; FALSE on failure.

Notes

For a non-NULL form, supply a complete, valid IFF buffer with consistent nested lengths
and a padding byte after each odd-length chunk. No buffer length
is passed to this API; malformed input is not safely rejected.
The buffer must not alias storage in the destination tree.

Strings and FORM data are copied. NULL clears the data, retaining
its containers. Failures can leave partial containers or duplicate
device entries; prior data is not restored. Call from task context.
Change detection runs before return. This does not bind a class or
write a preference file.

btSetForcedBinding()

Synopsis

BOOL btSetForcedBinding(
   STRPTR owner, STRPTR devid, STRPTR svcid)

Function

Set or clear the preferred class owner recorded for a device or
service. This changes configuration, not an active binding.

Inputs

owner - Class owner name; NULL or an empty string clears the choice.
devid - Non-NULL, NUL-terminated device ID.
svcid - Service ID, or NULL for a device-wide choice.
    Non-NULL strings must be terminated; matching is case-sensitive.

Result

TRUE if a choice was stored, or for clearing even if none existed.
FALSE if storing a choice fails.

Notes

Strings are copied. For a service, all matching service containers
under the first matching device are visited. A successful update
of one container can mask a failure in another. Creation failures
can leave partial containers or duplicate device entries.

Call from task context. Change detection runs before return; no
file is saved and no class is immediately rebound.

btSetServiceValue()

Synopsis

LONG btSetServiceValue(
   APTR record, ULONG index, APTR data, ULONG len)

Function

Replace a local GATT characteristic value and queue updates for subscribers.

Inputs

record - Live GATT service-record handle.
index - Zero-based index in the record's characteristic array.
data - Buffer containing len bytes; may be NULL when len is zero.
len - New byte length, no greater than the characteristic's capacity.

Result

Number of bytes stored, including zero. Returns -1 for NULL or a
non-GATT record, an invalid index, missing nonempty data, excessive
length, notification allocation failure or a full notification queue.
On these failures the current value remains unchanged.

Notes

The value is copied and its length replaced; unused capacity is not
part of the value. The call may update a disabled record and does not
require BGDP_WRITE, which controls access from remote devices.

For BGDP_NOTIFY or BGDP_INDICATE, an update snapshot is allocated
before checking subscribers. With subscribers, it is appended to the
shared queue, limited to 256 outstanding snapshots across all records.
Without subscribers, the snapshot is discarded. Even without subscribers,
its initial allocation can fail. Successful updates wake radio tasks.

Return confirms the local update, not transmission or acknowledgement.
Each notification or indication carries at most the negotiated ATT
MTU minus three bytes, also bounded by the sender's packet buffer;
longer values are truncated for that update, not split into messages.
Updates may be skipped when the record is disabled, a subscription
ends, a link fails, or indication handling stops. Remote reads of a
BGDP_STREAM value remain empty; btGetServiceValue() returns its stored
local bytes.

Call from task context. Keep the record and bluetooth.library valid,
serialize with record removal, and keep data unchanged until return.
The GATT lock serializes value access; it does not retain the record.
No ownership of the input buffer is transferred.

btSpawnSubTask()

Synopsis

struct Task * btSpawnSubTask(
   STRPTR name, APTR initpc, APTR userdata)

Function

Start a worker using the configured Bluetooth subtask priority and
AROS_STACKSIZE. Create a DOS process when dos.library can be opened;
otherwise create an Exec task.

Inputs

name - Non-NULL, NUL-terminated task name; copied during creation.
initpc - Non-NULL entry point compatible with both possible startup
    environments. It receives no ordinary C argument from this call.
userdata - Borrowed pointer installed in the worker's tc_UserData.
    The worker can retrieve it through FindTask(NULL).

Result

Task pointer, or NULL if required arguments are NULL or creation
fails. The result can point to a Process. It is not an initialization
completion notification or a lifetime reference.

Notes

Call from task context. The worker may run or exit before the caller
resumes. Establish an explicit startup and shutdown handshake before
using the returned pointer. Keep userdata and entry code alive until
the worker finishes; neither is copied or freed by this function.
A DOS process does not copy the caller's local variables (NP_CopyVars
is FALSE). An Exec task must not assume a DOS process environment.
The caller must keep libraries used by the worker open.

btStartDiscoveryA()

Synopsis

BOOL btStartDiscoveryA(
   APTR bth, struct TagItem *taglist)

Function

Start device discovery on a Bluetooth adapter.

Inputs

bth - Live hardware handle.
taglist - Discovery options, or NULL for defaults.

Tags

BDSA_Duration - ULONG duration in seconds. Defaults to
    BGCA_DiscoveryTime; zero selects 10 seconds. Values above 60
    are limited to 60. Name resolution can extend the operation.
BDSA_Classic - Enable classic inquiry; TRUE by default.
BDSA_LE - Enable LE active scanning; TRUE by default.
BDSA_ResolveNames - Resolve missing names of discovered classic
    devices after inquiry; TRUE by default.
BDSA_ClearOld - FALSE by default. TRUE removes unregistered devices
    that are neither connected nor connecting, have no device or
    service binding, and have no outstanding device use count.

Result

TRUE if discovery was accepted. FALSE for NULL hardware, a missing
hardware task, an adapter that is not ready, discovery already in
progress, or no requested discovery mode supported by the adapter.
Detailed errors are not returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

Unsupported modes are ignored when another requested mode is
available. Discovery clears the discovered flag on retained devices.
ClearOld invalidates handles to removed devices and their services
and endpoints; a raw pointer alone does not prevent removal.

Return does not wait for radio discovery or name resolution.
BEHMB_DISCOVERYSTART and BEHMB_DISCOVERYSTOP identify the adapter.
Controller command failures are not reflected in the return value;
TRUE does not guarantee that the radio started or found a device.

Call from a task other than the adapter's hardware task. Keep the
adapter and bluetooth.library valid during the call. The call uses
SIGF_SINGLE and waits for the hardware task without a caller timeout;
do not hold locks that task needs. The tag list is not retained.

btStopDiscovery()

Synopsis

BOOL btStopDiscovery(
   APTR bth)

Function

Request termination of device discovery on an adapter.

Inputs

bth - Live hardware handle.

Result

TRUE if the stop request was processed, including when discovery
was already inactive. FALSE for NULL hardware or a missing hardware
task. Detailed errors are not returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

Cancels pending discovery and queued name lookups. An outstanding
name lookup may delay BEHMB_DISCOVERYSTOP. The call does not wait
for controller cancellation commands to complete, and their failure
is not returned. Existing discovery results remain available.
Background scanning may resume; this call does not disable the radio.

Call from a task other than the adapter's hardware task. Keep the
adapter and bluetooth.library valid during the call. It uses
SIGF_SINGLE and waits for the hardware task without a caller timeout.
Do not hold locks that task needs.

btUnbindAll()

Synopsis

VOID btUnbindAll(
   )

Function

Release device and service bindings across the active hardware device lists.

Inputs

None.

Result

None. Callback failures are not reported.

Notes

Application bindings are included, so their release hooks may run.
The traversal drops the base lock for each release and restarts
afterward. This is not an atomic snapshot or a permanent binding
inhibit. Stop competing claims and scans if all devices must remain
unbound when the call returns.

Call from task context outside workers that release callbacks must
stop. Keep devices and services valid across each release. Callbacks
run synchronously under the owning device's write lock and may wait
without a timeout. Continuous rebinding can prevent termination.
Classes remain registered, devices remain present, and forced-binding
configuration is unchanged. Devices outside the active lists are
not visited.

btUnlockBase()

Synopsis

VOID btUnlockBase(
   )

Function

Release one lock acquisition held by the calling task on the Bluetooth library base.

Inputs

None.

Result

None. Ownership errors are logged, not returned.

Notes

Release exclusive acquisitions before any underlying shared
acquisitions. The last acquisition of a mode releases that mode and
wakes waiting tasks; it does not guarantee which waiter proceeds.
An unlock by a non-owner or without an acquisition leaves the lock
unchanged and can add diagnostic messages. Do not use this call
as an ownership test. Call from task context.

btUnlockDevice()

Synopsis

VOID btUnlockDevice(
   APTR bd)

Function

Release one lock acquisition held by the calling task on a Bluetooth device.

Inputs

bd - Live device object. NULL is invalid.

Result

None. Ownership errors are logged, not returned.

Notes

Release exclusive acquisitions before any underlying shared
acquisitions. The last acquisition of a mode releases that mode and
wakes waiting tasks; it does not guarantee which waiter proceeds.
An unlock by a non-owner or without an acquisition leaves the lock
unchanged and can add diagnostic messages. Do not use this call
as an ownership test. Call from task context.

btUnpairDevice()

Synopsis

BOOL btUnpairDevice(
   APTR bd)

Function

Remove locally stored pairing keys and request device disconnection.

Inputs

bd - Live device handle.

Result

TRUE after the local key state is cleared and disconnection is
requested. FALSE for NULL or a missing hardware task. Detailed
errors are not returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

Clears the bonded flag and cached current address and requests a
configuration save. Registration is retained. Both transports are
disconnected or their connection attempts cancelled without waiting
for controller completion. TRUE confirms neither disk persistence
nor removal of keys stored by the remote device.

Serialize with pairing and other registration or key changes; this
call does not make those operations an atomic transaction. Call from
a task other than the adapter's hardware task. Keep the device,
adapter and bluetooth.library valid until return. The call uses
SIGF_SINGLE and waits without a caller timeout. Do not hold locks
needed by the hardware task, including configuration locks.

btUnregisterDevice()

Synopsis

BOOL btUnregisterDevice(
   APTR bd)

Function

Remove a device registration and its locally stored pairing keys.

Inputs

bd - Live device handle.

Result

TRUE after processing, including when already unregistered. FALSE
for NULL or a missing hardware task. Detailed errors are not
returned through IoErr().
Hardware shutdown also returns FALSE.

Notes

For a registered device, clears registration, bonding, keys and the
cached current address, requests a configuration save and sends
BEHMB_DEVICEUNREGISTERED. An already unregistered device is left
unchanged, including any key state it still has.

Binding release is delegated to the event handler and may occur after
return. Event allocation can fail independently. The call does not
itself disconnect or free the device. Return does not confirm binding
release, disk persistence or deletion of keys on the remote device.
Quiesce users of bindings before unregistering; their handles become
invalid when release callbacks run.

Call from a task other than the adapter's hardware task. Keep the
device, adapter and bluetooth.library valid and serialize registration
and pairing changes. The call uses SIGF_SINGLE and waits without a
caller timeout. Do not hold locks needed by the hardware task,
including configuration locks.

btWaitChannel()

Synopsis

LONG btWaitChannel(
   APTR pp)

Function

Wait until a channel is no longer pending and remove its queued reply.

Inputs

pp - Live channel whose reply has not been removed by GetMsg()
    or another waiter.

Result

Zero on success, or the stored IOERR_* or BTIOERR_* completion code.

Notes

Call from the task signaled by the reply port. The call waits on
that port's signal and leaves other queued messages in place.
Signals observed while waiting are restored for other port users.
It neither frees the channel nor releases the caller's buffer.

No overall timeout or break-signal cancellation is provided. Do not
call from the hardware task or while holding a lock it needs.
For a newly allocated channel this returns its initial zero status
without submitting anything. A nonpending channel returns its
stored status; that is not evidence of a new operation.

Bugs

Every call updates the device's reachability history from the stored
error, including repeated calls after completion. Wait once per
submitted request; use btGetChannelError() for later inspection.

btWriteCfg()

Synopsis

APTR btWriteCfg(
   APTR bic)

Function

Serialize a configuration FORM and its descendants. Plain chunks
precede child FORMs in the output. For the global root, refresh the
stored global settings from the running stack first.

Inputs

bic - Live context, or NULL for the global root.

Result

Newly allocated FORM buffer, or NULL if the root is absent or the
buffer cannot be allocated. Release the buffer with btFreeVec().

Notes

The buffer includes the eight-byte IFF header; decode its big-endian
length and add eight to obtain the total byte count. It remains
independent of later tree changes. Chunk payloads can contain native
structures: the root uses IFFFORM_BTCFG for the current byte order,
not a portable interchange format. Keep bluetooth.library open
until the buffer is freed. Call from task context.

Serialize this call with other configuration access. Root export
can replace the stored global-settings chunk. An allocation failure
during that refresh is not reported separately; a non-NULL result
does not guarantee that every global setting was refreshed.

Docutils System Messages

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 396); backlink

Unknown target name: "btremfirmwareloader()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 462); backlink

Unknown target name: "btenumeratehardware()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 2387); backlink

Unknown target name: "unpackstructuretags()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 3440); backlink

Unknown target name: "btaddeventhandler()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 4103); backlink

Unknown target name: "btaddeventhandler()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 4499); backlink

Unknown target name: "btaddeventhandler()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 4651); backlink

Unknown target name: "packstructuretags()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 5047); backlink

Unknown target name: "btaddeventhandler()".

System Message: ERROR/3 (/home/vsts/work/1/b/documentation/html/documentation/developers/autodocs/bluetooth.en.rst, line 5106); backlink

Unknown target name: "btaddeventhandler()".