profile.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. package profile
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "math"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "hth/internal/ids"
  15. "hth/internal/protocol"
  16. )
  17. const SchemaID = "hth-device-profile-v1"
  18. type Range struct {
  19. Min float64 `json:"min"`
  20. Max float64 `json:"max"`
  21. }
  22. type Sensor struct {
  23. ID string `json:"id"`
  24. Aliases []string `json:"aliases"`
  25. DisplayName string `json:"display_name"`
  26. Kind string `json:"kind"`
  27. Unit string `json:"unit"`
  28. SourceIndex int `json:"source_index"`
  29. HoodID string `json:"hood_id"`
  30. ChamberID string `json:"chamber_id"`
  31. DIMMID string `json:"dimm_id"`
  32. Connector string `json:"connector"`
  33. ValidRange Range `json:"valid_range"`
  34. Resolution float64 `json:"resolution"`
  35. SourceTimestamp bool `json:"source_timestamp"`
  36. MappingConfidence string `json:"mapping_confidence"`
  37. CalibrationVersion string `json:"calibration_version"`
  38. FeedbackMode string `json:"feedback_mode"`
  39. Notes string `json:"notes"`
  40. }
  41. type Actuator struct {
  42. ID string `json:"id"`
  43. Aliases []string `json:"aliases"`
  44. DisplayName string `json:"display_name"`
  45. Kind string `json:"kind"`
  46. Unit string `json:"unit"`
  47. CommandRange Range `json:"command_range"`
  48. Resolution float64 `json:"resolution"`
  49. ControlMode string `json:"control_mode"`
  50. FeedbackMode string `json:"feedback_mode"`
  51. Idempotent bool `json:"idempotent"`
  52. OneShot bool `json:"one_shot"`
  53. SafetyDefault float64 `json:"safety_default"`
  54. MaxSlewPerSecond float64 `json:"max_slew_per_second"`
  55. ActualFeedback bool `json:"actual_feedback"`
  56. HoodID string `json:"hood_id"`
  57. ChamberID string `json:"chamber_id"`
  58. Connector string `json:"connector"`
  59. SetAllOffset int `json:"set_all_offset"`
  60. PhysicalPTCIndex []int `json:"physical_ptc_indices"`
  61. Notes string `json:"notes"`
  62. }
  63. type Honesty struct {
  64. FirmwareVersion string `json:"firmware_version"`
  65. FanRPM string `json:"fan_rpm"`
  66. PTCActualPower string `json:"ptc_actual_power"`
  67. EncoderPosition string `json:"encoder_position"`
  68. Ack bool `json:"ack"`
  69. DIMMTemperatureMap string `json:"dimm_temperature_map"`
  70. HardwareValidation string `json:"hardware_validation"`
  71. }
  72. type Safety struct {
  73. Fan int `json:"fan"`
  74. PTC int `json:"ptc"`
  75. DoorClosePercent int `json:"door_close_percent"`
  76. Notes string `json:"notes"`
  77. }
  78. type Watchdog struct {
  79. TimeoutSeconds int `json:"timeout_seconds"`
  80. FedBy string `json:"fed_by"`
  81. GetFeedsWatchdog bool `json:"get_feeds_watchdog"`
  82. EnableAfterStartupComplete bool `json:"enable_after_startup_complete"`
  83. Target struct {
  84. Fan int `json:"fan"`
  85. PTC int `json:"ptc"`
  86. } `json:"target"`
  87. HeartbeatRepeatsDoorPercent bool `json:"heartbeat_repeats_door_percent"`
  88. HeartbeatMustNotRewriteDoorsToZero bool `json:"heartbeat_must_not_rewrite_doors_to_zero"`
  89. HostHeartbeatPeriodMS int `json:"host_heartbeat_period_ms"`
  90. }
  91. type UART struct {
  92. Baud int `json:"baud"`
  93. DataBits int `json:"data_bits"`
  94. Parity string `json:"parity"`
  95. StopBits int `json:"stop_bits"`
  96. FlowControl string `json:"flow_control"`
  97. InterByteTimeoutMS int `json:"inter_byte_timeout_ms"`
  98. }
  99. type Timeouts struct {
  100. FrameInterByteMS int `json:"frame_inter_byte_ms"`
  101. HostGetResponseMS int `json:"host_get_response_ms"`
  102. TemperatureScanBusyMS int `json:"temperature_scan_busy_ms"`
  103. }
  104. type ProtocolSetAll struct {
  105. PayloadLength int `json:"payload_length"`
  106. FanOffset int `json:"fan_offset"`
  107. ChamberPTCOffset int `json:"chamber_ptc_offset"`
  108. ChamberPTCCount int `json:"chamber_ptc_count"`
  109. ZDoorOffset int `json:"z_door_offset"`
  110. XDoorOffset int `json:"x_door_offset"`
  111. YDoorOffset int `json:"y_door_offset"`
  112. LegacyPayloadLengthRejected int `json:"legacy_payload_length_rejected"`
  113. DutyMin int `json:"duty_min"`
  114. DutyMax int `json:"duty_max"`
  115. DoorPercentMin int `json:"door_percent_min"`
  116. DoorPercentMax int `json:"door_percent_max"`
  117. Response string `json:"response"`
  118. IdempotentSameTarget bool `json:"idempotent_same_target"`
  119. RetryPolicy string `json:"retry_policy"`
  120. }
  121. type CRC struct {
  122. Name string `json:"name"`
  123. Polynomial int `json:"polynomial"`
  124. Initial int `json:"initial"`
  125. ReflectInput bool `json:"reflect_input"`
  126. ReflectOutput bool `json:"reflect_output"`
  127. XorOutput int `json:"xor_output"`
  128. Coverage string `json:"coverage"`
  129. WireOrder string `json:"wire_order"`
  130. }
  131. type Protocol struct {
  132. HeaderHex string `json:"header_hex"`
  133. CRC CRC `json:"crc"`
  134. Ack bool `json:"ack"`
  135. StatusQuery bool `json:"status_query"`
  136. MaxPayloadLength int `json:"max_payload_length"`
  137. SetAll ProtocolSetAll `json:"set_all"`
  138. GetTemperature struct {
  139. PayloadLength int `json:"payload_length"`
  140. ResponsePayloadLength int `json:"response_payload_length"`
  141. } `json:"get_temperature"`
  142. GetMotorStatus struct {
  143. PayloadLength int `json:"payload_length"`
  144. ResponsePayloadLength int `json:"response_payload_length"`
  145. } `json:"get_motor_status"`
  146. Commands map[string]int `json:"commands"`
  147. }
  148. type Startup struct {
  149. GetTemperatureDropped bool `json:"get_temperature_dropped"`
  150. GetMotorStatusAllowed bool `json:"get_motor_status_allowed"`
  151. SetAllUpdatesThermalOnly bool `json:"set_all_updates_thermal_only"`
  152. DoorPercentIgnored bool `json:"door_percent_ignored"`
  153. ReadinessProbe string `json:"readiness_probe"`
  154. }
  155. type Temperature struct {
  156. ValueCount int `json:"value_count"`
  157. InvalidValue int `json:"invalid_value"`
  158. MaximumCelsius int `json:"maximum_celsius"`
  159. Unit string `json:"unit"`
  160. SourceTimestamp bool `json:"source_timestamp"`
  161. SequentialScan bool `json:"sequential_scan"`
  162. }
  163. type Motors struct {
  164. Order []string `json:"order"`
  165. ControlMode string `json:"control_mode"`
  166. PositionFeedback string `json:"position_feedback"`
  167. BusyReadable bool `json:"busy_readable"`
  168. PercentMin int `json:"percent_min"`
  169. PercentMax int `json:"percent_max"`
  170. OpenEndpointPercent int `json:"open_endpoint_percent"`
  171. CloseEndpointPercent int `json:"close_endpoint_percent"`
  172. }
  173. type Topology struct {
  174. HoodCount int `json:"hood_count"`
  175. ChamberCount int `json:"chamber_count"`
  176. DoorChamber int `json:"door_chamber"`
  177. }
  178. type Profile struct {
  179. Schema string `json:"schema"`
  180. ProfileID string `json:"profile_id"`
  181. ProfileRevision string `json:"profile_revision"`
  182. ProjectID string `json:"project_id"`
  183. APIVersion string `json:"api_version"`
  184. SourceContractSchema string `json:"source_contract_schema"`
  185. SourceContractSHA256 string `json:"source_contract_sha256"`
  186. SourceGoldenSHA256 string `json:"source_golden_sha256"`
  187. UART UART `json:"uart"`
  188. Protocol Protocol `json:"protocol"`
  189. Timeouts Timeouts `json:"timeouts"`
  190. Watchdog Watchdog `json:"watchdog"`
  191. Startup Startup `json:"startup"`
  192. Temperature Temperature `json:"temperature"`
  193. Motors Motors `json:"motors"`
  194. Topology Topology `json:"topology"`
  195. Safety Safety `json:"safety"`
  196. Sensors []Sensor `json:"sensors"`
  197. Actuators []Actuator `json:"actuators"`
  198. Honesty Honesty `json:"honesty"`
  199. GoldenVectors map[string]string `json:"golden_vectors"`
  200. GoldenNotes map[string]string `json:"golden_notes"`
  201. Path string `json:"-"`
  202. FileSHA256 string `json:"-"`
  203. Raw []byte `json:"-"`
  204. }
  205. func Load(path string) (*Profile, error) {
  206. return load(path, false)
  207. }
  208. func LoadStrict(path string) (*Profile, error) {
  209. return load(path, true)
  210. }
  211. func load(path string, strict bool) (*Profile, error) {
  212. raw, err := os.ReadFile(path)
  213. if err != nil {
  214. return nil, fmt.Errorf("profile: read %s: %w", path, err)
  215. }
  216. sum := sha256.Sum256(raw)
  217. if err := rejectDuplicateJSONKeys(raw); err != nil {
  218. return nil, fmt.Errorf("profile: %s: %w", path, err)
  219. }
  220. dec := json.NewDecoder(strings.NewReader(string(raw)))
  221. if strict {
  222. dec.DisallowUnknownFields()
  223. }
  224. var p Profile
  225. if err := dec.Decode(&p); err != nil {
  226. return nil, fmt.Errorf("profile: parse %s: %w", path, err)
  227. }
  228. var extra json.RawMessage
  229. if err := dec.Decode(&extra); err != io.EOF {
  230. if err == nil {
  231. return nil, fmt.Errorf("profile: trailing JSON after first object in %s", path)
  232. }
  233. return nil, fmt.Errorf("profile: trailing data after first object in %s: %w", path, err)
  234. }
  235. p.Path = path
  236. p.FileSHA256 = hex.EncodeToString(sum[:])
  237. p.Raw = raw
  238. if err := p.Validate(); err != nil {
  239. return nil, err
  240. }
  241. if strict {
  242. if err := p.ValidateProd2U(); err != nil {
  243. return nil, err
  244. }
  245. }
  246. return &p, nil
  247. }
  248. func (p *Profile) Validate() error {
  249. if p.Schema != SchemaID {
  250. return fmt.Errorf("profile: schema %q want %q", p.Schema, SchemaID)
  251. }
  252. if p.ProfileID == "" || p.ProfileRevision == "" {
  253. return fmt.Errorf("profile: missing profile_id/revision")
  254. }
  255. if p.Safety.Notes == "" {
  256. return fmt.Errorf("profile: safety.notes required (must document door 0 = full open)")
  257. }
  258. if p.Safety.Fan < 0 || p.Safety.Fan > 100 || p.Safety.PTC < 0 || p.Safety.PTC > 100 {
  259. return fmt.Errorf("profile: safety fan/ptc out of 0..100")
  260. }
  261. if p.Safety.DoorClosePercent < 0 || p.Safety.DoorClosePercent > 100 {
  262. return fmt.Errorf("profile: safety door_close_percent out of 0..100")
  263. }
  264. if p.Watchdog.TimeoutSeconds <= 0 {
  265. return fmt.Errorf("profile: watchdog.timeout_seconds required")
  266. }
  267. if p.Watchdog.GetFeedsWatchdog {
  268. return fmt.Errorf("profile: GET must not feed watchdog")
  269. }
  270. if !p.Watchdog.HeartbeatRepeatsDoorPercent || !p.Watchdog.HeartbeatMustNotRewriteDoorsToZero {
  271. return fmt.Errorf("profile: heartbeat must repeat real door percents and must not rewrite doors to 0")
  272. }
  273. if p.Protocol.Ack {
  274. return fmt.Errorf("profile: current Prod2U contract has no ACK")
  275. }
  276. if p.Protocol.SetAll.PayloadLength != protocol.SetAllPayloadLen {
  277. return fmt.Errorf("profile: SET_ALL payload_length want %d", protocol.SetAllPayloadLen)
  278. }
  279. if p.Protocol.SetAll.RetryPolicy != "never_when_outcome_unknown" {
  280. return fmt.Errorf("profile: retry_policy must be never_when_outcome_unknown")
  281. }
  282. if p.Temperature.ValueCount != protocol.TemperaturePayloadLen {
  283. return fmt.Errorf("profile: temperature.value_count want %d", protocol.TemperaturePayloadLen)
  284. }
  285. if p.Temperature.InvalidValue != int(protocol.TempInvalid) {
  286. return fmt.Errorf("profile: invalid_value must be 0xFF")
  287. }
  288. if p.Honesty.FirmwareVersion != "NOT_SUPPORTED" || p.Honesty.FanRPM != "NOT_SUPPORTED" ||
  289. p.Honesty.EncoderPosition != "NOT_SUPPORTED" || p.Honesty.PTCActualPower != "NOT_SUPPORTED" {
  290. return fmt.Errorf("profile: honesty must mark firmware/rpm/encoder/ptc actual as NOT_SUPPORTED")
  291. }
  292. if p.Honesty.DIMMTemperatureMap != "UNKNOWN" {
  293. return fmt.Errorf("profile: dimm map must be UNKNOWN")
  294. }
  295. for i := 0; i < p.Temperature.ValueCount; i++ {
  296. want := ids.TempChannel(i)
  297. found := false
  298. for _, s := range p.Sensors {
  299. if s.ID == want {
  300. if s.DIMMID != "" {
  301. return fmt.Errorf("profile: do not invent DIMM map on %s", want)
  302. }
  303. found = true
  304. break
  305. }
  306. }
  307. if !found {
  308. return fmt.Errorf("profile: missing sensor %s", want)
  309. }
  310. }
  311. for _, id := range []string{ids.Fan1, ids.Fan2, ids.Fan3, ids.Fan4, ids.PTC1, ids.PTC2, ids.PTC3, ids.PTC4, ids.DoorX, ids.DoorY, ids.DoorZ} {
  312. if p.LookupActuator(id) == nil {
  313. return fmt.Errorf("profile: missing actuator %s", id)
  314. }
  315. }
  316. if p.Motors.ControlMode != "PERCENT_CLOSE" {
  317. return fmt.Errorf("profile: motors.control_mode must be PERCENT_CLOSE (legacy jog forbidden)")
  318. }
  319. if p.Startup.ReadinessProbe != "motor_status_startup_complete" {
  320. return fmt.Errorf("profile: readiness_probe must be motor_status_startup_complete")
  321. }
  322. if err := p.validateIDs(); err != nil {
  323. return err
  324. }
  325. if p.UART.Baud != 0 && p.UART.Baud != 115200 {
  326. return fmt.Errorf("profile: uart.baud must be 115200 (host serial path is fixed 115200 8N1)")
  327. }
  328. if p.UART.DataBits != 0 && p.UART.DataBits != 8 {
  329. return fmt.Errorf("profile: uart data_bits must be 8")
  330. }
  331. if p.UART.Parity != "" && !strings.EqualFold(p.UART.Parity, "none") && p.UART.Parity != "N" {
  332. return fmt.Errorf("profile: uart parity must be none")
  333. }
  334. if p.UART.StopBits != 0 && p.UART.StopBits != 1 {
  335. return fmt.Errorf("profile: uart stop_bits must be 1")
  336. }
  337. if p.UART.FlowControl != "" && !strings.EqualFold(p.UART.FlowControl, "none") {
  338. return fmt.Errorf("profile: uart flow_control must be none")
  339. }
  340. if err := p.validateProtocolCRC(); err != nil {
  341. return err
  342. }
  343. if !sha256Hex(p.SourceContractSHA256) {
  344. return fmt.Errorf("profile: source_contract_sha256 required as 64-char hex")
  345. }
  346. if !sha256Hex(p.SourceGoldenSHA256) {
  347. return fmt.Errorf("profile: source_golden_sha256 required as 64-char hex")
  348. }
  349. if err := p.validateEvidenceFiles(); err != nil {
  350. return err
  351. }
  352. return nil
  353. }
  354. func ValidateProd2U(p *Profile) error {
  355. return p.ValidateProd2U()
  356. }
  357. func (p *Profile) ValidateProd2U() error {
  358. if p.Protocol.HeaderHex == "" || !strings.EqualFold(strings.ReplaceAll(p.Protocol.HeaderHex, " ", ""), "A55A") {
  359. return fmt.Errorf("profile: Prod2U header_hex must be A55A")
  360. }
  361. crc := p.Protocol.CRC
  362. if crc.Name != "CRC-16/CCITT-FALSE" {
  363. return fmt.Errorf("profile: Prod2U crc.name must be CRC-16/CCITT-FALSE")
  364. }
  365. if crc.Polynomial != 0x1021 {
  366. return fmt.Errorf("profile: Prod2U crc.polynomial must be 0x1021")
  367. }
  368. if crc.Initial != 0xFFFF {
  369. return fmt.Errorf("profile: Prod2U crc.initial must be 0xFFFF")
  370. }
  371. if crc.ReflectInput || crc.ReflectOutput {
  372. return fmt.Errorf("profile: Prod2U crc RefIn/RefOut must be false")
  373. }
  374. if crc.XorOutput != 0 {
  375. return fmt.Errorf("profile: Prod2U crc.xor_output must be 0")
  376. }
  377. if crc.Coverage != "type_length_payload" {
  378. return fmt.Errorf("profile: Prod2U crc.coverage must be type_length_payload")
  379. }
  380. if !strings.EqualFold(crc.WireOrder, "little") && !strings.EqualFold(crc.WireOrder, "le") {
  381. return fmt.Errorf("profile: Prod2U crc.wire_order must be little")
  382. }
  383. wantCmd := map[string]int{
  384. "set_all": 1, "get_temperature": 2, "get_motor_status": 3,
  385. "temperature_data": 0x82, "motor_status_data": 0x83,
  386. }
  387. seenCode := map[int]string{}
  388. for name, code := range wantCmd {
  389. got, ok := p.Protocol.Commands[name]
  390. if !ok {
  391. return fmt.Errorf("profile: Prod2U missing command %s", name)
  392. }
  393. if got != code {
  394. return fmt.Errorf("profile: Prod2U command %s type want %d got %d", name, code, got)
  395. }
  396. if prev, ok := seenCode[code]; ok {
  397. return fmt.Errorf("profile: Prod2U command type 0x%02x used by %s and %s", code, prev, name)
  398. }
  399. seenCode[code] = name
  400. }
  401. for name, code := range p.Protocol.Commands {
  402. if want, ok := wantCmd[name]; ok {
  403. if code != want {
  404. return fmt.Errorf("profile: Prod2U command %s type want %d got %d", name, want, code)
  405. }
  406. continue
  407. }
  408. if prev, ok := seenCode[code]; ok {
  409. return fmt.Errorf("profile: Prod2U command type 0x%02x used by %s and %s", code, prev, name)
  410. }
  411. seenCode[code] = name
  412. }
  413. if p.Protocol.GetTemperature.PayloadLength != 0 {
  414. return fmt.Errorf("profile: Prod2U get_temperature request payload_length must be 0")
  415. }
  416. if p.Protocol.GetTemperature.ResponsePayloadLength != protocol.TemperaturePayloadLen {
  417. return fmt.Errorf("profile: Prod2U get_temperature response payload_length want %d", protocol.TemperaturePayloadLen)
  418. }
  419. if p.Protocol.GetMotorStatus.PayloadLength != 0 {
  420. return fmt.Errorf("profile: Prod2U get_motor_status request payload_length must be 0")
  421. }
  422. if p.Protocol.GetMotorStatus.ResponsePayloadLength != protocol.MotorStatusPayloadLen {
  423. return fmt.Errorf("profile: Prod2U get_motor_status response payload_length want %d", protocol.MotorStatusPayloadLen)
  424. }
  425. if p.Protocol.SetAll.PayloadLength != protocol.SetAllPayloadLen {
  426. return fmt.Errorf("profile: Prod2U SET_ALL payload_length want %d", protocol.SetAllPayloadLen)
  427. }
  428. if p.UART.Baud != 115200 {
  429. return fmt.Errorf("profile: Prod2U uart.baud must be 115200")
  430. }
  431. if p.UART.DataBits != 8 {
  432. return fmt.Errorf("profile: Prod2U uart.data_bits must be 8")
  433. }
  434. if !strings.EqualFold(p.UART.Parity, "none") && p.UART.Parity != "N" {
  435. return fmt.Errorf("profile: Prod2U uart.parity must be none/N")
  436. }
  437. if p.UART.StopBits != 1 {
  438. return fmt.Errorf("profile: Prod2U uart.stop_bits must be 1")
  439. }
  440. if !strings.EqualFold(p.UART.FlowControl, "none") {
  441. return fmt.Errorf("profile: Prod2U uart.flow_control must be none")
  442. }
  443. return nil
  444. }
  445. func rejectDuplicateJSONKeys(raw []byte) error {
  446. dec := json.NewDecoder(bytes.NewReader(raw))
  447. type frame struct {
  448. keys map[string]struct{}
  449. expectKey bool
  450. isObject bool
  451. }
  452. var stack []frame
  453. for {
  454. tok, err := dec.Token()
  455. if err == io.EOF {
  456. return nil
  457. }
  458. if err != nil {
  459. return err
  460. }
  461. switch t := tok.(type) {
  462. case json.Delim:
  463. switch t {
  464. case '{':
  465. stack = append(stack, frame{keys: map[string]struct{}{}, expectKey: true, isObject: true})
  466. case '[':
  467. stack = append(stack, frame{})
  468. case '}', ']':
  469. if len(stack) == 0 {
  470. return fmt.Errorf("duplicate-key scan: unmatched closer")
  471. }
  472. stack = stack[:len(stack)-1]
  473. if len(stack) > 0 && stack[len(stack)-1].isObject {
  474. stack[len(stack)-1].expectKey = true
  475. }
  476. }
  477. case string:
  478. if len(stack) == 0 {
  479. continue
  480. }
  481. top := &stack[len(stack)-1]
  482. if top.isObject && top.expectKey {
  483. if _, ok := top.keys[t]; ok {
  484. return fmt.Errorf("duplicate JSON key %q (fail closed)", t)
  485. }
  486. top.keys[t] = struct{}{}
  487. top.expectKey = false
  488. continue
  489. }
  490. if top.isObject && !top.expectKey {
  491. top.expectKey = true
  492. }
  493. default:
  494. if len(stack) > 0 && stack[len(stack)-1].isObject && !stack[len(stack)-1].expectKey {
  495. stack[len(stack)-1].expectKey = true
  496. }
  497. }
  498. }
  499. }
  500. func (p *Profile) validateEvidenceFiles() error {
  501. if p.Path == "" {
  502. return nil
  503. }
  504. dir := filepath.Dir(p.Path)
  505. for i := 0; i < 8; i++ {
  506. dir = filepath.Dir(dir)
  507. pairs := []struct {
  508. rel string
  509. want string
  510. kind string
  511. }{
  512. {filepath.Join("src", "generated", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
  513. {filepath.Join("evidence", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
  514. {filepath.Join("src", "generated", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
  515. {filepath.Join("evidence", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
  516. }
  517. for _, pair := range pairs {
  518. path := filepath.Join(dir, pair.rel)
  519. raw, err := os.ReadFile(path)
  520. if err != nil {
  521. continue
  522. }
  523. sum := sha256.Sum256(raw)
  524. got := hex.EncodeToString(sum[:])
  525. if !strings.EqualFold(got, pair.want) {
  526. return fmt.Errorf("profile: %s does not match %s (got %s want %s)", pair.kind, path, got, pair.want)
  527. }
  528. }
  529. if filepath.Base(dir) == "/" || dir == filepath.Dir(dir) {
  530. break
  531. }
  532. }
  533. return nil
  534. }
  535. func sha256Hex(s string) bool {
  536. if len(s) != 64 {
  537. return false
  538. }
  539. for _, c := range s {
  540. if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
  541. return false
  542. }
  543. }
  544. return true
  545. }
  546. func isFinite(v float64) bool {
  547. return !math.IsNaN(v) && !math.IsInf(v, 0)
  548. }
  549. func (p *Profile) validateProtocolCRC() error {
  550. if p.Protocol.HeaderHex != "" && !strings.EqualFold(strings.ReplaceAll(p.Protocol.HeaderHex, " ", ""), "A55A") {
  551. return fmt.Errorf("profile: protocol.header_hex must be A55A")
  552. }
  553. crc := p.Protocol.CRC
  554. if crc.Name != "" && !strings.Contains(strings.ToUpper(crc.Name), "CCITT") && !strings.Contains(strings.ToUpper(crc.Name), "CRC-16") {
  555. return fmt.Errorf("profile: crc.name must be CRC-16/CCITT-FALSE")
  556. }
  557. if crc.Polynomial != 0 && crc.Polynomial != 0x1021 {
  558. return fmt.Errorf("profile: crc.polynomial must be 0x1021")
  559. }
  560. if crc.Initial != 0 && crc.Initial != 0xFFFF {
  561. return fmt.Errorf("profile: crc.initial must be 0xFFFF")
  562. }
  563. if crc.ReflectInput || crc.ReflectOutput {
  564. return fmt.Errorf("profile: crc RefIn/RefOut must be false")
  565. }
  566. if crc.XorOutput != 0 {
  567. return fmt.Errorf("profile: crc xor_output must be 0")
  568. }
  569. if crc.Coverage != "" && crc.Coverage != "header+type+length+payload" && crc.Coverage != "type+length+payload" && crc.Coverage != "after_header" {
  570. // accept documented coverage strings used by the generated profile
  571. if !strings.Contains(strings.ToLower(crc.Coverage), "payload") && crc.Coverage != "frame_without_crc" {
  572. return fmt.Errorf("profile: crc.coverage %q not recognized", crc.Coverage)
  573. }
  574. }
  575. if crc.WireOrder != "" && !strings.EqualFold(crc.WireOrder, "little") && !strings.EqualFold(crc.WireOrder, "le") {
  576. return fmt.Errorf("profile: crc.wire_order must be little-endian")
  577. }
  578. seenCmd := map[int]string{}
  579. for name, code := range p.Protocol.Commands {
  580. if prev, ok := seenCmd[code]; ok {
  581. return fmt.Errorf("profile: command type 0x%02x used by %s and %s", code, prev, name)
  582. }
  583. seenCmd[code] = name
  584. }
  585. if p.Protocol.GetTemperature.ResponsePayloadLength != 0 && p.Protocol.GetTemperature.ResponsePayloadLength != protocol.TemperaturePayloadLen {
  586. return fmt.Errorf("profile: get_temperature response length want %d", protocol.TemperaturePayloadLen)
  587. }
  588. if p.Protocol.GetMotorStatus.ResponsePayloadLength != 0 && p.Protocol.GetMotorStatus.ResponsePayloadLength != protocol.MotorStatusPayloadLen {
  589. return fmt.Errorf("profile: get_motor_status response length want %d", protocol.MotorStatusPayloadLen)
  590. }
  591. return nil
  592. }
  593. func (p *Profile) validateIDs() error {
  594. seenID := map[string]string{}
  595. seenAlias := map[string]string{}
  596. srcIdx := map[int]string{}
  597. add := func(kind, id string, aliases []string) error {
  598. if id == "" {
  599. return fmt.Errorf("profile: empty %s id", kind)
  600. }
  601. if prev, ok := seenID[id]; ok {
  602. return fmt.Errorf("profile: duplicate id %s (%s and %s)", id, prev, kind)
  603. }
  604. if prev, ok := seenAlias[id]; ok {
  605. return fmt.Errorf("profile: id %q collides with earlier alias of %s", id, prev)
  606. }
  607. seenID[id] = kind
  608. local := map[string]struct{}{}
  609. for _, al := range aliases {
  610. if al == "" {
  611. continue
  612. }
  613. if _, dup := local[al]; dup {
  614. return fmt.Errorf("profile: duplicate alias %q on %s", al, id)
  615. }
  616. local[al] = struct{}{}
  617. if prev, ok := seenAlias[al]; ok {
  618. return fmt.Errorf("profile: duplicate alias %q on %s and %s", al, prev, id)
  619. }
  620. if prev, ok := seenID[al]; ok {
  621. return fmt.Errorf("profile: alias %q collides with id of %s", al, prev)
  622. }
  623. seenAlias[al] = id
  624. }
  625. return nil
  626. }
  627. for _, s := range p.Sensors {
  628. if s.ValidRange.Min > s.ValidRange.Max {
  629. return fmt.Errorf("profile: sensor %s min>max", s.ID)
  630. }
  631. if s.Resolution <= 0 {
  632. return fmt.Errorf("profile: sensor %s resolution must be > 0", s.ID)
  633. }
  634. if err := add("sensor", s.ID, s.Aliases); err != nil {
  635. return err
  636. }
  637. if prev, ok := srcIdx[s.SourceIndex]; ok && s.Kind == "TEMPERATURE" {
  638. return fmt.Errorf("profile: sensor source_index %d reused by %s and %s", s.SourceIndex, prev, s.ID)
  639. }
  640. if s.Kind == "TEMPERATURE" {
  641. srcIdx[s.SourceIndex] = s.ID
  642. }
  643. if !isFinite(s.Resolution) || !isFinite(s.ValidRange.Min) || !isFinite(s.ValidRange.Max) {
  644. return fmt.Errorf("profile: sensor %s has non-finite numeric field", s.ID)
  645. }
  646. if strings.EqualFold(s.Kind, "UNSPECIFIED") || s.Kind == "" {
  647. return fmt.Errorf("profile: sensor %s kind must not be UNSPECIFIED", s.ID)
  648. }
  649. if strings.EqualFold(s.FeedbackMode, "UNSPECIFIED") || s.FeedbackMode == "" {
  650. return fmt.Errorf("profile: sensor %s feedback_mode must not be UNSPECIFIED", s.ID)
  651. }
  652. }
  653. offsets := map[int]string{}
  654. for _, a := range p.Actuators {
  655. if a.CommandRange.Min > a.CommandRange.Max {
  656. return fmt.Errorf("profile: actuator %s min>max", a.ID)
  657. }
  658. if a.Resolution <= 0 {
  659. return fmt.Errorf("profile: actuator %s resolution must be > 0", a.ID)
  660. }
  661. if a.MaxSlewPerSecond < 0 {
  662. return fmt.Errorf("profile: actuator %s slew must be >= 0", a.ID)
  663. }
  664. if a.SafetyDefault < a.CommandRange.Min || a.SafetyDefault > a.CommandRange.Max {
  665. return fmt.Errorf("profile: actuator %s safety_default out of range", a.ID)
  666. }
  667. if a.SetAllOffset < 0 {
  668. return fmt.Errorf("profile: SET_ALL offset %d for %s is negative", a.SetAllOffset, a.ID)
  669. }
  670. if p.Protocol.SetAll.PayloadLength > 0 && a.SetAllOffset >= p.Protocol.SetAll.PayloadLength {
  671. return fmt.Errorf("profile: SET_ALL offset %d for %s exceeds payload_length %d", a.SetAllOffset, a.ID, p.Protocol.SetAll.PayloadLength)
  672. }
  673. if other, ok := offsets[a.SetAllOffset]; ok {
  674. return fmt.Errorf("profile: SET_ALL offset %d for %s already occupied by %s", a.SetAllOffset, a.ID, other)
  675. }
  676. offsets[a.SetAllOffset] = a.ID
  677. if !isFinite(a.Resolution) || !isFinite(a.CommandRange.Min) || !isFinite(a.CommandRange.Max) || !isFinite(a.SafetyDefault) || !isFinite(a.MaxSlewPerSecond) {
  678. return fmt.Errorf("profile: actuator %s has non-finite numeric field", a.ID)
  679. }
  680. if strings.EqualFold(a.Kind, "UNSPECIFIED") || a.Kind == "" {
  681. return fmt.Errorf("profile: actuator %s kind must not be UNSPECIFIED", a.ID)
  682. }
  683. if strings.EqualFold(a.ControlMode, "UNSPECIFIED") || a.ControlMode == "" {
  684. return fmt.Errorf("profile: actuator %s control_mode must not be UNSPECIFIED", a.ID)
  685. }
  686. if strings.EqualFold(a.FeedbackMode, "UNSPECIFIED") || a.FeedbackMode == "" {
  687. return fmt.Errorf("profile: actuator %s feedback_mode must not be UNSPECIFIED", a.ID)
  688. }
  689. if err := add("actuator", a.ID, a.Aliases); err != nil {
  690. return err
  691. }
  692. }
  693. return nil
  694. }
  695. func (p *Profile) LookupActuator(id string) *Actuator {
  696. for i := range p.Actuators {
  697. a := &p.Actuators[i]
  698. if a.ID == id {
  699. return a
  700. }
  701. for _, al := range a.Aliases {
  702. if al == id {
  703. return a
  704. }
  705. }
  706. }
  707. return nil
  708. }
  709. func (p *Profile) LookupSensor(id string) *Sensor {
  710. for i := range p.Sensors {
  711. s := &p.Sensors[i]
  712. if s.ID == id {
  713. return s
  714. }
  715. for _, al := range s.Aliases {
  716. if al == id {
  717. return s
  718. }
  719. }
  720. }
  721. return nil
  722. }
  723. func (p *Profile) InterByteTimeout() time.Duration {
  724. ms := p.Timeouts.FrameInterByteMS
  725. if ms <= 0 {
  726. ms = p.UART.InterByteTimeoutMS
  727. }
  728. if ms <= 0 {
  729. ms = 10
  730. }
  731. return time.Duration(ms) * time.Millisecond
  732. }
  733. func (p *Profile) GetResponseTimeout() time.Duration {
  734. ms := p.Timeouts.HostGetResponseMS
  735. if ms <= 0 {
  736. ms = 5000
  737. }
  738. return time.Duration(ms) * time.Millisecond
  739. }
  740. func (p *Profile) FirmwareWatchdog() time.Duration {
  741. return time.Duration(p.Watchdog.TimeoutSeconds) * time.Second
  742. }
  743. func (p *Profile) MinSamplePeriod() time.Duration {
  744. // UART + sequential 27-channel scan: do not let clients request faster than 50ms.
  745. return 50 * time.Millisecond
  746. }
  747. func (p *Profile) RecommendedSamplePeriod() time.Duration {
  748. scan := time.Duration(p.Timeouts.TemperatureScanBusyMS) * time.Millisecond
  749. if scan <= 0 {
  750. scan = 5 * time.Second
  751. }
  752. // Host cannot honestly recommend faster than the blocking temperature scan.
  753. return scan
  754. }
  755. // ProfileIdentityDigest is a profile-file digest. It is NOT the API
  756. // Capability Hash; callers must use caphash.HashCanonicalCapabilities /
  757. // device.BuildCanonicalCapabilities.
  758. func (p *Profile) ProfileIdentityDigest() string {
  759. type view struct {
  760. ProfileID string
  761. ProfileRevision string
  762. Contract string
  763. Sensors []string
  764. Actuators []string
  765. Honesty Honesty
  766. Ack bool
  767. Readiness string
  768. API string
  769. Safety Safety
  770. Slew []float64
  771. Units []string
  772. Ranges []Range
  773. }
  774. v := view{
  775. ProfileID: p.ProfileID, ProfileRevision: p.ProfileRevision, Contract: p.SourceContractSHA256,
  776. Honesty: p.Honesty, Ack: p.Protocol.Ack, Readiness: p.Startup.ReadinessProbe, API: p.APIVersion,
  777. Safety: p.Safety,
  778. }
  779. for _, s := range p.Sensors {
  780. v.Sensors = append(v.Sensors, s.ID)
  781. v.Units = append(v.Units, s.Unit)
  782. v.Ranges = append(v.Ranges, s.ValidRange)
  783. }
  784. for _, a := range p.Actuators {
  785. v.Actuators = append(v.Actuators, a.ID)
  786. v.Slew = append(v.Slew, a.MaxSlewPerSecond)
  787. v.Units = append(v.Units, a.Unit)
  788. v.Ranges = append(v.Ranges, a.CommandRange)
  789. }
  790. b, _ := json.Marshal(v)
  791. sum := sha256.Sum256(b)
  792. return hex.EncodeToString(sum[:])
  793. }
  794. func (p *Profile) SafeSetAll() protocol.SetAll {
  795. s := protocol.SetAll{
  796. DoorZ: uint8(p.Safety.DoorClosePercent),
  797. DoorX: uint8(p.Safety.DoorClosePercent),
  798. DoorY: uint8(p.Safety.DoorClosePercent),
  799. }
  800. for i := range s.Fan {
  801. s.Fan[i] = uint8(p.Safety.Fan)
  802. }
  803. for i := range s.PTC {
  804. s.PTC[i] = uint8(p.Safety.PTC)
  805. }
  806. return s
  807. }
  808. func (p *Profile) Baud() int {
  809. if p.UART.Baud == 0 {
  810. return 115200
  811. }
  812. return p.UART.Baud
  813. }