TempTrack-iOS/TempTrack/Temperature/TemperatureValue.swift

71 lines
1.5 KiB
Swift
Raw Normal View History

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)
}
}
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)
}
}
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 "-"
2023-06-03 08:15:00 +02:00
case .invalidMeasurement:
return "?"
case .value(let value):
return String(format:"%.1f°", value)
2023-06-03 08:15:00 +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)
}
}