SEND_HEX.ps1 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. param(
  2. [Parameter(Mandatory = $true)][string]$Hex,
  3. [string]$Port = "COM5",
  4. [int]$Baud = 921600,
  5. [int]$TimeoutMs = 750
  6. )
  7. Set-StrictMode -Version Latest
  8. $ErrorActionPreference = "Stop"
  9. function Convert-HexToBytes([string]$Value) {
  10. $normalized = ($Value -replace '[^0-9A-Fa-f]', '').ToUpperInvariant()
  11. if (-not $normalized -or ($normalized.Length % 2) -ne 0) {
  12. throw "Hex must contain a nonempty even number of hexadecimal digits"
  13. }
  14. $bytes = [byte[]]::new($normalized.Length / 2)
  15. for ($index = 0; $index -lt $bytes.Length; $index++) {
  16. $bytes[$index] = [Convert]::ToByte($normalized.Substring($index * 2, 2), 16)
  17. }
  18. return $bytes
  19. }
  20. function Convert-BytesToHex([byte[]]$Bytes) {
  21. return (($Bytes | ForEach-Object { "{0:X2}" -f $_ }) -join '')
  22. }
  23. function Get-Crc16([byte[]]$Bytes, [int]$Offset, [int]$Count) {
  24. [uint32]$crc = 0xFFFF
  25. for ($index = 0; $index -lt $Count; $index++) {
  26. $crc = ($crc -bxor ([uint32]$Bytes[$Offset + $index] -shl 8)) -band 0xFFFF
  27. for ($bit = 0; $bit -lt 8; $bit++) {
  28. if (($crc -band 0x8000) -ne 0) {
  29. $crc = (($crc -shl 1) -bxor 0x1021) -band 0xFFFF
  30. } else {
  31. $crc = ($crc -shl 1) -band 0xFFFF
  32. }
  33. }
  34. }
  35. return [uint16]$crc
  36. }
  37. function Convert-BinaryFrames([byte[]]$Bytes, [string]$Label) {
  38. $frames = [System.Collections.Generic.List[object]]::new()
  39. $offset = 0
  40. while ($offset -lt $Bytes.Length) {
  41. $remaining = $Bytes.Length - $offset
  42. if ($remaining -lt 16) {
  43. throw "$Label truncated frame"
  44. }
  45. if ($Bytes[$offset] -ne 0xA5 -or $Bytes[$offset + 1] -ne 0x5A) {
  46. throw "$Label envelope mismatch: magic"
  47. }
  48. if ($Bytes[$offset + 2] -ne 2) {
  49. throw "$Label envelope mismatch: version"
  50. }
  51. if ($Bytes[$offset + 3] -ne 4) {
  52. throw "$Label envelope mismatch: profile"
  53. }
  54. for ($index = 5; $index -le 8; $index++) {
  55. if ($Bytes[$offset + $index] -ne 0) {
  56. throw "$Label envelope mismatch: seq must be zero"
  57. }
  58. }
  59. for ($index = 9; $index -le 12; $index++) {
  60. if ($Bytes[$offset + $index] -ne 0) {
  61. throw "$Label envelope mismatch: timestamp must be zero"
  62. }
  63. }
  64. $payloadLength = [int]$Bytes[$offset + 13]
  65. $frameLength = 16 + $payloadLength
  66. if ($remaining -lt $frameLength) {
  67. throw "$Label truncated frame"
  68. }
  69. $frame = [byte[]]::new($frameLength)
  70. [Array]::Copy($Bytes, $offset, $frame, 0, $frameLength)
  71. $expectedCrc = Get-Crc16 $frame 2 ($frameLength - 4)
  72. $actualCrc = [uint16]([uint32]$frame[$frameLength - 2] -bor ([uint32]$frame[$frameLength - 1] -shl 8))
  73. if ($actualCrc -ne $expectedCrc) {
  74. throw "$Label CRC mismatch"
  75. }
  76. $payload = [byte[]]::new($payloadLength)
  77. if ($payloadLength -gt 0) {
  78. [Array]::Copy($frame, 14, $payload, 0, $payloadLength)
  79. }
  80. [void]$frames.Add([pscustomobject]@{
  81. Type = [int]$frame[4]
  82. PayloadLength = $payloadLength
  83. Payload = $payload
  84. Raw = $frame
  85. })
  86. $offset += $frameLength
  87. }
  88. return $frames.ToArray()
  89. }
  90. function Get-RequestOpcode([byte[]]$Request) {
  91. $requestFrames = @(Convert-BinaryFrames -Bytes $Request -Label "Request")
  92. if ($requestFrames.Count -ne 1) {
  93. throw "Request must contain exactly one binary921-v3 frame"
  94. }
  95. $requestFrame = $requestFrames[0]
  96. if ($requestFrame.Type -notin @(0x05, 0x07, 0x11)) {
  97. throw ("Request frame type 0x{0:X2} is not a host request" -f $requestFrame.Type)
  98. }
  99. if ($requestFrame.PayloadLength -lt 1) {
  100. throw "Request payload has no command opcode"
  101. }
  102. return [int]$requestFrame.Payload[0]
  103. }
  104. function Get-ResponseTimeoutMs(
  105. [byte[]]$Request,
  106. [int]$RequestedTimeoutMs
  107. ) {
  108. if ($RequestedTimeoutMs -le 0) {
  109. throw "RequestedTimeoutMs must be positive"
  110. }
  111. $opcode = Get-RequestOpcode -Request $Request
  112. if ($opcode -eq 0x35) {
  113. return [Math]::Max($RequestedTimeoutMs, 3000)
  114. }
  115. return $RequestedTimeoutMs
  116. }
  117. function Get-StatusName([int]$Status) {
  118. switch ($Status) {
  119. 0x00 { return "OK" }
  120. 0x01 { return "UNSUPPORTED_IN_PROFILE" }
  121. 0x02 { return "BAD_FLAGS" }
  122. 0x03 { return "BAD_LENGTH" }
  123. 0x05 { return "BAD_VALUE" }
  124. 0x09 { return "BUSY" }
  125. 0x16 { return "PARTIAL" }
  126. default { throw ("HOST_ACK contains unknown status 0x{0:X2}" -f $Status) }
  127. }
  128. }
  129. function Assert-ResponseContract([byte[]]$Request, [byte[]]$ResponseBytes) {
  130. $requestOpcode = Get-RequestOpcode -Request $Request
  131. $frames = @(Convert-BinaryFrames -Bytes $ResponseBytes -Label "Response")
  132. if ($frames.Count -eq 0) {
  133. throw "Missing HOST_ACK"
  134. }
  135. if ($frames[0].Type -ne 0x06) {
  136. throw "First response is not HOST_ACK"
  137. }
  138. $ackFrame = $frames[0]
  139. if ($ackFrame.PayloadLength -ne 8) {
  140. throw ("HOST_ACK payload length must be 8, got {0}" -f $ackFrame.PayloadLength)
  141. }
  142. $ackPayload = $ackFrame.Payload
  143. if ($ackPayload[0] -notin @(0, 1)) {
  144. throw "HOST_ACK ok must be 0 or 1"
  145. }
  146. $ackOk = $ackPayload[0] -eq 1
  147. $ackCommand = [int]$ackPayload[1]
  148. if ($ackCommand -ne $requestOpcode) {
  149. throw ("ACK command mismatch: requested 0x{0:X2}, received 0x{1:X2}" -f $requestOpcode, $ackCommand)
  150. }
  151. $statusValue = [int]$ackPayload[2]
  152. $statusName = Get-StatusName -Status $statusValue
  153. $acceptedStatus = $statusValue -in @(0x00, 0x16)
  154. if ($ackOk -ne $acceptedStatus) {
  155. throw ("ACK ok/status mismatch: ok={0}, status={1}" -f ([int]$ackOk), $statusName)
  156. }
  157. if (-not $ackOk) {
  158. throw ("Device rejected command 0x{0:X2}: {1} (0x{2:X2})" -f $requestOpcode, $statusName, $statusValue)
  159. }
  160. $responseType = [int]$ackPayload[6]
  161. $resultFlags = [int]$ackPayload[7]
  162. if ($requestOpcode -eq 0x37) {
  163. if ($frames.Count -ne 2 -or $frames[1].Type -ne 0x12) {
  164. throw "GET_MOTOR_STATUS must receive exactly HOST_ACK then MOTION_STATUS"
  165. }
  166. if ($responseType -ne 0x12) {
  167. throw "GET_MOTOR_STATUS ACK response type mismatch"
  168. }
  169. if ($resultFlags -ne 0x08) {
  170. throw "GET_MOTOR_STATUS ACK result flags mismatch"
  171. }
  172. if ($frames[1].PayloadLength -ne 10) {
  173. throw ("MOTION_STATUS payload length must be 10, got {0}" -f $frames[1].PayloadLength)
  174. }
  175. } else {
  176. if ($frames.Count -ne 1) {
  177. throw "Ordinary command must receive exactly one HOST_ACK"
  178. }
  179. if ($responseType -ne 0) {
  180. throw "Ordinary HOST_ACK response type must be zero"
  181. }
  182. }
  183. $frameResults = @(
  184. foreach ($frame in $frames) {
  185. [ordered]@{
  186. type = ("0x{0:X2}" -f $frame.Type)
  187. payload_length = $frame.PayloadLength
  188. hex = Convert-BytesToHex $frame.Raw
  189. }
  190. }
  191. )
  192. return [ordered]@{
  193. status = "pass"
  194. request_opcode = ("0x{0:X2}" -f $requestOpcode)
  195. ack = [ordered]@{
  196. ok = $ackOk
  197. command = ("0x{0:X2}" -f $ackCommand)
  198. status = $statusName
  199. status_code = ("0x{0:X2}" -f $statusValue)
  200. detail = ("0x{0:X2}" -f [int]$ackPayload[3])
  201. state_hash16 = ("0x{0:X4}" -f ([uint16]([uint32]$ackPayload[4] -bor ([uint32]$ackPayload[5] -shl 8))))
  202. response_type = ("0x{0:X2}" -f $responseType)
  203. result_flags = ("0x{0:X2}" -f $resultFlags)
  204. }
  205. frames = $frameResults
  206. }
  207. }
  208. # SEND_HEX_RUNTIME_START
  209. $request = Convert-HexToBytes $Hex
  210. $effectiveTimeoutMs = Get-ResponseTimeoutMs `
  211. -Request $request `
  212. -RequestedTimeoutMs $TimeoutMs
  213. $serial = [System.IO.Ports.SerialPort]::new($Port, $Baud, "None", 8, "One")
  214. $serial.Handshake = "None"
  215. $serial.DtrEnable = $false
  216. $serial.RtsEnable = $false
  217. $serial.ReadTimeout = 25
  218. $serial.WriteTimeout = 250
  219. $buffer = [System.Collections.Generic.List[byte]]::new()
  220. $deadline = [DateTime]::UtcNow.AddMilliseconds($effectiveTimeoutMs)
  221. $quietDeadline = $null
  222. try {
  223. $serial.Open()
  224. $serial.DiscardInBuffer()
  225. $serial.DiscardOutBuffer()
  226. $serial.Write($request, 0, $request.Length)
  227. while ([DateTime]::UtcNow -lt $deadline) {
  228. $available = $serial.BytesToRead
  229. if ($available -gt 0) {
  230. $chunk = [byte[]]::new($available)
  231. $read = $serial.Read($chunk, 0, $chunk.Length)
  232. for ($index = 0; $index -lt $read; $index++) {
  233. $buffer.Add($chunk[$index])
  234. }
  235. $quietDeadline = [DateTime]::UtcNow.AddMilliseconds(30)
  236. } elseif ($null -ne $quietDeadline -and [DateTime]::UtcNow -ge $quietDeadline) {
  237. break
  238. } else {
  239. Start-Sleep -Milliseconds 1
  240. }
  241. }
  242. } finally {
  243. if ($serial.IsOpen) {
  244. $serial.Close()
  245. }
  246. $serial.Dispose()
  247. }
  248. if ($buffer.Count -eq 0) {
  249. throw "HOST_ACK timeout"
  250. }
  251. $response = $buffer.ToArray()
  252. $result = Assert-ResponseContract -Request $request -ResponseBytes $response
  253. [ordered]@{
  254. status = $result.status
  255. port = $Port
  256. baud = $Baud
  257. effective_timeout_ms = $effectiveTimeoutMs
  258. request_hex = Convert-BytesToHex $request
  259. request_opcode = $result.request_opcode
  260. ack = $result.ack
  261. frames = $result.frames
  262. } | ConvertTo-Json -Depth 6