Sesame-Server/Sources/App/DeviceResponse.swift

66 lines
1.6 KiB
Swift
Raw Normal View History

2022-04-07 23:53:25 +02:00
import Foundation
import NIOCore
struct DeviceResponse {
static var deviceTimedOut: DeviceResponse {
.init(event: .deviceTimedOut)
}
static var deviceNotConnected: DeviceResponse {
.init(event: .deviceNotConnected)
}
static var unexpectedSocketEvent: DeviceResponse {
.init(event: .unexpectedSocketEvent)
}
static var invalidMessageData: DeviceResponse {
.init(event: .invalidMessageData)
}
static var noBodyData: DeviceResponse {
.init(event: .noBodyData)
}
static var operationInProgress: DeviceResponse {
.init(event: .operationInProgress)
}
2022-04-07 23:53:25 +02:00
/// The response to a key from the server
let event: MessageResult
/// The index of the next key to use
let response: Message?
init?(_ buffer: ByteBuffer) {
guard let byte = buffer.getBytes(at: 0, length: 1) else {
2022-04-07 23:53:25 +02:00
print("No bytes received from device")
return nil
}
guard let event = MessageResult(rawValue: byte[0]) else {
print("Unknown response \(byte[0]) received from device")
return nil
}
self.event = event
guard let data = buffer.getSlice(at: 1, length: Message.length) else {
self.response = nil
return
}
self.response = Message(decodeFrom: data)
}
init(event: MessageResult) {
self.event = event
self.response = nil
}
var encoded: Data {
guard let message = response else {
return Data([event.rawValue])
}
return Data([event.rawValue]) + message.encoded
}
}