Sesame-iOS/Sesame/API/DeviceResponse.swift

91 lines
2.5 KiB
Swift
Raw Normal View History

2022-04-09 17:43:33 +02:00
import Foundation
import NIOCore
2022-04-13 14:55:22 +02:00
/**
Encapsulates a response from a device.
*/
2022-04-09 17:43:33 +02:00
struct DeviceResponse {
2022-04-13 14:55:22 +02:00
/// Shorthand property for a timeout event.
2022-04-09 17:43:33 +02:00
static var deviceTimedOut: DeviceResponse {
.init(event: .deviceTimedOut)
}
2022-04-13 14:55:22 +02:00
/// Shorthand property for a disconnected event.
2022-04-09 17:43:33 +02:00
static var deviceNotConnected: DeviceResponse {
.init(event: .deviceNotConnected)
}
/// Shorthand property for a connected event.
static var deviceConnected: DeviceResponse {
.init(event: .deviceConnected)
}
2022-04-13 14:55:22 +02:00
/// Shorthand property for an unexpected socket event.
2022-04-09 17:43:33 +02:00
static var unexpectedSocketEvent: DeviceResponse {
.init(event: .unexpectedSocketEvent)
}
2022-04-13 14:55:22 +02:00
/// Shorthand property for an invalid message.
2022-04-09 17:43:33 +02:00
static var invalidMessageData: DeviceResponse {
.init(event: .invalidMessageData)
}
2022-04-13 14:55:22 +02:00
/// Shorthand property for missing body data.
2022-04-09 17:43:33 +02:00
static var noBodyData: DeviceResponse {
.init(event: .noBodyData)
}
2022-04-13 14:55:22 +02:00
/// Shorthand property for a busy connection
2022-04-09 17:43:33 +02:00
static var operationInProgress: DeviceResponse {
.init(event: .operationInProgress)
}
/// The response to a key from the server
let event: MessageResult
/// The index of the next key to use
let response: Message?
2022-04-13 14:55:22 +02:00
/**
Decode a message from a buffer.
The buffer must contain `Message.length+1` bytes. The first byte denotes the event type,
the remaining bytes contain the message.
- Parameter buffer: The buffer where the message bytes are stored
*/
2022-04-09 17:43:33 +02:00
init?(_ buffer: ByteBuffer) {
guard let byte = buffer.getBytes(at: 0, length: 1) else {
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)
}
2022-04-13 14:55:22 +02:00
/**
Create a response from an event without a message from the device.
- Parameter event: The response from the device.
*/
2022-04-09 17:43:33 +02:00
init(event: MessageResult) {
self.event = event
self.response = nil
}
2022-04-13 14:55:22 +02:00
/// Get the reponse encoded in bytes.
2022-04-09 17:43:33 +02:00
var encoded: Data {
guard let message = response else {
return Data([event.rawValue])
}
return Data([event.rawValue]) + message.encoded
}
}