feat: Adds MQTTConnectionService

This commit is contained in:
2024-11-09 09:03:31 -05:00
parent 79bb162434
commit 90c5b7c77f
4 changed files with 92 additions and 21 deletions

View File

@@ -2,6 +2,10 @@
import PackageDescription import PackageDescription
let swiftSettings: [SwiftSetting] = [
.enableExperimentalFeature("StrictConcurrency")
]
let package = Package( let package = Package(
name: "dewPoint-controller", name: "dewPoint-controller",
platforms: [ platforms: [
@@ -47,7 +51,8 @@ let package = Package(
"Models", "Models",
.product(name: "MQTTNIO", package: "mqtt-nio"), .product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "NIO", package: "swift-nio") .product(name: "NIO", package: "swift-nio")
] ],
swiftSettings: swiftSettings
), ),
.target( .target(
name: "DewPointEnvironment", name: "DewPointEnvironment",
@@ -56,17 +61,20 @@ let package = Package(
"Client", "Client",
"Models", "Models",
.product(name: "MQTTNIO", package: "mqtt-nio") .product(name: "MQTTNIO", package: "mqtt-nio")
] ],
swiftSettings: swiftSettings
), ),
.target( .target(
name: "EnvVars", name: "EnvVars",
dependencies: [] dependencies: [],
swiftSettings: swiftSettings
), ),
.target( .target(
name: "Models", name: "Models",
dependencies: [ dependencies: [
.product(name: "Psychrometrics", package: "swift-psychrometrics") .product(name: "Psychrometrics", package: "swift-psychrometrics")
] ],
swiftSettings: swiftSettings
), ),
.target( .target(
name: "Client", name: "Client",
@@ -75,7 +83,8 @@ let package = Package(
.product(name: "CoreUnitTypes", package: "swift-psychrometrics"), .product(name: "CoreUnitTypes", package: "swift-psychrometrics"),
.product(name: "NIO", package: "swift-nio"), .product(name: "NIO", package: "swift-nio"),
.product(name: "Psychrometrics", package: "swift-psychrometrics") .product(name: "Psychrometrics", package: "swift-psychrometrics")
] ],
swiftSettings: swiftSettings
), ),
.target( .target(
name: "ClientLive", name: "ClientLive",
@@ -84,7 +93,8 @@ let package = Package(
"EnvVars", "EnvVars",
.product(name: "MQTTNIO", package: "mqtt-nio"), .product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle") .product(name: "ServiceLifecycle", package: "swift-service-lifecycle")
] ],
swiftSettings: swiftSettings
), ),
.testTarget( .testTarget(
name: "ClientTests", name: "ClientTests",
@@ -94,10 +104,13 @@ let package = Package(
] ]
), ),
.target( .target(
name: "TopicsLive", name: "MQTTConnectionService",
dependencies: [ dependencies: [
"Models" "EnvVars",
] .product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle")
],
swiftSettings: swiftSettings
), ),
.target( .target(
name: "SensorsService", name: "SensorsService",
@@ -105,7 +118,8 @@ let package = Package(
"Models", "Models",
.product(name: "MQTTNIO", package: "mqtt-nio"), .product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle") .product(name: "ServiceLifecycle", package: "swift-service-lifecycle")
] ],
swiftSettings: swiftSettings
), ),
.testTarget( .testTarget(
name: "SensorsServiceTests", name: "SensorsServiceTests",
@@ -114,6 +128,13 @@ let package = Package(
// TODO: Remove. // TODO: Remove.
"ClientLive" "ClientLive"
] ]
),
.target(
name: "TopicsLive",
dependencies: [
"Models"
],
swiftSettings: swiftSettings
) )
] ]
) )

View File

@@ -0,0 +1,56 @@
import EnvVars
import Logging
import MQTTNIO
import NIO
import ServiceLifecycle
/// Manages the MQTT broker connection.
public actor MQTTConnectionService: Service {
private let cleanSession: Bool
public let client: MQTTClient
private var shuttingDown = false
var logger: Logger { client.logger }
public init(
cleanSession: Bool = true,
client: MQTTClient
) {
self.cleanSession = cleanSession
self.client = client
}
/// The entry-point of the service.
///
/// This method connects to the MQTT broker and manages the connection.
/// It will attempt to gracefully shutdown the connection upon receiving
/// `sigterm` signals.
public func run() async throws {
await withGracefulShutdownHandler {
await self.connect()
} onGracefulShutdown: {
Task { await self.shutdown() }
}
}
private func shutdown() async {
shuttingDown = true
try? await client.disconnect()
try? await client.shutdown()
}
private func connect() async {
do {
try await client.connect(cleanSession: cleanSession)
client.addCloseListener(named: "SensorsClient") { [self] _ in
Task {
self.logger.debug("Connection closed.")
self.logger.debug("Reconnecting...")
await self.connect()
}
}
logger.debug("Connection successful.")
} catch {
logger.trace("Connection Failed.\n\(error)")
}
}
}

View File

@@ -3,6 +3,7 @@
/// Represents a temperature and humidity sensor that can be used to derive /// Represents a temperature and humidity sensor that can be used to derive
/// the dew-point temperature and enthalpy values. /// the dew-point temperature and enthalpy values.
/// ///
/// > Note: Temperature values are received in `celsius`.
public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @unchecked Sendable { public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @unchecked Sendable {
/// The identifier of the sensor, same as the location. /// The identifier of the sensor, same as the location.
@@ -25,9 +26,6 @@ public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @
/// The topics to listen for updated sensor values. /// The topics to listen for updated sensor values.
public let topics: Topics public let topics: Topics
/// The psychrometric units of the sensor.
public let units: PsychrometricEnvironment.Units
/// Create a new temperature and humidity sensor. /// Create a new temperature and humidity sensor.
/// ///
/// - Parameters: /// - Parameters:
@@ -36,21 +34,18 @@ public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @
/// - temperature: The current temperature value of the sensor. /// - temperature: The current temperature value of the sensor.
/// - humidity: The current relative humidity value of the sensor. /// - humidity: The current relative humidity value of the sensor.
/// - needsProcessed: If the sensor needs to be processed. /// - needsProcessed: If the sensor needs to be processed.
/// - units: The unit of measure for the sensor.
public init( public init(
location: Location, location: Location,
altitude: Length = .feet(800.0), altitude: Length = .feet(800.0),
temperature: Temperature? = nil, temperature: Temperature? = nil,
humidity: RelativeHumidity? = nil, humidity: RelativeHumidity? = nil,
needsProcessed: Bool = false, needsProcessed: Bool = false,
units: PsychrometricEnvironment.Units = .imperial,
topics: Topics? = nil topics: Topics? = nil
) { ) {
self.altitude = altitude self.altitude = altitude
self.location = location self.location = location
self._temperature = TrackedChanges(wrappedValue: temperature, needsProcessed: needsProcessed) self._temperature = TrackedChanges(wrappedValue: temperature, needsProcessed: needsProcessed)
self._humidity = TrackedChanges(wrappedValue: humidity, needsProcessed: needsProcessed) self._humidity = TrackedChanges(wrappedValue: humidity, needsProcessed: needsProcessed)
self.units = units
self.topics = topics ?? .init(location: location) self.topics = topics ?? .init(location: location)
} }
@@ -61,7 +56,7 @@ public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @
!temperature.rawValue.isNaN, !temperature.rawValue.isNaN,
!humidity.rawValue.isNaN !humidity.rawValue.isNaN
else { return nil } else { return nil }
return .init(dryBulb: temperature, humidity: humidity, units: units) return .init(dryBulb: temperature, humidity: humidity)
} }
/// The calculated enthalpy of the sensor. /// The calculated enthalpy of the sensor.
@@ -71,7 +66,7 @@ public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @
!temperature.rawValue.isNaN, !temperature.rawValue.isNaN,
!humidity.rawValue.isNaN !humidity.rawValue.isNaN
else { return nil } else { return nil }
return .init(dryBulb: temperature, humidity: humidity, altitude: altitude, units: units) return .init(dryBulb: temperature, humidity: humidity, altitude: altitude)
} }
/// Check whether any of the sensor values have changed and need processed. /// Check whether any of the sensor values have changed and need processed.

View File

@@ -1,6 +1,6 @@
import Foundation import Foundation
import Logging import Logging
@preconcurrency import Models import Models
@preconcurrency import MQTTNIO @preconcurrency import MQTTNIO
import NIO import NIO
import Psychrometrics import Psychrometrics
@@ -102,13 +102,12 @@ public actor SensorsService: Service {
// MARK: - Errors // MARK: - Errors
struct DecodingError: Error {} struct DecodingError: Error {}
struct MQTTClientNotConnected: Error {}
struct NotFoundError: Error {} struct NotFoundError: Error {}
struct SensorExists: Error {} struct SensorExists: Error {}
// MARK: - Helpers // MARK: - Helpers
struct MQTTClientNotConnected: Error {}
private extension TemperatureAndHumiditySensor.Topics { private extension TemperatureAndHumiditySensor.Topics {
func contains(_ topic: String) -> Bool { func contains(_ topic: String) -> Bool {
temperature == topic || humidity == topic temperature == topic || humidity == topic