44 lines
1.2 KiB
Swift
44 lines
1.2 KiB
Swift
|
import Foundation
|
||
|
|
||
|
enum DeviceInfoError: Error {
|
||
|
case missingData
|
||
|
}
|
||
|
|
||
|
extension Data {
|
||
|
|
||
|
mutating func decodeUInt16() throws -> UInt16 {
|
||
|
guard count >= 2 else {
|
||
|
throw DeviceInfoError.missingData
|
||
|
}
|
||
|
let low = removeFirst()
|
||
|
let high = removeFirst()
|
||
|
return UInt16(high: high, low: low)
|
||
|
}
|
||
|
|
||
|
mutating func decodeTwoByteInteger() throws -> Int {
|
||
|
try decodeUInt16().integer
|
||
|
}
|
||
|
|
||
|
mutating func decodeFourByteInteger() throws -> Int {
|
||
|
guard count >= 4 else {
|
||
|
throw DeviceInfoError.missingData
|
||
|
}
|
||
|
let byte0 = removeFirst()
|
||
|
let byte1 = removeFirst()
|
||
|
let byte2 = removeFirst()
|
||
|
let byte3 = removeFirst()
|
||
|
return (Int(byte3) << 24) | (Int(byte2) << 16) | (Int(byte1) << 8) | Int(byte0)
|
||
|
}
|
||
|
|
||
|
mutating func decodeSensor() throws -> TemperatureSensor? {
|
||
|
guard count >= 11 else {
|
||
|
throw DeviceInfoError.missingData
|
||
|
}
|
||
|
let address = Array(self[startIndex..<startIndex+8])
|
||
|
removeFirst(8)
|
||
|
let temperatureByte = removeFirst()
|
||
|
let time = try decodeUInt16()
|
||
|
return .init(address: address, valueByte: temperatureByte, secondsAgo: time)
|
||
|
}
|
||
|
}
|