71 lines
1.5 KiB
Swift
71 lines
1.5 KiB
Swift
import Foundation
|
|
|
|
enum TemperatureValue {
|
|
case notFound
|
|
case invalidMeasurement
|
|
case value(Double)
|
|
|
|
init(byte: UInt8) {
|
|
switch byte {
|
|
case 0:
|
|
self = .notFound
|
|
case 1:
|
|
self = .invalidMeasurement
|
|
default:
|
|
self = .value(Double(byte) * 0.5 - 40)
|
|
}
|
|
}
|
|
|
|
var byte: UInt8 {
|
|
switch self {
|
|
case .notFound:
|
|
return 0
|
|
case .invalidMeasurement:
|
|
return 1
|
|
case .value(let double):
|
|
let value = (double * 2).roundedInt + 80
|
|
return UInt8(clamping: value)
|
|
}
|
|
}
|
|
|
|
var optionalValue: Double? {
|
|
if case .value(let val) = self {
|
|
return val
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var isValid: Bool {
|
|
if case .value = self {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
var text: String {
|
|
switch self {
|
|
case .notFound:
|
|
return "-"
|
|
case .invalidMeasurement:
|
|
return "?"
|
|
case .value(let value):
|
|
return String(format:"%.1f°", value)
|
|
}
|
|
}
|
|
}
|
|
|
|
extension TemperatureValue: Codable {
|
|
|
|
init(from decoder: Decoder) throws {
|
|
let container = try decoder.singleValueContainer()
|
|
let byte = try container.decode(UInt8.self)
|
|
self.init(byte: byte)
|
|
}
|
|
|
|
func encode(to encoder: Encoder) throws {
|
|
var container = encoder.singleValueContainer()
|
|
try container.encode(byte)
|
|
}
|
|
|
|
}
|