Files
swift-mqtt-dewpoint/Sources/MQTTConnectionService/MQTTConnectionService.swift
2024-11-15 17:15:01 -05:00

38 lines
1.1 KiB
Swift

import Dependencies
import Logging
import Models
import MQTTManager
import ServiceLifecycle
public struct MQTTConnectionService: Service {
@Dependency(\.mqtt) var mqtt
private let logger: Logger?
public init(
logger: Logger? = nil
) {
self.logger = logger
}
/// The entry-point of the service which starts the connection
/// to the MQTT broker and handles graceful shutdown of the
/// connection.
public func run() async throws {
try await withGracefulShutdownHandler {
try await mqtt.connect()
for await event in try mqtt.connectionStream().cancelOnGracefulShutdown() {
// We don't really need to do anything with the events, so just logging
// for now. But we need to iterate on an async stream for the service to
// continue to run and handle graceful shutdowns.
logger?.trace("Received connection event: \(event)")
}
// when we reach here we are shutting down, so we shutdown
// the manager.
mqtt.shutdown()
} onGracefulShutdown: {
self.logger?.trace("Received graceful shutdown.")
}
}
}