| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282 |
- param(
- [Parameter(Mandatory = $true)][string]$Hex,
- [string]$Port = "COM5",
- [int]$Baud = 921600,
- [int]$TimeoutMs = 750
- )
- Set-StrictMode -Version Latest
- $ErrorActionPreference = "Stop"
- function Convert-HexToBytes([string]$Value) {
- $normalized = ($Value -replace '[^0-9A-Fa-f]', '').ToUpperInvariant()
- if (-not $normalized -or ($normalized.Length % 2) -ne 0) {
- throw "Hex must contain a nonempty even number of hexadecimal digits"
- }
- $bytes = [byte[]]::new($normalized.Length / 2)
- for ($index = 0; $index -lt $bytes.Length; $index++) {
- $bytes[$index] = [Convert]::ToByte($normalized.Substring($index * 2, 2), 16)
- }
- return $bytes
- }
- function Convert-BytesToHex([byte[]]$Bytes) {
- return (($Bytes | ForEach-Object { "{0:X2}" -f $_ }) -join '')
- }
- function Get-Crc16([byte[]]$Bytes, [int]$Offset, [int]$Count) {
- [uint32]$crc = 0xFFFF
- for ($index = 0; $index -lt $Count; $index++) {
- $crc = ($crc -bxor ([uint32]$Bytes[$Offset + $index] -shl 8)) -band 0xFFFF
- for ($bit = 0; $bit -lt 8; $bit++) {
- if (($crc -band 0x8000) -ne 0) {
- $crc = (($crc -shl 1) -bxor 0x1021) -band 0xFFFF
- } else {
- $crc = ($crc -shl 1) -band 0xFFFF
- }
- }
- }
- return [uint16]$crc
- }
- function Convert-BinaryFrames([byte[]]$Bytes, [string]$Label) {
- $frames = [System.Collections.Generic.List[object]]::new()
- $offset = 0
- while ($offset -lt $Bytes.Length) {
- $remaining = $Bytes.Length - $offset
- if ($remaining -lt 16) {
- throw "$Label truncated frame"
- }
- if ($Bytes[$offset] -ne 0xA5 -or $Bytes[$offset + 1] -ne 0x5A) {
- throw "$Label envelope mismatch: magic"
- }
- if ($Bytes[$offset + 2] -ne 2) {
- throw "$Label envelope mismatch: version"
- }
- if ($Bytes[$offset + 3] -ne 4) {
- throw "$Label envelope mismatch: profile"
- }
- for ($index = 5; $index -le 8; $index++) {
- if ($Bytes[$offset + $index] -ne 0) {
- throw "$Label envelope mismatch: seq must be zero"
- }
- }
- for ($index = 9; $index -le 12; $index++) {
- if ($Bytes[$offset + $index] -ne 0) {
- throw "$Label envelope mismatch: timestamp must be zero"
- }
- }
- $payloadLength = [int]$Bytes[$offset + 13]
- $frameLength = 16 + $payloadLength
- if ($remaining -lt $frameLength) {
- throw "$Label truncated frame"
- }
- $frame = [byte[]]::new($frameLength)
- [Array]::Copy($Bytes, $offset, $frame, 0, $frameLength)
- $expectedCrc = Get-Crc16 $frame 2 ($frameLength - 4)
- $actualCrc = [uint16]([uint32]$frame[$frameLength - 2] -bor ([uint32]$frame[$frameLength - 1] -shl 8))
- if ($actualCrc -ne $expectedCrc) {
- throw "$Label CRC mismatch"
- }
- $payload = [byte[]]::new($payloadLength)
- if ($payloadLength -gt 0) {
- [Array]::Copy($frame, 14, $payload, 0, $payloadLength)
- }
- [void]$frames.Add([pscustomobject]@{
- Type = [int]$frame[4]
- PayloadLength = $payloadLength
- Payload = $payload
- Raw = $frame
- })
- $offset += $frameLength
- }
- return $frames.ToArray()
- }
- function Get-RequestOpcode([byte[]]$Request) {
- $requestFrames = @(Convert-BinaryFrames -Bytes $Request -Label "Request")
- if ($requestFrames.Count -ne 1) {
- throw "Request must contain exactly one binary921-v3 frame"
- }
- $requestFrame = $requestFrames[0]
- if ($requestFrame.Type -notin @(0x05, 0x07, 0x11)) {
- throw ("Request frame type 0x{0:X2} is not a host request" -f $requestFrame.Type)
- }
- if ($requestFrame.PayloadLength -lt 1) {
- throw "Request payload has no command opcode"
- }
- return [int]$requestFrame.Payload[0]
- }
- function Get-ResponseTimeoutMs(
- [byte[]]$Request,
- [int]$RequestedTimeoutMs
- ) {
- if ($RequestedTimeoutMs -le 0) {
- throw "RequestedTimeoutMs must be positive"
- }
- $opcode = Get-RequestOpcode -Request $Request
- if ($opcode -eq 0x35) {
- return [Math]::Max($RequestedTimeoutMs, 3000)
- }
- return $RequestedTimeoutMs
- }
- function Get-StatusName([int]$Status) {
- switch ($Status) {
- 0x00 { return "OK" }
- 0x01 { return "UNSUPPORTED_IN_PROFILE" }
- 0x02 { return "BAD_FLAGS" }
- 0x03 { return "BAD_LENGTH" }
- 0x05 { return "BAD_VALUE" }
- 0x09 { return "BUSY" }
- 0x16 { return "PARTIAL" }
- default { throw ("HOST_ACK contains unknown status 0x{0:X2}" -f $Status) }
- }
- }
- function Assert-ResponseContract([byte[]]$Request, [byte[]]$ResponseBytes) {
- $requestOpcode = Get-RequestOpcode -Request $Request
- $frames = @(Convert-BinaryFrames -Bytes $ResponseBytes -Label "Response")
- if ($frames.Count -eq 0) {
- throw "Missing HOST_ACK"
- }
- if ($frames[0].Type -ne 0x06) {
- throw "First response is not HOST_ACK"
- }
- $ackFrame = $frames[0]
- if ($ackFrame.PayloadLength -ne 8) {
- throw ("HOST_ACK payload length must be 8, got {0}" -f $ackFrame.PayloadLength)
- }
- $ackPayload = $ackFrame.Payload
- if ($ackPayload[0] -notin @(0, 1)) {
- throw "HOST_ACK ok must be 0 or 1"
- }
- $ackOk = $ackPayload[0] -eq 1
- $ackCommand = [int]$ackPayload[1]
- if ($ackCommand -ne $requestOpcode) {
- throw ("ACK command mismatch: requested 0x{0:X2}, received 0x{1:X2}" -f $requestOpcode, $ackCommand)
- }
- $statusValue = [int]$ackPayload[2]
- $statusName = Get-StatusName -Status $statusValue
- $acceptedStatus = $statusValue -in @(0x00, 0x16)
- if ($ackOk -ne $acceptedStatus) {
- throw ("ACK ok/status mismatch: ok={0}, status={1}" -f ([int]$ackOk), $statusName)
- }
- if (-not $ackOk) {
- throw ("Device rejected command 0x{0:X2}: {1} (0x{2:X2})" -f $requestOpcode, $statusName, $statusValue)
- }
- $responseType = [int]$ackPayload[6]
- $resultFlags = [int]$ackPayload[7]
- if ($requestOpcode -eq 0x37) {
- if ($frames.Count -ne 2 -or $frames[1].Type -ne 0x12) {
- throw "GET_MOTOR_STATUS must receive exactly HOST_ACK then MOTION_STATUS"
- }
- if ($responseType -ne 0x12) {
- throw "GET_MOTOR_STATUS ACK response type mismatch"
- }
- if ($resultFlags -ne 0x08) {
- throw "GET_MOTOR_STATUS ACK result flags mismatch"
- }
- if ($frames[1].PayloadLength -ne 10) {
- throw ("MOTION_STATUS payload length must be 10, got {0}" -f $frames[1].PayloadLength)
- }
- } else {
- if ($frames.Count -ne 1) {
- throw "Ordinary command must receive exactly one HOST_ACK"
- }
- if ($responseType -ne 0) {
- throw "Ordinary HOST_ACK response type must be zero"
- }
- }
- $frameResults = @(
- foreach ($frame in $frames) {
- [ordered]@{
- type = ("0x{0:X2}" -f $frame.Type)
- payload_length = $frame.PayloadLength
- hex = Convert-BytesToHex $frame.Raw
- }
- }
- )
- return [ordered]@{
- status = "pass"
- request_opcode = ("0x{0:X2}" -f $requestOpcode)
- ack = [ordered]@{
- ok = $ackOk
- command = ("0x{0:X2}" -f $ackCommand)
- status = $statusName
- status_code = ("0x{0:X2}" -f $statusValue)
- detail = ("0x{0:X2}" -f [int]$ackPayload[3])
- state_hash16 = ("0x{0:X4}" -f ([uint16]([uint32]$ackPayload[4] -bor ([uint32]$ackPayload[5] -shl 8))))
- response_type = ("0x{0:X2}" -f $responseType)
- result_flags = ("0x{0:X2}" -f $resultFlags)
- }
- frames = $frameResults
- }
- }
- # SEND_HEX_RUNTIME_START
- $request = Convert-HexToBytes $Hex
- $effectiveTimeoutMs = Get-ResponseTimeoutMs `
- -Request $request `
- -RequestedTimeoutMs $TimeoutMs
- $serial = [System.IO.Ports.SerialPort]::new($Port, $Baud, "None", 8, "One")
- $serial.Handshake = "None"
- $serial.DtrEnable = $false
- $serial.RtsEnable = $false
- $serial.ReadTimeout = 25
- $serial.WriteTimeout = 250
- $buffer = [System.Collections.Generic.List[byte]]::new()
- $deadline = [DateTime]::UtcNow.AddMilliseconds($effectiveTimeoutMs)
- $quietDeadline = $null
- try {
- $serial.Open()
- $serial.DiscardInBuffer()
- $serial.DiscardOutBuffer()
- $serial.Write($request, 0, $request.Length)
- while ([DateTime]::UtcNow -lt $deadline) {
- $available = $serial.BytesToRead
- if ($available -gt 0) {
- $chunk = [byte[]]::new($available)
- $read = $serial.Read($chunk, 0, $chunk.Length)
- for ($index = 0; $index -lt $read; $index++) {
- $buffer.Add($chunk[$index])
- }
- $quietDeadline = [DateTime]::UtcNow.AddMilliseconds(30)
- } elseif ($null -ne $quietDeadline -and [DateTime]::UtcNow -ge $quietDeadline) {
- break
- } else {
- Start-Sleep -Milliseconds 1
- }
- }
- } finally {
- if ($serial.IsOpen) {
- $serial.Close()
- }
- $serial.Dispose()
- }
- if ($buffer.Count -eq 0) {
- throw "HOST_ACK timeout"
- }
- $response = $buffer.ToArray()
- $result = Assert-ResponseContract -Request $request -ResponseBytes $response
- [ordered]@{
- status = $result.status
- port = $Port
- baud = $Baud
- effective_timeout_ms = $effectiveTimeoutMs
- request_hex = Convert-BytesToHex $request
- request_opcode = $result.request_opcode
- ack = $result.ack
- frames = $result.frames
- } | ConvertTo-Json -Depth 6
|