Skip to content

Commit

Permalink
#161 Add DataConvertible to ATTReadRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
colemancda committed Nov 8, 2024
1 parent c82e6b4 commit d698b0c
Showing 1 changed file with 15 additions and 26 deletions.
41 changes: 15 additions & 26 deletions Sources/BluetoothGATT/ATTReadRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,57 +6,46 @@
// Copyright © 2018 PureSwift. All rights reserved.
//

import Foundation
import Bluetooth

/// Read Request
///
/// The *Read Request* is used to request the server to read the value of an attribute
/// and return its value in a *Read Response*.
@frozen
public struct ATTReadRequest: ATTProtocolDataUnit, Equatable {
public struct ATTReadRequest: ATTProtocolDataUnit, Equatable, Hashable, Sendable {

public static var attributeOpcode: ATTOpcode { return .readRequest }
public static var attributeOpcode: ATTOpcode { .readRequest }

/// The handle of the attribute to read.
public var handle: UInt16

public init(handle: UInt16) {

self.handle = handle
}
}

public extension ATTReadRequest {
// MARK: - DataConvertible

extension ATTReadRequest: DataConvertible {

internal static var length: Int { return 1 + 2 }
public static var length: Int { 3 }

init?(data: Data) {
public init?<Data: DataContainer>(data: Data) {

guard data.count == type(of: self).length,
type(of: self).validateOpcode(data)
guard data.count == Self.length,
Self.validateOpcode(data)
else { return nil }

self.handle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2])))
}

var data: Data {

return Data(self)
}
}

// MARK: - DataConvertible

extension ATTReadRequest: DataConvertible {

var dataLength: Int {

return type(of: self).length
public func append<Data>(to data: inout Data) where Data : DataContainer {
data += Self.attributeOpcode.rawValue
data += self.handle.littleEndian
}

static func += <T: DataContainer> (data: inout T, value: ATTReadRequest) {

data += attributeOpcode.rawValue
data += value.handle
public var dataLength: Int {
Self.length
}
}

0 comments on commit d698b0c

Please sign in to comment.