2022-01-24 17:17:06 +01:00
|
|
|
import Foundation
|
|
|
|
import WebSocketKit
|
|
|
|
import Vapor
|
2023-02-06 21:57:42 +01:00
|
|
|
import Clairvoyant
|
2022-01-24 17:17:06 +01:00
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
enum DeviceState: UInt8 {
|
|
|
|
|
|
|
|
case disconnected = 0
|
|
|
|
case connected = 1
|
|
|
|
case authenticated = 2
|
|
|
|
}
|
|
|
|
|
|
|
|
extension DeviceState: MetricValue {
|
|
|
|
|
|
|
|
static let valueType: MetricType = .customType(named: "DeviceState")
|
|
|
|
}
|
|
|
|
|
2022-04-07 23:53:25 +02:00
|
|
|
final class DeviceManager {
|
2022-01-24 17:17:06 +01:00
|
|
|
|
|
|
|
/// The connection to the device
|
|
|
|
private var connection: WebSocket?
|
2022-04-07 23:53:25 +02:00
|
|
|
|
|
|
|
/// The authentication token of the device for the socket connection
|
2022-05-01 13:28:06 +02:00
|
|
|
private let deviceKey: Data
|
2022-04-07 23:53:25 +02:00
|
|
|
|
2022-05-01 13:12:16 +02:00
|
|
|
/// The authentication token of the remote
|
|
|
|
private let remoteKey: Data
|
|
|
|
|
2022-04-07 23:53:25 +02:00
|
|
|
/// Indicate that the socket is fully initialized with an authorized device
|
2023-09-07 14:05:41 +02:00
|
|
|
private var deviceIsAuthenticated = false
|
2022-04-08 23:38:22 +02:00
|
|
|
|
2023-01-31 19:10:33 +01:00
|
|
|
private let deviceTimeout: Int64
|
2023-02-06 21:57:42 +01:00
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
private let deviceStateMetric: Metric<DeviceState>
|
2023-02-06 21:57:42 +01:00
|
|
|
|
|
|
|
private let messagesToDeviceMetric: Metric<Int>
|
2022-01-24 17:17:06 +01:00
|
|
|
|
2023-11-08 10:24:50 +01:00
|
|
|
private let scheduler: AsyncScheduler
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
var deviceState: DeviceState {
|
|
|
|
guard let connection, !connection.isClosed else {
|
|
|
|
return .disconnected
|
|
|
|
}
|
|
|
|
guard deviceIsAuthenticated else {
|
|
|
|
return .connected
|
|
|
|
}
|
|
|
|
return .authenticated
|
|
|
|
}
|
|
|
|
|
2022-01-24 17:17:06 +01:00
|
|
|
/// Indicator for device availability
|
|
|
|
var deviceIsConnected: Bool {
|
2022-04-08 23:38:22 +02:00
|
|
|
deviceIsAuthenticated && !(connection?.isClosed ?? true)
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
|
2022-04-07 23:53:25 +02:00
|
|
|
/// A promise to finish the request once the device responds or times out
|
2023-11-10 13:45:42 +01:00
|
|
|
private var requestInProgress: CheckedContinuation<Data, Error>?
|
2022-01-24 17:17:06 +01:00
|
|
|
|
2023-11-08 10:24:50 +01:00
|
|
|
init(deviceKey: Data, remoteKey: Data, deviceTimeout: Int64, scheduler: AsyncScheduler) {
|
2022-01-24 17:17:06 +01:00
|
|
|
self.deviceKey = deviceKey
|
2022-05-01 13:12:16 +02:00
|
|
|
self.remoteKey = remoteKey
|
2023-01-31 19:10:33 +01:00
|
|
|
self.deviceTimeout = deviceTimeout
|
2023-11-10 13:45:42 +01:00
|
|
|
self.deviceStateMetric = .init(
|
|
|
|
"sesame.device",
|
2023-02-06 21:57:42 +01:00
|
|
|
name: "Device connected",
|
|
|
|
description: "Shows if the device is connected via WebSocket")
|
2023-10-01 19:26:31 +02:00
|
|
|
self.messagesToDeviceMetric = .init(
|
2023-02-06 21:57:42 +01:00
|
|
|
"sesame.messages",
|
|
|
|
name: "Forwarded Messages",
|
|
|
|
description: "The number of messages transmitted to the device")
|
2023-11-08 10:24:50 +01:00
|
|
|
self.scheduler = scheduler
|
2023-02-06 21:57:42 +01:00
|
|
|
}
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
private func updateDeviceConnectionMetric() async {
|
|
|
|
_ = try? await deviceStateMetric.update(deviceState)
|
2023-02-06 21:57:42 +01:00
|
|
|
}
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
private func updateMessageCountMetric() async {
|
|
|
|
let lastValue = await messagesToDeviceMetric.lastValue()?.value ?? 0
|
|
|
|
_ = try? await messagesToDeviceMetric.update(lastValue + 1)
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: API
|
|
|
|
|
2023-09-07 14:05:41 +02:00
|
|
|
private var deviceStatus: String {
|
2023-11-10 13:45:42 +01:00
|
|
|
"\(deviceState.rawValue)"
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
func sendMessageToDevice(_ message: Data, on eventLoop: EventLoop) async throws -> Data {
|
2022-01-24 17:17:06 +01:00
|
|
|
guard let socket = connection, !socket.isClosed else {
|
|
|
|
connection = nil
|
2023-11-10 13:45:42 +01:00
|
|
|
throw MessageResult.deviceNotConnected
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
2022-04-07 23:53:25 +02:00
|
|
|
guard requestInProgress == nil else {
|
2023-11-10 13:45:42 +01:00
|
|
|
throw MessageResult.operationInProgress
|
2022-04-07 23:53:25 +02:00
|
|
|
}
|
2023-11-10 13:45:42 +01:00
|
|
|
do {
|
|
|
|
try await socket.send(Array(message))
|
|
|
|
await updateMessageCountMetric()
|
|
|
|
} catch {
|
|
|
|
throw MessageResult.deviceNotConnected
|
|
|
|
}
|
|
|
|
startTimeoutForDeviceRequest(on: eventLoop)
|
|
|
|
|
|
|
|
let result: Data = try await withCheckedThrowingContinuation { continuation in
|
|
|
|
self.requestInProgress = continuation
|
|
|
|
}
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
private func startTimeoutForDeviceRequest(on eventLoop: EventLoop) {
|
2023-01-31 19:10:33 +01:00
|
|
|
eventLoop.scheduleTask(in: .seconds(deviceTimeout)) { [weak self] in
|
2023-11-10 13:45:42 +01:00
|
|
|
self?.resumeDeviceRequest(with: .deviceTimedOut)
|
2022-01-29 10:26:30 +01:00
|
|
|
}
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
private func resumeDeviceRequest(with data: Data) {
|
|
|
|
requestInProgress?.resume(returning: data)
|
|
|
|
requestInProgress = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
private func resumeDeviceRequest(with result: MessageResult) {
|
|
|
|
requestInProgress?.resume(throwing: result)
|
|
|
|
requestInProgress = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func authenticateDevice(hash: String) async {
|
2022-05-01 13:28:06 +02:00
|
|
|
guard let key = Data(fromHexEncodedString: hash),
|
|
|
|
SHA256.hash(data: key) == self.deviceKey else {
|
2023-02-06 21:44:56 +01:00
|
|
|
log("Invalid device key")
|
2023-11-10 13:45:42 +01:00
|
|
|
await removeDeviceConnection()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
guard let connection, !connection.isClosed else {
|
|
|
|
await updateDeviceConnectionMetric()
|
2022-01-24 17:17:06 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
deviceIsAuthenticated = true
|
2023-11-10 13:45:42 +01:00
|
|
|
await updateDeviceConnectionMetric()
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
|
2022-05-01 13:12:16 +02:00
|
|
|
func authenticateRemote(_ token: Data) -> Bool {
|
|
|
|
let hash = SHA256.hash(data: token)
|
|
|
|
return hash == remoteKey
|
|
|
|
}
|
|
|
|
|
2023-08-08 16:32:25 +02:00
|
|
|
func processDeviceResponse(_ buffer: ByteBuffer) {
|
|
|
|
guard let data = buffer.getData(at: 0, length: buffer.readableBytes) else {
|
|
|
|
log("Failed to get data buffer received from device")
|
2023-11-10 13:45:42 +01:00
|
|
|
self.resumeDeviceRequest(with: .invalidDeviceResponse)
|
2023-08-08 16:32:25 +02:00
|
|
|
return
|
|
|
|
}
|
2023-11-10 13:45:42 +01:00
|
|
|
self.resumeDeviceRequest(with: data)
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func didCloseDeviceSocket() {
|
|
|
|
deviceIsAuthenticated = false
|
|
|
|
connection = nil
|
|
|
|
}
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
func removeDeviceConnection() async {
|
|
|
|
try? await connection?.close()
|
2022-01-24 17:17:06 +01:00
|
|
|
connection = nil
|
2023-11-10 13:45:42 +01:00
|
|
|
deviceIsAuthenticated = false
|
|
|
|
await updateDeviceConnectionMetric()
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
func createNewDeviceConnection(_ socket: WebSocket) async {
|
|
|
|
await removeDeviceConnection()
|
2023-09-07 14:05:41 +02:00
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
socket.onBinary { [weak self] _, data in
|
|
|
|
self?.processDeviceResponse(data)
|
2023-09-07 14:05:41 +02:00
|
|
|
}
|
2023-11-10 13:45:42 +01:00
|
|
|
socket.onText { [weak self] _, text async in
|
|
|
|
await self?.authenticateDevice(hash: text)
|
2023-09-07 14:05:41 +02:00
|
|
|
}
|
|
|
|
|
2023-11-10 13:45:42 +01:00
|
|
|
_ = socket.onClose.always { [weak self] _ in
|
|
|
|
self?.didCloseDeviceSocket()
|
2023-09-07 14:05:41 +02:00
|
|
|
}
|
|
|
|
|
2022-01-24 17:17:06 +01:00
|
|
|
connection = socket
|
2023-11-10 13:45:42 +01:00
|
|
|
await updateDeviceConnectionMetric()
|
2022-01-24 17:17:06 +01:00
|
|
|
}
|
|
|
|
}
|