Class BaseBluetoothRemoteCharacteristic
Interface representing a Bluetooth characteristic, providing properties and methods for interacting with it.
public abstract class BaseBluetoothRemoteCharacteristic : BaseBindableObject, IBluetoothRemoteCharacteristic, INotifyPropertyChanged, IAsyncDisposable
- Inheritance
-
BaseBluetoothRemoteCharacteristic
- Implements
- Derived
- Inherited Members
Constructors
BaseBluetoothRemoteCharacteristic(IBluetoothRemoteService, BluetoothRemoteCharacteristicFactorySpec, IBluetoothRemoteDescriptorFactory, IBluetoothNameProvider?, ILogger<IBluetoothRemoteCharacteristic>?)
Initializes a new instance using a factory spec.
protected BaseBluetoothRemoteCharacteristic(IBluetoothRemoteService parentService, IBluetoothRemoteCharacteristicFactory.BluetoothRemoteCharacteristicFactorySpec spec, IBluetoothRemoteDescriptorFactory descriptorFactory, IBluetoothNameProvider? nameProvider = null, ILogger<IBluetoothRemoteCharacteristic>? logger = null)
Parameters
parentServiceIBluetoothRemoteServiceThe Bluetooth service associated with this characteristic.
specIBluetoothRemoteCharacteristicFactory.BluetoothRemoteCharacteristicFactorySpecThe factory spec containing characteristic information.
descriptorFactoryIBluetoothRemoteDescriptorFactoryThe factory for creating Bluetooth remote descriptors.
nameProviderIBluetoothNameProviderAn optional provider for characteristic names, used to resolve the name based on the ID.
loggerILogger<IBluetoothRemoteCharacteristic>The logger instance to use for logging (optional).
BaseBluetoothRemoteCharacteristic(IBluetoothRemoteService, Guid, IBluetoothNameProvider?, ILogger<IBluetoothRemoteCharacteristic>?)
Initializes a new instance of the BaseBluetoothRemoteCharacteristic class.
protected BaseBluetoothRemoteCharacteristic(IBluetoothRemoteService parentService, Guid id, IBluetoothNameProvider? nameProvider = null, ILogger<IBluetoothRemoteCharacteristic>? logger = null)
Parameters
parentServiceIBluetoothRemoteServiceThe Bluetooth service associated with this characteristic.
idGuidThe unique identifier for the characteristic.
nameProviderIBluetoothNameProviderAn optional provider for characteristic names, used to resolve the name based on the ID.
loggerILogger<IBluetoothRemoteCharacteristic>The logger instance to use for logging (optional).
Exceptions
- ArgumentNullException
Thrown when
parentServiceis null.
Properties
CanListen
Gets a value indicating whether the characteristic supports notifications.
public bool CanListen { get; }
Property Value
CanRead
Gets a value indicating whether the characteristic can be read.
public bool CanRead { get; }
Property Value
CanWrite
Gets a value indicating whether the characteristic can be written to.
public bool CanWrite { get; }
Property Value
DescriptorFactory
Gets the factory for creating Bluetooth remote descriptors.
protected IBluetoothRemoteDescriptorFactory? DescriptorFactory { get; }
Property Value
Id
Gets the universally unique identifier (UUID) of the characteristic.
public Guid Id { get; }
Property Value
IsExploringDescriptors
Gets a value indicating whether a descriptor exploration operation is currently in progress.
public bool IsExploringDescriptors { get; }
Property Value
IsListening
Gets a value indicating whether the characteristic is currently listening for notifications.
public bool IsListening { get; protected set; }
Property Value
IsReading
Gets a value indicating whether a read value operation is currently in progress. This flag helps prevent concurrent read operations and tracks the operation state.
public bool IsReading { get; }
Property Value
IsReadingIsListening
Gets or sets a value indicating whether a read listening operation is currently in progress. This flag helps prevent concurrent read operations and tracks the operation state.
public bool IsReadingIsListening { get; }
Property Value
IsWriting
Gets a value indicating whether a write value operation is currently in progress. This flag helps prevent concurrent write operations and tracks the operation state.
public bool IsWriting { get; }
Property Value
IsWritingIsListening
Gets or sets a value indicating whether a write listening operation is currently in progress. This flag helps prevent concurrent write operations and tracks the operation state.
public bool IsWritingIsListening { get; }
Property Value
Name
The name of the Bluetooth characteristic. This is typically used for debugging and logging purposes, and may not be available for all characteristics. If the characteristic is not recognized, this will default to "Unknown Characteristic".
public string Name { get; }
Property Value
Service
Gets the Bluetooth service associated with this characteristic.
public IBluetoothRemoteService Service { get; }
Property Value
Value
Gets the value of the characteristic as a read-only memory segment. Useful for asynchronous operations.
public ReadOnlyMemory<byte> Value { get; }
Property Value
ValueSpan
Gets the value of the characteristic as a read-only span. Useful for high-performance scenarios.
public ReadOnlySpan<byte> ValueSpan { get; }
Property Value
Methods
AbortReliableWriteAsync(TimeSpan?, CancellationToken)
Aborts the current reliable write transaction and discards all queued writes.
public ValueTask AbortReliableWriteAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
timeoutTimeSpan?The timeout for this operation.
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask
A task that represents the asynchronous operation.
Exceptions
- InvalidOperationException
Thrown when no reliable write transaction is in progress.
- TimeoutException
Thrown when the operation times out.
- OperationCanceledException
Thrown when the operation is cancelled.
BeginReliableWriteAsync(TimeSpan?, CancellationToken)
Begins a reliable write transaction. Reliable write allows you to queue multiple writes and execute them atomically.
public ValueTask BeginReliableWriteAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
timeoutTimeSpan?The timeout for this operation.
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask
A task that represents the asynchronous operation.
Exceptions
- InvalidOperationException
Thrown when a reliable write transaction is already in progress.
- TimeoutException
Thrown when the operation times out.
- OperationCanceledException
Thrown when the operation is cancelled.
ClearDescriptorsAsync()
Resets the list of descriptors, and stops all subscriptions and notifications.
public ValueTask ClearDescriptorsAsync()
Returns
DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
public ValueTask DisposeAsync()
Returns
- ValueTask
A task that represents the asynchronous dispose operation.
DisposeAsyncCore()
Performs the core disposal logic for the characteristic, including stopping listening and cleaning up resources. This method is called during disposal to ensure proper cleanup of the characteristic's resources.
protected virtual ValueTask DisposeAsyncCore()
Returns
- ValueTask
A task that represents the asynchronous disposal operation.
Remarks
This method will attempt to stop listening if the characteristic is currently listening for notifications.
A DeviceNotConnectedException is treated as an expected disposal race (device disconnected
between the connectivity check and the stop request) and is silently discarded. Any other exception during
the stop listening process is forwarded to the unhandled exception listener. IsListening
is always cleared in a finally block so the object reflects reality regardless of outcome.
ExecuteReliableWriteAsync(TimeSpan?, CancellationToken)
Executes all writes queued in the current reliable write transaction.
public ValueTask ExecuteReliableWriteAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
timeoutTimeSpan?The timeout for this operation.
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask
A task that represents the asynchronous operation.
Exceptions
- InvalidOperationException
Thrown when no reliable write transaction is in progress.
- TimeoutException
Thrown when the operation times out.
- OperationCanceledException
Thrown when the operation is cancelled.
ExploreDescriptorsAsync(DescriptorExplorationOptions?, TimeSpan?, CancellationToken)
Explores (discovers) the descriptors of this characteristic asynchronously.
public Task ExploreDescriptorsAsync(DescriptorExplorationOptions? options = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
optionsDescriptorExplorationOptionsOptional exploration configuration. If null, uses default options (with caching enabled). Set
UseCache = falseto force re-exploration even if descriptors were previously discovered. UseDescriptorUuidFilterto discover only specific descriptors by UUID.timeoutTimeSpan?The timeout for this operation.
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- Task
A task that represents the asynchronous operation.
Remarks
Common Usage Patterns:
// Simple exploration (uses defaults: all descriptors, with caching):
await characteristic.ExploreDescriptorsAsync();
// Force re-exploration (ignore cache): await characteristic.ExploreDescriptorsAsync(new() { UseCache = false });
// Filter by descriptor UUID (e.g., Client Characteristic Configuration):
await characteristic.ExploreDescriptorsAsync(new DescriptorExplorationOptions
{
DescriptorUuidFilter = uuid => uuid == BluetoothUuids.ClientCharacteristicConfiguration
});
Caching Behavior:
By default (options = null), caching is enabled (UseCache = true).
This means if descriptors have already been explored, the method returns immediately
without re-querying the device. To force re-exploration, explicitly set UseCache = false.
GetDescriptor(Func<IBluetoothRemoteDescriptor, bool>)
Gets the descriptor that matches the specified filter.
public IBluetoothRemoteDescriptor GetDescriptor(Func<IBluetoothRemoteDescriptor, bool> filter)
Parameters
filterFunc<IBluetoothRemoteDescriptor, bool>The filter to apply to the descriptors.
Returns
- IBluetoothRemoteDescriptor
The descriptor that matches the filter.
Exceptions
- DescriptorNotFoundException
Thrown when no descriptor matches the specified filter.
- MultipleDescriptorsFoundException
Thrown when multiple descriptors match the specified filter.
GetDescriptor(Guid)
Gets a descriptor by its ID.
public IBluetoothRemoteDescriptor GetDescriptor(Guid id)
Parameters
idGuidThe ID of the descriptor to get.
Returns
- IBluetoothRemoteDescriptor
The descriptor with the specified ID.
Exceptions
- DescriptorNotFoundException
Thrown when no descriptor with the specified ID is found.
- MultipleDescriptorsFoundException
Thrown when multiple descriptors with the specified ID are found.
GetDescriptorOrDefault(Func<IBluetoothRemoteDescriptor, bool>)
Gets the descriptor that matches the specified filter.
public IBluetoothRemoteDescriptor? GetDescriptorOrDefault(Func<IBluetoothRemoteDescriptor, bool> filter)
Parameters
filterFunc<IBluetoothRemoteDescriptor, bool>The filter to apply to the descriptors.
Returns
- IBluetoothRemoteDescriptor
The descriptor that matches the filter, or null if not found.
Exceptions
- MultipleDescriptorsFoundException
Thrown if multiple descriptors match the specified filter.
GetDescriptorOrDefault(Guid)
Gets a descriptor by its ID.
public IBluetoothRemoteDescriptor? GetDescriptorOrDefault(Guid id)
Parameters
idGuidThe ID of the descriptor to get.
Returns
- IBluetoothRemoteDescriptor
The descriptor with the specified ID, or null if not found.
Exceptions
- MultipleDescriptorsFoundException
Thrown if multiple descriptors match the specified ID.
GetDescriptors(Func<IBluetoothRemoteDescriptor, bool>?)
Gets the descriptors that match the specified filter. 0-N
public IEnumerable<IBluetoothRemoteDescriptor> GetDescriptors(Func<IBluetoothRemoteDescriptor, bool>? filter = null)
Parameters
filterFunc<IBluetoothRemoteDescriptor, bool>The filter to apply to the descriptors.
Returns
- IEnumerable<IBluetoothRemoteDescriptor>
The descriptors that match the filter, or all descriptors if the filter is null.
HasDescriptor(Func<IBluetoothRemoteDescriptor, bool>)
Gets a value indicating whether this characteristic has a descriptor that matches the specified filter.
public bool HasDescriptor(Func<IBluetoothRemoteDescriptor, bool> filter)
Parameters
filterFunc<IBluetoothRemoteDescriptor, bool>The filter to apply to the descriptors.
Returns
- bool
True if a matching descriptor is found; otherwise, false.
HasDescriptor(Guid)
Gets a value indicating whether this characteristic has a descriptor with the specified ID.
public bool HasDescriptor(Guid id)
Parameters
idGuidThe ID of the descriptor to check for.
Returns
- bool
True if a descriptor with the specified ID is found; otherwise, false.
NativeAbortReliableWriteAsync()
Platform-specific implementation to abort a reliable write transaction.
protected abstract ValueTask NativeAbortReliableWriteAsync()
Returns
NativeBeginReliableWriteAsync()
Platform-specific implementation to begin a reliable write transaction.
protected abstract ValueTask NativeBeginReliableWriteAsync()
Returns
NativeCanListen()
Platform-specific implementation to determine if the characteristic can listen for notifications.
protected abstract bool NativeCanListen()
Returns
- bool
True if the characteristic supports listening for notifications; otherwise, false.
NativeCanRead()
Platform-specific implementation to determine if the characteristic can be read. This method should check the platform-specific properties to determine read capability.
protected abstract bool NativeCanRead()
Returns
- bool
True if the characteristic supports read operations; otherwise, false.
NativeCanWrite()
Platform-specific implementation to determine if the characteristic can be written to. This method should check the platform-specific properties to determine write capability.
protected abstract bool NativeCanWrite()
Returns
- bool
True if the characteristic supports write operations; otherwise, false.
NativeDescriptorsExplorationAsync(TimeSpan?, CancellationToken)
Platform-specific implementation to explore (discover) descriptors.
protected abstract ValueTask NativeDescriptorsExplorationAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
timeoutTimeSpan?cancellationTokenCancellationToken
Returns
NativeExecuteReliableWriteAsync()
Platform-specific implementation to execute a reliable write transaction.
protected abstract ValueTask NativeExecuteReliableWriteAsync()
Returns
NativeReadIsListeningAsync()
Platform-specific implementation to read the current listening state of the characteristic. This method should initiate the platform-specific operation to query whether notifications/indications are enabled.
protected abstract ValueTask NativeReadIsListeningAsync()
Returns
- ValueTask
A task that completes when the native read operation is initiated.
Remarks
Implementations should call OnReadIsListeningSucceeded(bool) when the operation succeeds or OnReadIsListeningFailed(Exception) when it fails.
NativeReadValueAsync()
Platform-specific implementation to read the characteristic's value. This method should initiate the platform-specific operation to read the characteristic value.
protected abstract ValueTask NativeReadValueAsync()
Returns
- ValueTask
A task that completes when the native read operation is initiated.
Remarks
Implementations should call OnReadValueSucceeded(ReadOnlyMemory<byte>) when the operation succeeds or OnReadValueFailed(Exception) when it fails.
NativeWriteIsListeningAsync(bool)
Platform-specific implementation to write (set) the listening state of the characteristic. This method should initiate the platform-specific operation to enable or disable notifications/indications.
protected abstract ValueTask NativeWriteIsListeningAsync(bool shouldBeListening)
Parameters
shouldBeListeningboolTrue to enable notifications/indications, false to disable them.
Returns
- ValueTask
A task that completes when the native write operation is initiated.
Remarks
Implementations should call OnWriteIsListeningSucceeded() when the operation succeeds or OnWriteIsListeningFailed(Exception) when it fails.
NativeWriteValueAsync(ReadOnlyMemory<byte>)
Platform-specific implementation to write the characteristic's value. This method should initiate the platform-specific operation to write the value to the characteristic.
protected abstract ValueTask NativeWriteValueAsync(ReadOnlyMemory<byte> value)
Parameters
valueReadOnlyMemory<byte>The value to write to the characteristic.
Returns
- ValueTask
A task that completes when the native write operation is initiated.
Remarks
Implementations should call OnWriteValueSucceeded() when the operation succeeds or OnWriteValueFailed(Exception) when it fails.
OnAbortReliableWriteFailed(Exception)
Called when abort reliable write fails.
protected void OnAbortReliableWriteFailed(Exception e)
Parameters
OnAbortReliableWriteSucceeded()
Called when abort reliable write succeeds.
protected void OnAbortReliableWriteSucceeded()
OnBeginReliableWriteFailed(Exception)
Called when begin reliable write fails.
protected void OnBeginReliableWriteFailed(Exception e)
Parameters
OnBeginReliableWriteSucceeded()
Called when begin reliable write succeeds.
protected void OnBeginReliableWriteSucceeded()
OnDescriptorsExplorationFailed(Exception)
Called when descriptor exploration fails.
protected void OnDescriptorsExplorationFailed(Exception e)
Parameters
OnDescriptorsExplorationSucceeded<TNativeDescriptorType>(IList<TNativeDescriptorType>, Func<TNativeDescriptorType, IBluetoothRemoteDescriptor, bool>, Func<TNativeDescriptorType, IBluetoothRemoteDescriptor>)
Called when descriptor exploration succeeds.
protected void OnDescriptorsExplorationSucceeded<TNativeDescriptorType>(IList<TNativeDescriptorType> descriptors, Func<TNativeDescriptorType, IBluetoothRemoteDescriptor, bool> areRepresentingTheSameObject, Func<TNativeDescriptorType, IBluetoothRemoteDescriptor> fromInputTypeToOutputTypeConversion)
Parameters
descriptorsIList<TNativeDescriptorType>areRepresentingTheSameObjectFunc<TNativeDescriptorType, IBluetoothRemoteDescriptor, bool>fromInputTypeToOutputTypeConversionFunc<TNativeDescriptorType, IBluetoothRemoteDescriptor>
Type Parameters
TNativeDescriptorType
OnExecuteReliableWriteFailed(Exception)
Called when execute reliable write fails.
protected void OnExecuteReliableWriteFailed(Exception e)
Parameters
OnExecuteReliableWriteSucceeded()
Called when execute reliable write succeeds.
protected void OnExecuteReliableWriteSucceeded()
OnReadIsListeningFailed(Exception)
Called when reading the listening state fails. Completes the task with an exception or dispatches to the unhandled exception listener.
protected void OnReadIsListeningFailed(Exception e)
Parameters
eExceptionThe exception that occurred during the read operation.
Remarks
If there's a pending read operation, the exception will be delivered to it. Otherwise, the exception will be dispatched to the unhandled exception listener.
OnReadIsListeningSucceeded(bool)
Called when reading the listening state succeeds. Updates the IsListening property and completes the task.
protected void OnReadIsListeningSucceeded(bool isListening)
Parameters
isListeningboolThe current listening state returned from the native platform.
Exceptions
- CharacteristicUnexpectedReadNotifyException
Thrown when no pending read operation is found to complete.
OnReadValueFailed(Exception)
Called when reading the characteristic's value fails. Completes the task with an exception or dispatches to the unhandled exception listener.
protected void OnReadValueFailed(Exception e)
Parameters
eExceptionThe exception that occurred during the read operation.
Remarks
If there's a pending read operation, the exception will be delivered to it. Otherwise, the exception will be dispatched to the unhandled exception listener.
OnReadValueSucceeded(ReadOnlyMemory<byte>)
Called when reading the characteristic's value succeeds. Updates the Value property and completes the task.
protected void OnReadValueSucceeded(ReadOnlyMemory<byte> value)
Parameters
valueReadOnlyMemory<byte>The value read from the characteristic.
Exceptions
- CharacteristicUnexpectedReadException
Thrown when no pending read operation is found to complete and the characteristic is not listening.
OnWriteIsListeningFailed(Exception)
Called when writing the listening state fails. Completes the task with an exception or dispatches to the unhandled exception listener.
protected void OnWriteIsListeningFailed(Exception e)
Parameters
eExceptionThe exception that occurred during the write operation.
Remarks
If there's a pending write operation, the exception will be delivered to it. Otherwise, the exception will be dispatched to the unhandled exception listener.
OnWriteIsListeningSucceeded()
Called when writing the listening state succeeds. Completes the task successfully.
protected void OnWriteIsListeningSucceeded()
Exceptions
- CharacteristicUnexpectedWriteNotifyException
Thrown when no pending write operation is found to complete.
OnWriteValueFailed(Exception)
Called when writing the characteristic's value fails. Completes the task with an exception or dispatches to the unhandled exception listener.
protected void OnWriteValueFailed(Exception e)
Parameters
eExceptionThe exception that occurred during the write operation.
Remarks
If there's a pending write operation, the exception will be delivered to it. Otherwise, the exception will be dispatched to the unhandled exception listener.
OnWriteValueSucceeded()
Called when writing the characteristic's value succeeds. Completes the task successfully.
protected void OnWriteValueSucceeded()
Exceptions
- CharacteristicUnexpectedWriteException
Thrown when no pending write operation is found to complete.
ReadIsListeningAsync(TimeSpan?, CancellationToken)
Reads the current listening state of the characteristic asynchronously, ensuring that only one read operation is in progress at a time.
public ValueTask<bool> ReadIsListeningAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
timeoutTimeSpan?The timeout for this operation.
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
Exceptions
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantListenException
Thrown when the characteristic does not support notifications or indications.
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
- TimeoutException
Thrown when the operation times out.
ReadValueAsync(bool, TimeSpan?, CancellationToken)
Reads the value of the characteristic asynchronously.
public ValueTask<ReadOnlyMemory<byte>> ReadValueAsync(bool skipIfPreviouslyRead = false, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
skipIfPreviouslyReadboolIf true, skips reading if the value was previously read.
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask<ReadOnlyMemory<byte>>
A task that represents the asynchronous read operation. The task result contains the value read.
Exceptions
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantReadException
Thrown when the characteristic doesn't support read operations.
- CharacteristicReadException
Thrown when the read operation fails.
- TimeoutException
Thrown when the operation times out.
- OperationCanceledException
Thrown when the operation is cancelled.
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantReadException
Thrown when the characteristic does not support read operations.
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
- TimeoutException
Thrown when the operation times out.
StartListeningAsync(TimeSpan?, CancellationToken)
Starts listening for notifications from the characteristic asynchronously.
public ValueTask StartListeningAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask
A task that represents the asynchronous operation.
Exceptions
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantListenException
Thrown when the characteristic doesn't support notifications.
- CharacteristicAlreadyNotifyingException
Thrown when the characteristic is already listening for notifications.
- CharacteristicNotifyException
Thrown when the notify operation fails.
- TimeoutException
Thrown when the operation times out.
- OperationCanceledException
Thrown when the operation is cancelled.
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantListenException
Thrown when the characteristic does not support notifications or indications.
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
- TimeoutException
Thrown when the operation times out.
StopListeningAsync(TimeSpan?, CancellationToken)
Stops listening for notifications from the characteristic asynchronously.
public ValueTask StopListeningAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask
A task that represents the asynchronous operation.
Exceptions
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantListenException
Thrown when the characteristic doesn't support notifications.
- CharacteristicAlreadyNotifyingException
Thrown when the characteristic is not currently listening.
- CharacteristicNotifyException
Thrown when the notify operation fails.
- TimeoutException
Thrown when the operation times out.
- OperationCanceledException
Thrown when the operation is cancelled.
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantListenException
Thrown when the characteristic does not support notifications or indications.
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
- TimeoutException
Thrown when the operation times out.
ToListenString()
Gets the notification capability string representation for the characteristic.
protected virtual string ToListenString()
Returns
- string
Returns "N*" if listening, "N" if notifications are supported but not listening, otherwise an empty string.
ToReadString()
Gets the read capability string representation for the characteristic.
protected virtual string ToReadString()
Returns
- string
Returns "R" if the characteristic can be read, otherwise an empty string.
ToString()
Returns a string representation of the Bluetooth characteristic, including its ID and access capabilities.
public override string ToString()
Returns
- string
A formatted string that includes the characteristic's short description, ID, and access permissions.
Examples
var characteristicString = characteristic.ToString();
Console.WriteLine(characteristicString); // Output example: CharacteristicName (CharacteristicId) (R/W/N*)
Remarks
The returned string includes a short description of the characteristic, its unique ID, and a shorthand notation for its access capabilities:
Rif the characteristic is readable.Wif the characteristic is writable.N*if the characteristic supports notifications and is actively listening.Nif the characteristic supports notifications but is not currently listening.
ToWriteString()
Gets the write capability string representation for the characteristic.
protected virtual string ToWriteString()
Returns
- string
Returns "W" if the characteristic can be written to, otherwise an empty string.
WaitForValueChangeAsync(Func<ReadOnlyMemory<byte>, bool>?, TimeSpan?, CancellationToken)
Waits for the characteristic's value to change and optionally applies a filter to the new value.
public ValueTask<ReadOnlyMemory<byte>> WaitForValueChangeAsync(Func<ReadOnlyMemory<byte>, bool>? valueFilter = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
valueFilterFunc<ReadOnlyMemory<byte>, bool>Optional filter to apply to the new value. If null, any value change will trigger completion.
timeoutTimeSpan?Optional timeout for the operation.
cancellationTokenCancellationTokenToken to cancel the operation.
Returns
- ValueTask<ReadOnlyMemory<byte>>
The new value that triggered the completion.
Exceptions
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
- TimeoutException
Thrown when the operation times out.
WriteIsListeningAsync(bool, TimeSpan?, CancellationToken)
Writes the desired listening state to the characteristic. This method ensures that only one write operation can occur at a time and handles the asynchronous flow of starting the write operation and waiting for its completion.
public ValueTask WriteIsListeningAsync(bool shouldBeListening, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
shouldBeListeningboolTrue to enable notifications/indications, false to disable them.
timeoutTimeSpan?The timeout for this operation.
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask
A task that represents the asynchronous operation.
Exceptions
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantListenException
Thrown when the characteristic does not support notifications or indications.
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
- TimeoutException
Thrown when the operation times out.
- UnreachableException
Thrown when an already writing operation is detected despite semaphore protection.
WriteValueAsync(ReadOnlyMemory<byte>, bool, TimeSpan?, CancellationToken)
Writes a value to the characteristic asynchronously.
public ValueTask WriteValueAsync(ReadOnlyMemory<byte> value, bool skipIfOldValueMatchesNewValue = false, TimeSpan? timeout = null, CancellationToken cancellationToken = default)
Parameters
valueReadOnlyMemory<byte>The value to write.
skipIfOldValueMatchesNewValueboolIf true, skips writing if the old value matches the new value.
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA cancellation token to cancel this operation.
Returns
- ValueTask
A task that represents the asynchronous write operation.
Exceptions
- ArgumentNullException
Thrown when
valueis null.- InvalidOperationException
Thrown when the characteristic doesn't support write operations.
- TimeoutException
Thrown when the operation times out.
- OperationCanceledException
Thrown when the operation is cancelled.
- DeviceNotConnectedException
Thrown when the device is not connected.
- CharacteristicCantWriteException
Thrown when the characteristic does not support write operations.
- CharacteristicAlreadyWritingException
Thrown when another write operation is already in progress despite semaphore protection.
- OperationCanceledException
Thrown when the operation is cancelled via the cancellation token.
- TimeoutException
Thrown when the operation times out.
Events
DescriptorListChanged
Event triggered when the list of available descriptors changes.
public event EventHandler<DescriptorListChangedEventArgs>? DescriptorListChanged
Event Type
DescriptorsAdded
Event triggered when descriptors are added.
public event EventHandler<DescriptorsAddedEventArgs>? DescriptorsAdded
Event Type
DescriptorsRemoved
Event triggered when descriptors are removed.
public event EventHandler<DescriptorsRemovedEventArgs>? DescriptorsRemoved
Event Type
ValueUpdated
Event raised when the value of the characteristic is updated, only triggered when IsListening is true.
public event EventHandler<ValueUpdatedEventArgs>? ValueUpdated