91 lines
2.5 KiB
Swift
91 lines
2.5 KiB
Swift
//
|
|
// NoticeMessage.swift
|
|
// sdlan
|
|
//
|
|
// Created by 安礼成 on 2024/6/3.
|
|
//
|
|
|
|
import Foundation
|
|
import NIOCore
|
|
|
|
struct NoticeMessage {
|
|
enum InboundMessage {
|
|
case none
|
|
case upgradeMessage(prompt: String, address: String)
|
|
case alertMessage(alert: String)
|
|
case ip(ip: String)
|
|
}
|
|
|
|
static func decodeMessage(buffer: inout ByteBuffer) -> InboundMessage {
|
|
guard let type = buffer.readInteger(as: UInt8.self) else {
|
|
return .none
|
|
}
|
|
|
|
switch type {
|
|
case 0x01:
|
|
if let len0 = buffer.readInteger(as: UInt16.self),
|
|
let prompt = buffer.readString(length: Int(len0)),
|
|
let len1 = buffer.readInteger(as: UInt16.self),
|
|
let address = buffer.readString(length: Int(len1)) {
|
|
return .upgradeMessage(prompt: prompt, address: address)
|
|
}
|
|
case 0x02:
|
|
if let len0 = buffer.readInteger(as: UInt16.self),
|
|
let alert = buffer.readString(length: Int(len0)) {
|
|
return .alertMessage(alert: alert)
|
|
}
|
|
|
|
case 0x03:
|
|
if let len0 = buffer.readInteger(as: UInt16.self),
|
|
let ipAddress = buffer.readString(length: Int(len0)) {
|
|
return .ip(ip: ipAddress)
|
|
}
|
|
default:
|
|
return .none
|
|
}
|
|
|
|
return .none
|
|
}
|
|
|
|
static func upgrade(prompt: String, address: String) -> Data {
|
|
var data = Data()
|
|
data.append(contentsOf: [0x01])
|
|
|
|
data.append(contentsOf: lenBytes(UInt16(prompt.count)))
|
|
data.append(prompt.data(using: .utf8)!)
|
|
|
|
data.append(contentsOf: lenBytes(UInt16(address.count)))
|
|
data.append(address.data(using: .utf8)!)
|
|
|
|
return data
|
|
}
|
|
|
|
static func alert(alert: String) -> Data {
|
|
var data = Data()
|
|
data.append(contentsOf: [0x02])
|
|
|
|
data.append(contentsOf: lenBytes(UInt16(alert.count)))
|
|
data.append(alert.data(using: .utf8)!)
|
|
|
|
return data
|
|
}
|
|
|
|
static func ipAdress(ip: String) -> Data {
|
|
var data = Data()
|
|
data.append(contentsOf: [0x03])
|
|
|
|
data.append(contentsOf: lenBytes(UInt16(ip.count)))
|
|
data.append(ip.data(using: .utf8)!)
|
|
|
|
return data
|
|
}
|
|
|
|
private static func lenBytes(_ value: UInt16) -> [UInt8] {
|
|
let byte1 = UInt8((value >> 8) & 0xFF)
|
|
let bytes2 = UInt8(value & 0xFF)
|
|
|
|
return [byte1, bytes2]
|
|
}
|
|
|
|
}
|