2023-06-03 08:15:00 +02:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-08 09:52:20 +02:00
|
|
|
var byte: UInt8 {
|
|
|
|
switch self {
|
|
|
|
case .notFound:
|
|
|
|
return 0
|
|
|
|
case .invalidMeasurement:
|
|
|
|
return 1
|
|
|
|
case .value(let double):
|
|
|
|
let value = Int(double + 40) * 2
|
|
|
|
return UInt8(clamping: value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-03 08:15:00 +02:00
|
|
|
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 "No sensor"
|
|
|
|
case .invalidMeasurement:
|
|
|
|
return "Invalid"
|
2023-06-05 13:05:57 +02:00
|
|
|
case .value(let value):
|
|
|
|
return String(format:" %.1f°C", value)
|
2023-06-03 08:15:00 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-06-08 09:52:20 +02:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|