Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make WriteCharacteristic fail if types mismatch #264

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions Bluejay/Bluejay/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//

import Foundation
import CoreBluetooth

/// Errors specific to Bluejay.
public enum BluejayError {
Expand All @@ -26,6 +27,8 @@ public enum BluejayError {
case missingService(ServiceIdentifier)
/// A Bluetooth characteristic is not found.
case missingCharacteristic(CharacteristicIdentifier)
/// A Bluetooth characteristic doesn't have the requested property
case missingCharacteristicProperty(CBCharacteristicProperties)
/// A Bluetooth operation is cancelled.
case cancelled
/// Bluejay disconnect is called.
Expand Down Expand Up @@ -89,6 +92,8 @@ extension BluejayError: LocalizedError {
return "Service not found: \(service.uuid)"
case let .missingCharacteristic(characteristic):
return "Characteristic not found: \(characteristic.uuid)"
case let .missingCharacteristicProperty(property):
return "Write type (\(property)) on characteristic was not found"
case .cancelled:
return "Cancelled"
case .explicitDisconnect:
Expand Down Expand Up @@ -140,11 +145,11 @@ extension BluejayError: LocalizedError {
}

extension BluejayError: CustomNSError {

public static var errorDomain: String {
return "Bluejay"
}

public var errorCode: Int {
switch self {
case .bluetoothUnavailable: return 1
Expand Down Expand Up @@ -176,6 +181,7 @@ extension BluejayError: CustomNSError {
case .multipleListenTrapped: return 27
case .multipleListenReplaced: return 28
case .tooMuchData: return 29
case .missingCharacteristicProperty: return 30
}
}

Expand Down
6 changes: 6 additions & 0 deletions Bluejay/Bluejay/WriteCharacteristic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ class WriteCharacteristic<T: Sendable>: Operation {
return
}

let property: CBCharacteristicProperties = type == .withoutResponse ? .writeWithoutResponse : .write
guard characteristic.properties.contains(property) else {
fail(BluejayError.missingCharacteristicProperty(property))
return
}

state = .running

peripheral.writeValue(value.toBluetoothData(), for: characteristic, type: type)
Expand Down