From e77efe795ccfc182f84f8011f75858f7db27bbfc Mon Sep 17 00:00:00 2001 From: Christoph Hagen Date: Thu, 7 Sep 2023 14:05:41 +0200 Subject: [PATCH] Move socket operations to device manager --- Sources/App/DeviceManager.swift | 16 ++++++++++++++-- Sources/App/routes.swift | 10 ---------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/Sources/App/DeviceManager.swift b/Sources/App/DeviceManager.swift index 963a891..4950b9e 100644 --- a/Sources/App/DeviceManager.swift +++ b/Sources/App/DeviceManager.swift @@ -15,7 +15,7 @@ final class DeviceManager { private let remoteKey: Data /// Indicate that the socket is fully initialized with an authorized device - var deviceIsAuthenticated = false + private var deviceIsAuthenticated = false private var isOpeningNewConnection = false @@ -62,7 +62,7 @@ final class DeviceManager { // MARK: API - var deviceStatus: String { + private var deviceStatus: String { deviceIsConnected ? "1" : "0" } @@ -148,6 +148,18 @@ final class DeviceManager { func createNewDeviceConnection(_ socket: WebSocket) { defer { updateDeviceConnectionMetric() } + + socket.onBinary { _, data in + self.processDeviceResponse(data) + } + socket.onText { _, text in + self.authenticateDevice(hash: text) + } + + _ = socket.onClose.always { _ in + self.didCloseDeviceSocket() + } + isOpeningNewConnection = true removeDeviceConnection() connection = socket diff --git a/Sources/App/routes.swift b/Sources/App/routes.swift index f61f062..c9e6f96 100755 --- a/Sources/App/routes.swift +++ b/Sources/App/routes.swift @@ -76,16 +76,6 @@ func routes(_ app: Application) throws { - Note: The first message from the device over the connection must be a valid auth token. */ app.webSocket(RouteAPI.socket.path) { req, socket in - socket.onBinary { _, data in - deviceManager.processDeviceResponse(data) - } - socket.onText { _, text in - deviceManager.authenticateDevice(hash: text) - } - - _ = socket.onClose.always { _ in - deviceManager.didCloseDeviceSocket() - } deviceManager.createNewDeviceConnection(socket) } }