feat: Updates to newer psychrometrics package. Not yet a working example.

This commit is contained in:
2024-11-09 11:35:30 -05:00
parent e2683d3f06
commit a87addaf0b
13 changed files with 821 additions and 737 deletions

View File

@@ -1,262 +1,260 @@
import CoreUnitTypes
import Logging
import Models
import MQTTNIO
import NIO
import NIOFoundationCompat
import Psychrometrics
/// Represents a type that can be initialized by a ``ByteBuffer``.
protocol BufferInitalizable {
init?(buffer: inout ByteBuffer)
}
extension Double: BufferInitalizable {
/// Attempt to create / parse a double from a byte buffer.
init?(buffer: inout ByteBuffer) {
guard let string = buffer.readString(
length: buffer.readableBytes,
encoding: String.Encoding.utf8
)
else { return nil }
self.init(string)
}
}
extension Temperature: BufferInitalizable {
/// Attempt to create / parse a temperature from a byte buffer.
init?(buffer: inout ByteBuffer) {
guard let value = Double(buffer: &buffer) else { return nil }
self.init(value, units: .celsius)
}
}
extension RelativeHumidity: BufferInitalizable {
/// Attempt to create / parse a relative humidity from a byte buffer.
init?(buffer: inout ByteBuffer) {
guard let value = Double(buffer: &buffer) else { return nil }
self.init(value)
}
}
// TODO: Remove below when migrated to async client.
extension MQTTNIO.MQTTClient {
/// Logs a failure for a given topic and error.
func logFailure(topic: String, error: Error) {
logger.error("\(topic): \(error)")
}
}
extension Result where Success == MQTTPublishInfo {
func logIfFailure(client: MQTTNIO.MQTTClient, topic: String) -> ByteBuffer? {
switch self {
case let .success(value):
guard value.topicName == topic else { return nil }
return value.payload
case let .failure(error):
client.logFailure(topic: topic, error: error)
return nil
}
}
}
extension Optional where Wrapped == ByteBuffer {
func parse<T>(as type: T.Type) -> T? where T: BufferInitalizable {
switch self {
case var .some(buffer):
return T.init(buffer: &buffer)
case .none:
return nil
}
}
}
fileprivate struct TemperatureAndHumiditySensorKeyPathEnvelope {
let humidityTopic: KeyPath<Topics.Sensors, String>
let temperatureTopic: KeyPath<Topics.Sensors, String>
let temperatureState: WritableKeyPath<State.Sensors, Temperature?>
let humidityState: WritableKeyPath<State.Sensors, RelativeHumidity?>
func addListener(to client: MQTTNIO.MQTTClient, topics: Topics, state: State) {
let temperatureTopic = topics.sensors[keyPath: temperatureTopic]
client.logger.trace("Adding listener for topic: \(temperatureTopic)")
client.addPublishListener(named: temperatureTopic) { result in
result.logIfFailure(client: client, topic: temperatureTopic)
.parse(as: Temperature.self)
.map { temperature in
state.sensors[keyPath: temperatureState] = temperature
}
}
let humidityTopic = topics.sensors[keyPath: humidityTopic]
client.logger.trace("Adding listener for topic: \(humidityTopic)")
client.addPublishListener(named: humidityTopic) { result in
result.logIfFailure(client: client, topic: humidityTopic)
.parse(as: RelativeHumidity.self)
.map { humidity in
state.sensors[keyPath: humidityState] = humidity
}
}
}
}
extension Array where Element == TemperatureAndHumiditySensorKeyPathEnvelope {
func addListeners(to client: MQTTNIO.MQTTClient, topics: Topics, state: State) {
_ = self.map { envelope in
envelope.addListener(to: client, topics: topics, state: state)
}
}
}
extension Array where Element == MQTTSubscribeInfo {
static func sensors(topics: Topics) -> Self {
[
.init(topicFilter: topics.sensors.mixedAirSensor.temperature, qos: .atLeastOnce),
.init(topicFilter: topics.sensors.mixedAirSensor.humidity, qos: .atLeastOnce),
.init(topicFilter: topics.sensors.postCoilSensor.temperature, qos: .atLeastOnce),
.init(topicFilter: topics.sensors.postCoilSensor.humidity, qos: .atLeastOnce),
.init(topicFilter: topics.sensors.returnAirSensor.temperature, qos: .atLeastOnce),
.init(topicFilter: topics.sensors.returnAirSensor.humidity, qos: .atLeastOnce),
.init(topicFilter: topics.sensors.supplyAirSensor.temperature, qos: .atLeastOnce),
.init(topicFilter: topics.sensors.supplyAirSensor.humidity, qos: .atLeastOnce),
]
}
}
extension State {
func addSensorListeners(to client: MQTTNIO.MQTTClient, topics: Topics) {
let envelopes: [TemperatureAndHumiditySensorKeyPathEnvelope] = [
.init(
humidityTopic: \.mixedAirSensor.humidity,
temperatureTopic: \.mixedAirSensor.temperature,
temperatureState: \.mixedAirSensor.temperature,
humidityState: \.mixedAirSensor.humidity
),
.init(
humidityTopic: \.postCoilSensor.humidity,
temperatureTopic: \.postCoilSensor.temperature,
temperatureState: \.postCoilSensor.temperature,
humidityState: \.postCoilSensor.humidity
),
.init(
humidityTopic: \.returnAirSensor.humidity,
temperatureTopic: \.returnAirSensor.temperature,
temperatureState: \.returnAirSensor.temperature,
humidityState: \.returnAirSensor.humidity
),
.init(
humidityTopic: \.supplyAirSensor.humidity,
temperatureTopic: \.supplyAirSensor.temperature,
temperatureState: \.supplyAirSensor.temperature,
humidityState: \.supplyAirSensor.humidity
),
]
envelopes.addListeners(to: client, topics: topics, state: self)
}
}
extension Client.SensorPublishRequest {
func dewPointData(topics: Topics, units: PsychrometricEnvironment.Units?) -> (DewPoint, String)? {
switch self {
case let .mixed(sensor):
guard let dp = sensor.dewPoint(units: units) else { return nil }
return (dp, topics.sensors.mixedAirSensor.dewPoint)
case let .postCoil(sensor):
guard let dp = sensor.dewPoint(units: units) else { return nil }
return (dp, topics.sensors.postCoilSensor.dewPoint)
case let .return(sensor):
guard let dp = sensor.dewPoint(units: units) else { return nil }
return (dp, topics.sensors.returnAirSensor.dewPoint)
case let .supply(sensor):
guard let dp = sensor.dewPoint(units: units) else { return nil }
return (dp, topics.sensors.supplyAirSensor.dewPoint)
}
}
func enthalpyData(altitude: Length, topics: Topics, units: PsychrometricEnvironment.Units?) -> (EnthalpyOf<MoistAir>, String)? {
switch self {
case let .mixed(sensor):
guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
return (enthalpy, topics.sensors.mixedAirSensor.enthalpy)
case let .postCoil(sensor):
guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
return (enthalpy, topics.sensors.postCoilSensor.enthalpy)
case let .return(sensor):
guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
return (enthalpy, topics.sensors.returnAirSensor.enthalpy)
case let .supply(sensor):
guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
return (enthalpy, topics.sensors.supplyAirSensor.enthalpy)
}
}
func setHasProcessed(state: State) {
switch self {
case .mixed:
state.sensors.mixedAirSensor.needsProcessed = false
case .postCoil:
state.sensors.postCoilSensor.needsProcessed = false
case .return:
state.sensors.returnAirSensor.needsProcessed = false
case .supply:
state.sensors.supplyAirSensor.needsProcessed = false
}
}
}
extension MQTTNIO.MQTTClient {
func publishDewPoint(
request: Client.SensorPublishRequest,
state: State,
topics: Topics
) -> EventLoopFuture<(MQTTNIO.MQTTClient, Client.SensorPublishRequest, State, Topics)> {
guard let (dewPoint, topic) = request.dewPointData(topics: topics, units: state.units)
else {
logger.trace("No dew point for sensor.")
return eventLoopGroup.next().makeSucceededFuture((self, request, state, topics))
}
let roundedDewPoint = round(dewPoint.rawValue * 100) / 100
logger.debug("Publishing dew-point: \(dewPoint), to: \(topic)")
return publish(
to: topic,
payload: ByteBufferAllocator().buffer(string: "\(roundedDewPoint)"),
qos: .atLeastOnce,
retain: true
)
.map { (self, request, state, topics) }
}
}
extension EventLoopFuture where Value == (Client.SensorPublishRequest, State) {
func setHasProcessed() -> EventLoopFuture<Void> {
map { request, state in
request.setHasProcessed(state: state)
}
}
}
extension EventLoopFuture where Value == (MQTTNIO.MQTTClient, Client.SensorPublishRequest, State, Topics) {
func publishEnthalpy() -> EventLoopFuture<(Client.SensorPublishRequest, State)> {
flatMap { client, request, state, topics in
guard let (enthalpy, topic) = request.enthalpyData(altitude: state.altitude, topics: topics, units: state.units)
else {
client.logger.trace("No enthalpy for sensor.")
return client.eventLoopGroup.next().makeSucceededFuture((request, state))
}
let roundedEnthalpy = round(enthalpy.rawValue * 100) / 100
client.logger.debug("Publishing enthalpy: \(enthalpy), to: \(topic)")
return client.publish(
to: topic,
payload: ByteBufferAllocator().buffer(string: "\(roundedEnthalpy)"),
qos: .atLeastOnce
)
.map { (request, state) }
}
}
}
// import Logging
// import Models
// import MQTTNIO
// import NIO
// import NIOFoundationCompat
// import PsychrometricClient
//
// /// Represents a type that can be initialized by a ``ByteBuffer``.
// protocol BufferInitalizable {
// init?(buffer: inout ByteBuffer)
// }
//
// extension Double: BufferInitalizable {
//
// /// Attempt to create / parse a double from a byte buffer.
// init?(buffer: inout ByteBuffer) {
// guard let string = buffer.readString(
// length: buffer.readableBytes,
// encoding: String.Encoding.utf8
// )
// else { return nil }
// self.init(string)
// }
// }
//
// extension Temperature: BufferInitalizable {
// /// Attempt to create / parse a temperature from a byte buffer.
// init?(buffer: inout ByteBuffer) {
// guard let value = Double(buffer: &buffer) else { return nil }
// self.init(value, units: .celsius)
// }
// }
//
// extension RelativeHumidity: BufferInitalizable {
// /// Attempt to create / parse a relative humidity from a byte buffer.
// init?(buffer: inout ByteBuffer) {
// guard let value = Double(buffer: &buffer) else { return nil }
// self.init(value)
// }
// }
//
// // TODO: Remove below when migrated to async client.
// extension MQTTNIO.MQTTClient {
// /// Logs a failure for a given topic and error.
// func logFailure(topic: String, error: Error) {
// logger.error("\(topic): \(error)")
// }
// }
//
// extension Result where Success == MQTTPublishInfo {
// func logIfFailure(client: MQTTNIO.MQTTClient, topic: String) -> ByteBuffer? {
// switch self {
// case let .success(value):
// guard value.topicName == topic else { return nil }
// return value.payload
// case let .failure(error):
// client.logFailure(topic: topic, error: error)
// return nil
// }
// }
// }
//
// extension Optional where Wrapped == ByteBuffer {
//
// func parse<T>(as _: T.Type) -> T? where T: BufferInitalizable {
// switch self {
// case var .some(buffer):
// return T(buffer: &buffer)
// case .none:
// return nil
// }
// }
// }
//
// private struct TemperatureAndHumiditySensorKeyPathEnvelope {
//
// let humidityTopic: KeyPath<Topics.Sensors, String>
// let temperatureTopic: KeyPath<Topics.Sensors, String>
// let temperatureState: WritableKeyPath<State.Sensors, Temperature?>
// let humidityState: WritableKeyPath<State.Sensors, RelativeHumidity?>
//
// func addListener(to client: MQTTNIO.MQTTClient, topics: Topics, state: State) {
// let temperatureTopic = topics.sensors[keyPath: temperatureTopic]
// client.logger.trace("Adding listener for topic: \(temperatureTopic)")
// client.addPublishListener(named: temperatureTopic) { result in
// result.logIfFailure(client: client, topic: temperatureTopic)
// .parse(as: Temperature.self)
// .map { temperature in
// state.sensors[keyPath: temperatureState] = temperature
// }
// }
//
// let humidityTopic = topics.sensors[keyPath: humidityTopic]
// client.logger.trace("Adding listener for topic: \(humidityTopic)")
// client.addPublishListener(named: humidityTopic) { result in
// result.logIfFailure(client: client, topic: humidityTopic)
// .parse(as: RelativeHumidity.self)
// .map { humidity in
// state.sensors[keyPath: humidityState] = humidity
// }
// }
// }
// }
//
// extension Array where Element == TemperatureAndHumiditySensorKeyPathEnvelope {
// func addListeners(to client: MQTTNIO.MQTTClient, topics: Topics, state: State) {
// _ = map { envelope in
// envelope.addListener(to: client, topics: topics, state: state)
// }
// }
// }
//
// extension Array where Element == MQTTSubscribeInfo {
// static func sensors(topics: Topics) -> Self {
// [
// .init(topicFilter: topics.sensors.mixedAirSensor.temperature, qos: .atLeastOnce),
// .init(topicFilter: topics.sensors.mixedAirSensor.humidity, qos: .atLeastOnce),
// .init(topicFilter: topics.sensors.postCoilSensor.temperature, qos: .atLeastOnce),
// .init(topicFilter: topics.sensors.postCoilSensor.humidity, qos: .atLeastOnce),
// .init(topicFilter: topics.sensors.returnAirSensor.temperature, qos: .atLeastOnce),
// .init(topicFilter: topics.sensors.returnAirSensor.humidity, qos: .atLeastOnce),
// .init(topicFilter: topics.sensors.supplyAirSensor.temperature, qos: .atLeastOnce),
// .init(topicFilter: topics.sensors.supplyAirSensor.humidity, qos: .atLeastOnce)
// ]
// }
// }
//
// extension State {
// func addSensorListeners(to client: MQTTNIO.MQTTClient, topics: Topics) {
// let envelopes: [TemperatureAndHumiditySensorKeyPathEnvelope] = [
// .init(
// humidityTopic: \.mixedAirSensor.humidity,
// temperatureTopic: \.mixedAirSensor.temperature,
// temperatureState: \.mixedAirSensor.temperature,
// humidityState: \.mixedAirSensor.humidity
// ),
// .init(
// humidityTopic: \.postCoilSensor.humidity,
// temperatureTopic: \.postCoilSensor.temperature,
// temperatureState: \.postCoilSensor.temperature,
// humidityState: \.postCoilSensor.humidity
// ),
// .init(
// humidityTopic: \.returnAirSensor.humidity,
// temperatureTopic: \.returnAirSensor.temperature,
// temperatureState: \.returnAirSensor.temperature,
// humidityState: \.returnAirSensor.humidity
// ),
// .init(
// humidityTopic: \.supplyAirSensor.humidity,
// temperatureTopic: \.supplyAirSensor.temperature,
// temperatureState: \.supplyAirSensor.temperature,
// humidityState: \.supplyAirSensor.humidity
// )
// ]
// envelopes.addListeners(to: client, topics: topics, state: self)
// }
// }
//
// extension Client.SensorPublishRequest {
//
// func dewPointData(topics: Topics, units: PsychrometricEnvironment.Units?) -> (DewPoint, String)? {
// switch self {
// case let .mixed(sensor):
// guard let dp = sensor.dewPoint(units: units) else { return nil }
// return (dp, topics.sensors.mixedAirSensor.dewPoint)
// case let .postCoil(sensor):
// guard let dp = sensor.dewPoint(units: units) else { return nil }
// return (dp, topics.sensors.postCoilSensor.dewPoint)
// case let .return(sensor):
// guard let dp = sensor.dewPoint(units: units) else { return nil }
// return (dp, topics.sensors.returnAirSensor.dewPoint)
// case let .supply(sensor):
// guard let dp = sensor.dewPoint(units: units) else { return nil }
// return (dp, topics.sensors.supplyAirSensor.dewPoint)
// }
// }
//
// func enthalpyData(altitude: Length, topics: Topics, units: PsychrometricEnvironment.Units?) -> (EnthalpyOf<MoistAir>, String)? {
// switch self {
// case let .mixed(sensor):
// guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
// return (enthalpy, topics.sensors.mixedAirSensor.enthalpy)
// case let .postCoil(sensor):
// guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
// return (enthalpy, topics.sensors.postCoilSensor.enthalpy)
// case let .return(sensor):
// guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
// return (enthalpy, topics.sensors.returnAirSensor.enthalpy)
// case let .supply(sensor):
// guard let enthalpy = sensor.enthalpy(altitude: altitude, units: units) else { return nil }
// return (enthalpy, topics.sensors.supplyAirSensor.enthalpy)
// }
// }
//
// func setHasProcessed(state: State) {
// switch self {
// case .mixed:
// state.sensors.mixedAirSensor.needsProcessed = false
// case .postCoil:
// state.sensors.postCoilSensor.needsProcessed = false
// case .return:
// state.sensors.returnAirSensor.needsProcessed = false
// case .supply:
// state.sensors.supplyAirSensor.needsProcessed = false
// }
// }
// }
//
// extension MQTTNIO.MQTTClient {
//
// func publishDewPoint(
// request: Client.SensorPublishRequest,
// state: State,
// topics: Topics
// ) -> EventLoopFuture<(MQTTNIO.MQTTClient, Client.SensorPublishRequest, State, Topics)> {
// guard let (dewPoint, topic) = request.dewPointData(topics: topics, units: state.units)
// else {
// logger.trace("No dew point for sensor.")
// return eventLoopGroup.next().makeSucceededFuture((self, request, state, topics))
// }
// let roundedDewPoint = round(dewPoint.rawValue * 100) / 100
// logger.debug("Publishing dew-point: \(dewPoint), to: \(topic)")
// return publish(
// to: topic,
// payload: ByteBufferAllocator().buffer(string: "\(roundedDewPoint)"),
// qos: .atLeastOnce,
// retain: true
// )
// .map { (self, request, state, topics) }
// }
// }
//
// extension EventLoopFuture where Value == (Client.SensorPublishRequest, State) {
// func setHasProcessed() -> EventLoopFuture<Void> {
// map { request, state in
// request.setHasProcessed(state: state)
// }
// }
// }
//
// extension EventLoopFuture where Value == (MQTTNIO.MQTTClient, Client.SensorPublishRequest, State, Topics) {
// func publishEnthalpy() -> EventLoopFuture<(Client.SensorPublishRequest, State)> {
// flatMap { client, request, state, topics in
// guard let (enthalpy, topic) = request.enthalpyData(altitude: state.altitude, topics: topics, units: state.units)
// else {
// client.logger.trace("No enthalpy for sensor.")
// return client.eventLoopGroup.next().makeSucceededFuture((request, state))
// }
// let roundedEnthalpy = round(enthalpy.rawValue * 100) / 100
// client.logger.debug("Publishing enthalpy: \(enthalpy), to: \(topic)")
// return client.publish(
// to: topic,
// payload: ByteBufferAllocator().buffer(string: "\(roundedEnthalpy)"),
// qos: .atLeastOnce
// )
// .map { (request, state) }
// }
// }
// }

View File

@@ -1,41 +1,40 @@
@_exported import Client
import CoreUnitTypes
import Foundation
import Models
import MQTTNIO
import NIO
import Psychrometrics
public extension Client {
// The state passed in here needs to be a class or we get escaping errors in the `addListeners` method.
static func live(
client: MQTTNIO.MQTTClient,
state: State,
topics: Topics
) -> Self {
.init(
addListeners: {
state.addSensorListeners(to: client, topics: topics)
},
connect: {
client.connect()
.map { _ in }
},
publishSensor: { request in
client.publishDewPoint(request: request, state: state, topics: topics)
.publishEnthalpy()
.setHasProcessed()
},
shutdown: {
client.disconnect()
.map { try? client.syncShutdownGracefully() }
},
subscribe: {
// Sensor subscriptions
client.subscribe(to: .sensors(topics: topics))
.map { _ in }
}
)
}
}
// @_exported import Client
// import Foundation
// import Models
// import MQTTNIO
// import NIO
// import PsychrometricClient
//
// public extension Client {
//
// // The state passed in here needs to be a class or we get escaping errors in the `addListeners` method.
// static func live(
// client: MQTTNIO.MQTTClient,
// state: State,
// topics: Topics
// ) -> Self {
// .init(
// addListeners: {
// state.addSensorListeners(to: client, topics: topics)
// },
// connect: {
// client.connect()
// .map { _ in }
// },
// publishSensor: { request in
// client.publishDewPoint(request: request, state: state, topics: topics)
// .publishEnthalpy()
// .setHasProcessed()
// },
// shutdown: {
// client.disconnect()
// .map { try? client.syncShutdownGracefully() }
// },
// subscribe: {
// // Sensor subscriptions
// client.subscribe(to: .sensors(topics: topics))
// .map { _ in }
// }
// )
// }
// }

View File

@@ -1,262 +1,262 @@
import EnvVars
import Logging
import Models
import MQTTNIO
import NIO
import Psychrometrics
import ServiceLifecycle
// TODO: Remove.
// TODO: Pass in eventLoopGroup and MQTTClient.
public actor SensorsClient {
public static let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
public let client: MQTTClient
public private(set) var shuttingDown: Bool
public private(set) var sensors: [TemperatureAndHumiditySensor]
var logger: Logger { client.logger }
public init(
envVars: EnvVars,
logger: Logger,
sensors: [TemperatureAndHumiditySensor] = []
) {
let config = MQTTClient.Configuration(
version: .v3_1_1,
userName: envVars.userName,
password: envVars.password,
useSSL: false,
useWebSockets: false,
tlsConfiguration: nil,
webSocketURLPath: nil
)
self.client = MQTTClient(
host: envVars.host,
identifier: envVars.identifier,
eventLoopGroupProvider: .shared(Self.eventLoopGroup),
logger: logger,
configuration: config
)
self.shuttingDown = false
self.sensors = sensors
}
public func addSensor(_ sensor: TemperatureAndHumiditySensor) async throws {
guard sensors.firstIndex(where: { $0.location == sensor.location }) == nil else {
throw SensorExists()
}
sensors.append(sensor)
}
public func connect(cleanSession: Bool = true) async {
do {
try await client.connect(cleanSession: cleanSession)
client.addCloseListener(named: "SensorsClient") { [self] _ in
guard !self.shuttingDown else { return }
Task {
self.logger.debug("Connection closed.")
self.logger.debug("Reconnecting...")
await self.connect()
}
}
logger.debug("Connection successful.")
} catch {
logger.trace("Connection Failed.\n\(error)")
}
}
public func start() async throws {
await withGracefulShutdownHandler {
await withThrowingTaskGroup(of: Void.self) { group in
group.addTask { try await self.subscribeToSensors() }
group.addTask { try await self.addSensorListeners() }
}
} onGracefulShutdown: {
Task { await self.shutdown() }
}
// import EnvVars
// import Logging
// import Models
// import MQTTNIO
// import NIO
// import PsychrometricClient
// import ServiceLifecycle
//
// // TODO: Remove.
// // TODO: Pass in eventLoopGroup and MQTTClient.
// public actor SensorsClient {
//
// public static let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
// public let client: MQTTClient
// public private(set) var shuttingDown: Bool
// public private(set) var sensors: [TemperatureAndHumiditySensor]
//
// var logger: Logger { client.logger }
//
// public init(
// envVars: EnvVars,
// logger: Logger,
// sensors: [TemperatureAndHumiditySensor] = []
// ) {
// let config = MQTTClient.Configuration(
// version: .v3_1_1,
// userName: envVars.userName,
// password: envVars.password,
// useSSL: false,
// useWebSockets: false,
// tlsConfiguration: nil,
// webSocketURLPath: nil
// )
// self.client = MQTTClient(
// host: envVars.host,
// identifier: envVars.identifier,
// eventLoopGroupProvider: .shared(Self.eventLoopGroup),
// logger: logger,
// configuration: config
// )
// self.shuttingDown = false
// self.sensors = sensors
// }
//
// public func addSensor(_ sensor: TemperatureAndHumiditySensor) async throws {
// guard sensors.firstIndex(where: { $0.location == sensor.location }) == nil else {
// throw SensorExists()
// }
// sensors.append(sensor)
// }
//
// public func connect(cleanSession: Bool = true) async {
// do {
// try await subscribeToSensors()
// try await addSensorListeners()
// logger.debug("Begin listening to sensors...")
// try await client.connect(cleanSession: cleanSession)
// client.addCloseListener(named: "SensorsClient") { [self] _ in
// guard !self.shuttingDown else { return }
// Task {
// self.logger.debug("Connection closed.")
// self.logger.debug("Reconnecting...")
// await self.connect()
// }
// }
// logger.debug("Connection successful.")
// } catch {
// logger.trace("Error:\n(error)")
// logger.trace("Connection Failed.\(error)")
// }
// }
//
// public func start() async throws {
// await withGracefulShutdownHandler {
// await withThrowingTaskGroup(of: Void.self) { group in
// group.addTask { try await self.subscribeToSensors() }
// group.addTask { try await self.addSensorListeners() }
// }
// } onGracefulShutdown: {
// Task { await self.shutdown() }
// }
// // do {
// // try await subscribeToSensors()
// // try await addSensorListeners()
// // logger.debug("Begin listening to sensors...")
// // } catch {
// // logger.trace("Error:(error)")
// // throw error
// // }
// }
//
// public func shutdown() async {
// shuttingDown = true
// try? await client.disconnect()
// try? await client.shutdown()
// }
//
// /// Subscribe to changes of the temperature and humidity sensors.
// func subscribeToSensors(qos: MQTTQoS = .exactlyOnce) async throws {
// for sensor in sensors {
// try await client.subscribeToSensor(sensor, qos: qos)
// }
// }
//
// private func _addSensorListeners(qos _: MQTTQoS = .exactlyOnce) async throws {
// // try await withThrowingDiscardingTaskGroup { group in
// // group.addTask { try await self.subscribeToSensors(qos: qos) }
//
// for await result in client.createPublishListener() {
// switch result {
// case let .failure(error):
// logger.trace("Error:\(error)")
// case let .success(value):
// let topic = value.topicName
// logger.trace("Received new value for topic: \(topic)")
// if topic.contains("temperature") {
// // do something.
// var buffer = value.payload
// guard let temperature = Temperature(buffer: &buffer) else {
// logger.trace("Decoding error for topic: \(topic)")
// throw DecodingError()
// }
// try sensors.update(topic: topic, keyPath: \.temperature, with: temperature)
// // group.addTask {
// Task {
// try await self.publishUpdates()
// }
//
// } else if topic.contains("humidity") {
// var buffer = value.payload
// // Decode and update the temperature value
// guard let humidity = RelativeHumidity(buffer: &buffer) else {
// logger.debug("Failed to decode humidity from buffer: \(buffer)")
// throw DecodingError()
// }
// try sensors.update(topic: topic, keyPath: \.humidity, with: humidity)
// // group.addTask {
// Task {
// try await self.publishUpdates()
// }
// }
// // }
// }
// }
// }
//
// func addSensorListeners(qos: MQTTQoS = .exactlyOnce) async throws {
// try await subscribeToSensors(qos: qos)
// client.addPublishListener(named: "SensorsClient") { result in
// do {
// switch result {
// case let .success(value):
// var buffer = value.payload
// let topic = value.topicName
// self.logger.trace("Received new value for topic: \(topic)")
//
// if topic.contains("temperature") {
// // Decode and update the temperature value
// guard let temperature = Temperature(buffer: &buffer) else {
// self.logger.debug("Failed to decode temperature from buffer: \(buffer)")
// throw DecodingError()
// }
// try self.sensors.update(topic: topic, keyPath: \.temperature, with: temperature)
// Task { try await self.publishUpdates() }
// } else if topic.contains("humidity") {
// // Decode and update the temperature value
// guard let humidity = RelativeHumidity(buffer: &buffer) else {
// self.logger.debug("Failed to decode humidity from buffer: \(buffer)")
// throw DecodingError()
// }
// try self.sensors.update(topic: topic, keyPath: \.humidity, with: humidity)
// Task { try await self.publishUpdates() }
// }
//
// case let .failure(error):
// self.logger.trace("Error:\(error)")
// throw error
// }
// } catch {
// self.logger.trace("Error:\(error)")
// }
// }
// }
//
// private func publish(double: Double?, to topic: String) async throws {
// guard let double else { return }
// let rounded = round(double * 100) / 100
// logger.debug("Publishing \(rounded), to: \(topic)")
// try await client.publish(
// to: topic,
// payload: ByteBufferAllocator().buffer(string: "\(rounded)"),
// qos: .exactlyOnce,
// retain: true
// )
// }
//
// private func publishUpdates() async throws {
// for sensor in sensors.filter(\.needsProcessed) {
// try await publish(double: sensor.dewPoint?.rawValue, to: sensor.topics.dewPoint)
// try await publish(double: sensor.enthalpy?.rawValue, to: sensor.topics.enthalpy)
// try sensors.hasProcessed(sensor)
// }
// }
// }
//
// // MARK: - Helpers
//
// private extension MQTTClient {
//
// func subscribeToSensor(
// _ sensor: TemperatureAndHumiditySensor,
// qos: MQTTQoS = .exactlyOnce
// ) async throws {
// do {
// _ = try await subscribe(to: [
// MQTTSubscribeInfo(topicFilter: sensor.topics.temperature, qos: qos),
// MQTTSubscribeInfo(topicFilter: sensor.topics.humidity, qos: qos)
// ])
// logger.debug("Subscribed to temperature-humidity sensor: \(sensor.id)")
// } catch {
// logger.trace("Failed to subscribe to temperature-humidity sensor: \(sensor.id)")
// throw error
// }
}
public func shutdown() async {
shuttingDown = true
try? await client.disconnect()
try? await client.shutdown()
}
/// Subscribe to changes of the temperature and humidity sensors.
func subscribeToSensors(qos: MQTTQoS = .exactlyOnce) async throws {
for sensor in sensors {
try await client.subscribeToSensor(sensor, qos: qos)
}
}
private func _addSensorListeners(qos _: MQTTQoS = .exactlyOnce) async throws {
// try await withThrowingDiscardingTaskGroup { group in
// group.addTask { try await self.subscribeToSensors(qos: qos) }
for await result in client.createPublishListener() {
switch result {
case let .failure(error):
logger.trace("Error:\n\(error)")
case let .success(value):
let topic = value.topicName
logger.trace("Received new value for topic: \(topic)")
if topic.contains("temperature") {
// do something.
var buffer = value.payload
guard let temperature = Temperature(buffer: &buffer) else {
logger.trace("Decoding error for topic: \(topic)")
throw DecodingError()
}
try sensors.update(topic: topic, keyPath: \.temperature, with: temperature)
// group.addTask {
Task {
try await self.publishUpdates()
}
} else if topic.contains("humidity") {
var buffer = value.payload
// Decode and update the temperature value
guard let humidity = RelativeHumidity(buffer: &buffer) else {
logger.debug("Failed to decode humidity from buffer: \(buffer)")
throw DecodingError()
}
try sensors.update(topic: topic, keyPath: \.humidity, with: humidity)
// group.addTask {
Task {
try await self.publishUpdates()
}
}
// }
}
}
}
func addSensorListeners(qos: MQTTQoS = .exactlyOnce) async throws {
try await subscribeToSensors(qos: qos)
client.addPublishListener(named: "SensorsClient") { result in
do {
switch result {
case let .success(value):
var buffer = value.payload
let topic = value.topicName
self.logger.trace("Received new value for topic: \(topic)")
if topic.contains("temperature") {
// Decode and update the temperature value
guard let temperature = Temperature(buffer: &buffer) else {
self.logger.debug("Failed to decode temperature from buffer: \(buffer)")
throw DecodingError()
}
try self.sensors.update(topic: topic, keyPath: \.temperature, with: temperature)
Task { try await self.publishUpdates() }
} else if topic.contains("humidity") {
// Decode and update the temperature value
guard let humidity = RelativeHumidity(buffer: &buffer) else {
self.logger.debug("Failed to decode humidity from buffer: \(buffer)")
throw DecodingError()
}
try self.sensors.update(topic: topic, keyPath: \.humidity, with: humidity)
Task { try await self.publishUpdates() }
}
case let .failure(error):
self.logger.trace("Error:\n\(error)")
throw error
}
} catch {
self.logger.trace("Error:\n\(error)")
}
}
}
private func publish(double: Double?, to topic: String) async throws {
guard let double else { return }
let rounded = round(double * 100) / 100
logger.debug("Publishing \(rounded), to: \(topic)")
try await client.publish(
to: topic,
payload: ByteBufferAllocator().buffer(string: "\(rounded)"),
qos: .exactlyOnce,
retain: true
)
}
private func publishUpdates() async throws {
for sensor in sensors.filter(\.needsProcessed) {
try await publish(double: sensor.dewPoint?.rawValue, to: sensor.topics.dewPoint)
try await publish(double: sensor.enthalpy?.rawValue, to: sensor.topics.enthalpy)
try sensors.hasProcessed(sensor)
}
}
}
// MARK: - Helpers
private extension MQTTClient {
func subscribeToSensor(
_ sensor: TemperatureAndHumiditySensor,
qos: MQTTQoS = .exactlyOnce
) async throws {
do {
_ = try await subscribe(to: [
MQTTSubscribeInfo(topicFilter: sensor.topics.temperature, qos: qos),
MQTTSubscribeInfo(topicFilter: sensor.topics.humidity, qos: qos)
])
logger.debug("Subscribed to temperature-humidity sensor: \(sensor.id)")
} catch {
logger.trace("Failed to subscribe to temperature-humidity sensor: \(sensor.id)")
throw error
}
}
}
struct DecodingError: Error {}
struct NotFoundError: Error {}
struct SensorExists: Error {}
private extension TemperatureAndHumiditySensor.Topics {
func contains(_ topic: String) -> Bool {
temperature == topic || humidity == topic
}
}
// TODO: Move to dewpoint-controller/main.swift
public extension Array where Element == TemperatureAndHumiditySensor {
static var live: Self {
TemperatureAndHumiditySensor.Location.allCases.map {
TemperatureAndHumiditySensor(location: $0)
}
}
}
private extension Array where Element == TemperatureAndHumiditySensor {
mutating func update<V>(
topic: String,
keyPath: WritableKeyPath<TemperatureAndHumiditySensor, V>,
with value: V
) throws {
guard let index = firstIndex(where: { $0.topics.contains(topic) }) else {
throw NotFoundError()
}
self[index][keyPath: keyPath] = value
}
mutating func hasProcessed(_ sensor: TemperatureAndHumiditySensor) throws {
guard let index = firstIndex(where: { $0.id == sensor.id }) else {
throw NotFoundError()
}
self[index].needsProcessed = false
}
}
// }
// }
//
// struct DecodingError: Error {}
// struct NotFoundError: Error {}
// struct SensorExists: Error {}
//
// private extension TemperatureAndHumiditySensor.Topics {
// func contains(_ topic: String) -> Bool {
// temperature == topic || humidity == topic
// }
// }
//
// // TODO: Move to dewpoint-controller/main.swift
// public extension Array where Element == TemperatureAndHumiditySensor {
// static var live: Self {
// TemperatureAndHumiditySensor.Location.allCases.map {
// TemperatureAndHumiditySensor(location: $0)
// }
// }
// }
//
// private extension Array where Element == TemperatureAndHumiditySensor {
//
// mutating func update<V>(
// topic: String,
// keyPath: WritableKeyPath<TemperatureAndHumiditySensor, V>,
// with value: V
// ) throws {
// guard let index = firstIndex(where: { $0.topics.contains(topic) }) else {
// throw NotFoundError()
// }
// self[index][keyPath: keyPath] = value
// }
//
// mutating func hasProcessed(_ sensor: TemperatureAndHumiditySensor) throws {
// guard let index = firstIndex(where: { $0.id == sensor.id }) else {
// throw NotFoundError()
// }
// self[index].needsProcessed = false
// }
//
// }