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
let swiftSettings: [SwiftSetting] = [
.enableExperimentalFeature("StrictConcurrency")
]
let package = Package(
name: "dewPoint-controller",
platforms: [
@@ -47,7 +51,8 @@ let package = Package(
"Models",
.product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "NIO", package: "swift-nio")
]
],
swiftSettings: swiftSettings
),
.target(
name: "DewPointEnvironment",
@@ -56,17 +61,20 @@ let package = Package(
"Client",
"Models",
.product(name: "MQTTNIO", package: "mqtt-nio")
]
],
swiftSettings: swiftSettings
),
.target(
name: "EnvVars",
dependencies: []
dependencies: [],
swiftSettings: swiftSettings
),
.target(
name: "Models",
dependencies: [
.product(name: "Psychrometrics", package: "swift-psychrometrics")
]
],
swiftSettings: swiftSettings
),
.target(
name: "Client",
@@ -75,7 +83,8 @@ let package = Package(
.product(name: "CoreUnitTypes", package: "swift-psychrometrics"),
.product(name: "NIO", package: "swift-nio"),
.product(name: "Psychrometrics", package: "swift-psychrometrics")
]
],
swiftSettings: swiftSettings
),
.target(
name: "ClientLive",
@@ -84,7 +93,8 @@ let package = Package(
"EnvVars",
.product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle")
]
],
swiftSettings: swiftSettings
),
.testTarget(
name: "ClientTests",
@@ -94,10 +104,13 @@ let package = Package(
]
),
.target(
name: "TopicsLive",
name: "MQTTConnectionService",
dependencies: [
"Models"
]
"EnvVars",
.product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle")
],
swiftSettings: swiftSettings
),
.target(
name: "SensorsService",
@@ -105,7 +118,8 @@ let package = Package(
"Models",
.product(name: "MQTTNIO", package: "mqtt-nio"),
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle")
]
],
swiftSettings: swiftSettings
),
.testTarget(
name: "SensorsServiceTests",
@@ -114,6 +128,13 @@ let package = Package(
// TODO: Remove.
"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
/// the dew-point temperature and enthalpy values.
///
/// > Note: Temperature values are received in `celsius`.
public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @unchecked Sendable {
/// 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.
public let topics: Topics
/// The psychrometric units of the sensor.
public let units: PsychrometricEnvironment.Units
/// Create a new temperature and humidity sensor.
///
/// - Parameters:
@@ -36,21 +34,18 @@ public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @
/// - temperature: The current temperature value of the sensor.
/// - humidity: The current relative humidity value of the sensor.
/// - needsProcessed: If the sensor needs to be processed.
/// - units: The unit of measure for the sensor.
public init(
location: Location,
altitude: Length = .feet(800.0),
temperature: Temperature? = nil,
humidity: RelativeHumidity? = nil,
needsProcessed: Bool = false,
units: PsychrometricEnvironment.Units = .imperial,
topics: Topics? = nil
) {
self.altitude = altitude
self.location = location
self._temperature = TrackedChanges(wrappedValue: temperature, needsProcessed: needsProcessed)
self._humidity = TrackedChanges(wrappedValue: humidity, needsProcessed: needsProcessed)
self.units = units
self.topics = topics ?? .init(location: location)
}
@@ -61,7 +56,7 @@ public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @
!temperature.rawValue.isNaN,
!humidity.rawValue.isNaN
else { return nil }
return .init(dryBulb: temperature, humidity: humidity, units: units)
return .init(dryBulb: temperature, humidity: humidity)
}
/// The calculated enthalpy of the sensor.
@@ -71,7 +66,7 @@ public struct TemperatureAndHumiditySensor: Equatable, Hashable, Identifiable, @
!temperature.rawValue.isNaN,
!humidity.rawValue.isNaN
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.

View File

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