66 lines
2.1 KiB
Swift
Executable File
66 lines
2.1 KiB
Swift
Executable File
import Vapor
|
|
|
|
extension PublicAPI {
|
|
|
|
var path: PathComponent {
|
|
.init(stringLiteral: rawValue)
|
|
}
|
|
|
|
var pathParameter: PathComponent {
|
|
.parameter(rawValue)
|
|
}
|
|
}
|
|
|
|
private func messageTransmission(_ req: Request) -> EventLoopFuture<DeviceResponse> {
|
|
guard let body = req.body.data else {
|
|
return req.eventLoop.makeSucceededFuture(.noBodyData)
|
|
}
|
|
guard let message = Message(decodeFrom: body) else {
|
|
return req.eventLoop.makeSucceededFuture(.invalidMessageData)
|
|
}
|
|
return deviceManager.sendMessageToDevice(message, on: req.eventLoop)
|
|
}
|
|
|
|
func routes(_ app: Application) throws {
|
|
|
|
/**
|
|
Get the connection status of the device.
|
|
|
|
The response is a string of either "1" (connected) or "0" (disconnected)
|
|
*/
|
|
app.get(PublicAPI.getDeviceStatus.path) { req -> String in
|
|
deviceManager.deviceStatus
|
|
}
|
|
|
|
/**
|
|
Post a key to the device for unlocking.
|
|
|
|
The request returns one or `Message.length+1` bytes of data, where the first byte is the raw value of a `MessageResult`,
|
|
and the optional following bytes contain the response message of the device. This request does not complete until either the device responds or the request times out. The timeout is specified by `KeyManagement.deviceTimeout`.
|
|
*/
|
|
app.post(PublicAPI.postMessage.path) { req in
|
|
messageTransmission(req).map {
|
|
Response(status: .ok, body: .init(data: $0.encoded))
|
|
}
|
|
}
|
|
|
|
/**
|
|
Start a new websocket connection for the client to receive table updates from the server
|
|
- Returns: Nothing
|
|
- Note: The first (and only) message from the client over the connection must be a valid session token.
|
|
*/
|
|
app.webSocket(PublicAPI.socket.path) { req, socket in
|
|
socket.onBinary { _, data in
|
|
deviceManager.processDeviceResponse(data)
|
|
}
|
|
socket.onText { _, text in
|
|
deviceManager.authenticateDevice(psk: text)
|
|
}
|
|
|
|
_ = socket.onClose.always { _ in
|
|
deviceManager.didCloseDeviceSocket()
|
|
}
|
|
deviceManager.createNewDeviceConnection(socket)
|
|
}
|
|
}
|