FPGA_WebLab/server/udpProtocol.ts

94 lines
2.3 KiB
TypeScript

import { type } from "./common";
import { z } from "zod";
import _ from "lodash";
export namespace SendProtocol {
const CMD_BURST_TYPE = 0b1100_0000
const CMD_TASK_ID = 0b0011_0000
const CMD_READ_WRITE_TYPE = 0b0000_0001
const AddrPackageOptionsSchema = z.object({
burstType: z.enum(["Fixed", "Extend"]),
taskID: z.number().nonnegative().lt(4),
readWriteType: z.enum(["r", "w"])
})
export type AddrPackageOptions = z.infer<typeof AddrPackageOptionsSchema>
export function isAddrPackageOptions(obj: any): obj is AddrPackageOptions {
return AddrPackageOptionsSchema.safeParse(obj).success
}
export class AddrPackage {
private ID: number = 0x00
private commandType: number = 0
private burstLength: number = 0
private _reserved: number = 0
private address: number = 0
constructor(options: AddrPackageOptions) {
this.setCommandType(options)
}
setCommandType(options: AddrPackageOptions) {
const validOptions = AddrPackageOptionsSchema.parse(options)
this.commandType =
}
setBurstLength(len: number) {
this.burstLength = len
}
setAddress(addr: number) {
this.address = addr
}
options(): AddrPackageOptions {
return {
burstType: type.numberMatch(this.commandType, CMD_BURST_TYPE, "Extend", "Fixed"),
readWriteType: type.numberMatch(this.commandType, CMD_READ_WRITE_TYPE, "w", "r")
}
}
toUint8Array(): Uint8Array {
var array = new Uint8Array(8)
array[0] = this.ID
array[1] = this.commandType
array[2] = this.burstLength
array[3] = this._reserved
let addressBytes = type.numberToBytes(this.address, 4)
array[4] = addressBytes[0]
array[5] = addressBytes[1]
array[6] = addressBytes[2]
array[7] = addressBytes[3]
return array
}
}
export class DataPackage {
private ID: number = 0xFF
private _reserved: number = 0
private body: Uint8Array
constructor(body: Uint8Array) {
this.body = body
}
toUint8Array(): Uint8Array {
var array = new Uint8Array(4 + this.body.length)
array[0] = this.ID
array.fill(this._reserved, 1, 4)
array.set(this.body, 4)
return array
}
}
}
export namespace ReceiveProcotol { }