profile.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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. return &p, nil
  242. }
  243. func (p *Profile) Validate() error {
  244. if p.Schema != SchemaID {
  245. return fmt.Errorf("profile: schema %q want %q", p.Schema, SchemaID)
  246. }
  247. if p.ProfileID == "" || p.ProfileRevision == "" {
  248. return fmt.Errorf("profile: missing profile_id/revision")
  249. }
  250. if p.Safety.Notes == "" {
  251. return fmt.Errorf("profile: safety.notes required (must document door 0 = full open)")
  252. }
  253. if p.Safety.Fan < 0 || p.Safety.Fan > 100 || p.Safety.PTC < 0 || p.Safety.PTC > 100 {
  254. return fmt.Errorf("profile: safety fan/ptc out of 0..100")
  255. }
  256. if p.Safety.DoorClosePercent < 0 || p.Safety.DoorClosePercent > 100 {
  257. return fmt.Errorf("profile: safety door_close_percent out of 0..100")
  258. }
  259. if p.Watchdog.TimeoutSeconds <= 0 {
  260. return fmt.Errorf("profile: watchdog.timeout_seconds required")
  261. }
  262. if p.Watchdog.GetFeedsWatchdog {
  263. return fmt.Errorf("profile: GET must not feed watchdog")
  264. }
  265. if !p.Watchdog.HeartbeatRepeatsDoorPercent || !p.Watchdog.HeartbeatMustNotRewriteDoorsToZero {
  266. return fmt.Errorf("profile: heartbeat must repeat real door percents and must not rewrite doors to 0")
  267. }
  268. if p.Protocol.Ack {
  269. return fmt.Errorf("profile: current Prod2U contract has no ACK")
  270. }
  271. if p.Protocol.SetAll.PayloadLength != protocol.SetAllPayloadLen {
  272. return fmt.Errorf("profile: SET_ALL payload_length want %d", protocol.SetAllPayloadLen)
  273. }
  274. if p.Protocol.SetAll.RetryPolicy != "never_when_outcome_unknown" {
  275. return fmt.Errorf("profile: retry_policy must be never_when_outcome_unknown")
  276. }
  277. if p.Temperature.ValueCount != protocol.TemperaturePayloadLen {
  278. return fmt.Errorf("profile: temperature.value_count want %d", protocol.TemperaturePayloadLen)
  279. }
  280. if p.Temperature.InvalidValue != int(protocol.TempInvalid) {
  281. return fmt.Errorf("profile: invalid_value must be 0xFF")
  282. }
  283. if p.Honesty.FirmwareVersion != "NOT_SUPPORTED" || p.Honesty.FanRPM != "NOT_SUPPORTED" ||
  284. p.Honesty.EncoderPosition != "NOT_SUPPORTED" || p.Honesty.PTCActualPower != "NOT_SUPPORTED" {
  285. return fmt.Errorf("profile: honesty must mark firmware/rpm/encoder/ptc actual as NOT_SUPPORTED")
  286. }
  287. if p.Honesty.DIMMTemperatureMap != "UNKNOWN" {
  288. return fmt.Errorf("profile: dimm map must be UNKNOWN")
  289. }
  290. for i := 0; i < p.Temperature.ValueCount; i++ {
  291. want := ids.TempChannel(i)
  292. found := false
  293. for _, s := range p.Sensors {
  294. if s.ID == want {
  295. if s.DIMMID != "" {
  296. return fmt.Errorf("profile: do not invent DIMM map on %s", want)
  297. }
  298. found = true
  299. break
  300. }
  301. }
  302. if !found {
  303. return fmt.Errorf("profile: missing sensor %s", want)
  304. }
  305. }
  306. 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} {
  307. if p.LookupActuator(id) == nil {
  308. return fmt.Errorf("profile: missing actuator %s", id)
  309. }
  310. }
  311. if p.Motors.ControlMode != "PERCENT_CLOSE" {
  312. return fmt.Errorf("profile: motors.control_mode must be PERCENT_CLOSE (legacy jog forbidden)")
  313. }
  314. if p.Startup.ReadinessProbe != "motor_status_startup_complete" {
  315. return fmt.Errorf("profile: readiness_probe must be motor_status_startup_complete")
  316. }
  317. if err := p.validateIDs(); err != nil {
  318. return err
  319. }
  320. if p.UART.Baud != 0 && p.UART.Baud != 115200 {
  321. return fmt.Errorf("profile: uart.baud must be 115200 (host serial path is fixed 115200 8N1)")
  322. }
  323. if p.UART.DataBits != 0 && p.UART.DataBits != 8 {
  324. return fmt.Errorf("profile: uart data_bits must be 8")
  325. }
  326. if p.UART.Parity != "" && !strings.EqualFold(p.UART.Parity, "none") && p.UART.Parity != "N" {
  327. return fmt.Errorf("profile: uart parity must be none")
  328. }
  329. if p.UART.StopBits != 0 && p.UART.StopBits != 1 {
  330. return fmt.Errorf("profile: uart stop_bits must be 1")
  331. }
  332. if p.UART.FlowControl != "" && !strings.EqualFold(p.UART.FlowControl, "none") {
  333. return fmt.Errorf("profile: uart flow_control must be none")
  334. }
  335. if err := p.validateProtocolCRC(); err != nil {
  336. return err
  337. }
  338. if !sha256Hex(p.SourceContractSHA256) {
  339. return fmt.Errorf("profile: source_contract_sha256 required as 64-char hex")
  340. }
  341. if !sha256Hex(p.SourceGoldenSHA256) {
  342. return fmt.Errorf("profile: source_golden_sha256 required as 64-char hex")
  343. }
  344. if err := p.validateEvidenceFiles(); err != nil {
  345. return err
  346. }
  347. return nil
  348. }
  349. func rejectDuplicateJSONKeys(raw []byte) error {
  350. dec := json.NewDecoder(bytes.NewReader(raw))
  351. type frame struct {
  352. keys map[string]struct{}
  353. expectKey bool
  354. isObject bool
  355. }
  356. var stack []frame
  357. for {
  358. tok, err := dec.Token()
  359. if err == io.EOF {
  360. return nil
  361. }
  362. if err != nil {
  363. return err
  364. }
  365. switch t := tok.(type) {
  366. case json.Delim:
  367. switch t {
  368. case '{':
  369. stack = append(stack, frame{keys: map[string]struct{}{}, expectKey: true, isObject: true})
  370. case '[':
  371. stack = append(stack, frame{})
  372. case '}', ']':
  373. if len(stack) == 0 {
  374. return fmt.Errorf("duplicate-key scan: unmatched closer")
  375. }
  376. stack = stack[:len(stack)-1]
  377. if len(stack) > 0 && stack[len(stack)-1].isObject {
  378. stack[len(stack)-1].expectKey = true
  379. }
  380. }
  381. case string:
  382. if len(stack) == 0 {
  383. continue
  384. }
  385. top := &stack[len(stack)-1]
  386. if top.isObject && top.expectKey {
  387. if _, ok := top.keys[t]; ok {
  388. return fmt.Errorf("duplicate JSON key %q (fail closed)", t)
  389. }
  390. top.keys[t] = struct{}{}
  391. top.expectKey = false
  392. continue
  393. }
  394. if top.isObject && !top.expectKey {
  395. top.expectKey = true
  396. }
  397. default:
  398. if len(stack) > 0 && stack[len(stack)-1].isObject && !stack[len(stack)-1].expectKey {
  399. stack[len(stack)-1].expectKey = true
  400. }
  401. }
  402. }
  403. }
  404. func (p *Profile) validateEvidenceFiles() error {
  405. if p.Path == "" {
  406. return nil
  407. }
  408. dir := filepath.Dir(p.Path)
  409. for i := 0; i < 8; i++ {
  410. dir = filepath.Dir(dir)
  411. pairs := []struct {
  412. rel string
  413. want string
  414. kind string
  415. }{
  416. {filepath.Join("src", "generated", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
  417. {filepath.Join("evidence", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
  418. {filepath.Join("src", "generated", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
  419. {filepath.Join("evidence", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
  420. }
  421. for _, pair := range pairs {
  422. path := filepath.Join(dir, pair.rel)
  423. raw, err := os.ReadFile(path)
  424. if err != nil {
  425. continue
  426. }
  427. sum := sha256.Sum256(raw)
  428. got := hex.EncodeToString(sum[:])
  429. if !strings.EqualFold(got, pair.want) {
  430. return fmt.Errorf("profile: %s does not match %s (got %s want %s)", pair.kind, path, got, pair.want)
  431. }
  432. }
  433. if filepath.Base(dir) == "/" || dir == filepath.Dir(dir) {
  434. break
  435. }
  436. }
  437. return nil
  438. }
  439. func sha256Hex(s string) bool {
  440. if len(s) != 64 {
  441. return false
  442. }
  443. for _, c := range s {
  444. if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
  445. return false
  446. }
  447. }
  448. return true
  449. }
  450. func isFinite(v float64) bool {
  451. return !math.IsNaN(v) && !math.IsInf(v, 0)
  452. }
  453. func (p *Profile) validateProtocolCRC() error {
  454. if p.Protocol.HeaderHex != "" && !strings.EqualFold(strings.ReplaceAll(p.Protocol.HeaderHex, " ", ""), "A55A") {
  455. return fmt.Errorf("profile: protocol.header_hex must be A55A")
  456. }
  457. crc := p.Protocol.CRC
  458. if crc.Name != "" && !strings.Contains(strings.ToUpper(crc.Name), "CCITT") && !strings.Contains(strings.ToUpper(crc.Name), "CRC-16") {
  459. return fmt.Errorf("profile: crc.name must be CRC-16/CCITT-FALSE")
  460. }
  461. if crc.Polynomial != 0 && crc.Polynomial != 0x1021 {
  462. return fmt.Errorf("profile: crc.polynomial must be 0x1021")
  463. }
  464. if crc.Initial != 0 && crc.Initial != 0xFFFF {
  465. return fmt.Errorf("profile: crc.initial must be 0xFFFF")
  466. }
  467. if crc.ReflectInput || crc.ReflectOutput {
  468. return fmt.Errorf("profile: crc RefIn/RefOut must be false")
  469. }
  470. if crc.XorOutput != 0 {
  471. return fmt.Errorf("profile: crc xor_output must be 0")
  472. }
  473. if crc.Coverage != "" && crc.Coverage != "header+type+length+payload" && crc.Coverage != "type+length+payload" && crc.Coverage != "after_header" {
  474. // accept documented coverage strings used by the generated profile
  475. if !strings.Contains(strings.ToLower(crc.Coverage), "payload") && crc.Coverage != "frame_without_crc" {
  476. return fmt.Errorf("profile: crc.coverage %q not recognized", crc.Coverage)
  477. }
  478. }
  479. if crc.WireOrder != "" && !strings.EqualFold(crc.WireOrder, "little") && !strings.EqualFold(crc.WireOrder, "le") {
  480. return fmt.Errorf("profile: crc.wire_order must be little-endian")
  481. }
  482. seenCmd := map[int]string{}
  483. for name, code := range p.Protocol.Commands {
  484. if prev, ok := seenCmd[code]; ok {
  485. return fmt.Errorf("profile: command type 0x%02x used by %s and %s", code, prev, name)
  486. }
  487. seenCmd[code] = name
  488. }
  489. if p.Protocol.GetTemperature.ResponsePayloadLength != 0 && p.Protocol.GetTemperature.ResponsePayloadLength != protocol.TemperaturePayloadLen {
  490. return fmt.Errorf("profile: get_temperature response length want %d", protocol.TemperaturePayloadLen)
  491. }
  492. if p.Protocol.GetMotorStatus.ResponsePayloadLength != 0 && p.Protocol.GetMotorStatus.ResponsePayloadLength != protocol.MotorStatusPayloadLen {
  493. return fmt.Errorf("profile: get_motor_status response length want %d", protocol.MotorStatusPayloadLen)
  494. }
  495. return nil
  496. }
  497. func (p *Profile) validateIDs() error {
  498. seenID := map[string]string{}
  499. seenAlias := map[string]string{}
  500. srcIdx := map[int]string{}
  501. add := func(kind, id string, aliases []string) error {
  502. if id == "" {
  503. return fmt.Errorf("profile: empty %s id", kind)
  504. }
  505. if prev, ok := seenID[id]; ok {
  506. return fmt.Errorf("profile: duplicate id %s (%s and %s)", id, prev, kind)
  507. }
  508. if prev, ok := seenAlias[id]; ok {
  509. return fmt.Errorf("profile: id %q collides with earlier alias of %s", id, prev)
  510. }
  511. seenID[id] = kind
  512. local := map[string]struct{}{}
  513. for _, al := range aliases {
  514. if al == "" {
  515. continue
  516. }
  517. if _, dup := local[al]; dup {
  518. return fmt.Errorf("profile: duplicate alias %q on %s", al, id)
  519. }
  520. local[al] = struct{}{}
  521. if prev, ok := seenAlias[al]; ok {
  522. return fmt.Errorf("profile: duplicate alias %q on %s and %s", al, prev, id)
  523. }
  524. if prev, ok := seenID[al]; ok {
  525. return fmt.Errorf("profile: alias %q collides with id of %s", al, prev)
  526. }
  527. seenAlias[al] = id
  528. }
  529. return nil
  530. }
  531. for _, s := range p.Sensors {
  532. if s.ValidRange.Min > s.ValidRange.Max {
  533. return fmt.Errorf("profile: sensor %s min>max", s.ID)
  534. }
  535. if s.Resolution <= 0 {
  536. return fmt.Errorf("profile: sensor %s resolution must be > 0", s.ID)
  537. }
  538. if err := add("sensor", s.ID, s.Aliases); err != nil {
  539. return err
  540. }
  541. if prev, ok := srcIdx[s.SourceIndex]; ok && s.Kind == "TEMPERATURE" {
  542. return fmt.Errorf("profile: sensor source_index %d reused by %s and %s", s.SourceIndex, prev, s.ID)
  543. }
  544. if s.Kind == "TEMPERATURE" {
  545. srcIdx[s.SourceIndex] = s.ID
  546. }
  547. if !isFinite(s.Resolution) || !isFinite(s.ValidRange.Min) || !isFinite(s.ValidRange.Max) {
  548. return fmt.Errorf("profile: sensor %s has non-finite numeric field", s.ID)
  549. }
  550. if strings.EqualFold(s.Kind, "UNSPECIFIED") || s.Kind == "" {
  551. return fmt.Errorf("profile: sensor %s kind must not be UNSPECIFIED", s.ID)
  552. }
  553. if strings.EqualFold(s.FeedbackMode, "UNSPECIFIED") || s.FeedbackMode == "" {
  554. return fmt.Errorf("profile: sensor %s feedback_mode must not be UNSPECIFIED", s.ID)
  555. }
  556. }
  557. offsets := map[int]string{}
  558. for _, a := range p.Actuators {
  559. if a.CommandRange.Min > a.CommandRange.Max {
  560. return fmt.Errorf("profile: actuator %s min>max", a.ID)
  561. }
  562. if a.Resolution <= 0 {
  563. return fmt.Errorf("profile: actuator %s resolution must be > 0", a.ID)
  564. }
  565. if a.MaxSlewPerSecond < 0 {
  566. return fmt.Errorf("profile: actuator %s slew must be >= 0", a.ID)
  567. }
  568. if a.SafetyDefault < a.CommandRange.Min || a.SafetyDefault > a.CommandRange.Max {
  569. return fmt.Errorf("profile: actuator %s safety_default out of range", a.ID)
  570. }
  571. if a.SetAllOffset < 0 {
  572. return fmt.Errorf("profile: SET_ALL offset %d for %s is negative", a.SetAllOffset, a.ID)
  573. }
  574. if p.Protocol.SetAll.PayloadLength > 0 && a.SetAllOffset >= p.Protocol.SetAll.PayloadLength {
  575. return fmt.Errorf("profile: SET_ALL offset %d for %s exceeds payload_length %d", a.SetAllOffset, a.ID, p.Protocol.SetAll.PayloadLength)
  576. }
  577. offsets[a.SetAllOffset] = a.ID
  578. if !isFinite(a.Resolution) || !isFinite(a.CommandRange.Min) || !isFinite(a.CommandRange.Max) || !isFinite(a.SafetyDefault) || !isFinite(a.MaxSlewPerSecond) {
  579. return fmt.Errorf("profile: actuator %s has non-finite numeric field", a.ID)
  580. }
  581. if strings.EqualFold(a.Kind, "UNSPECIFIED") || a.Kind == "" {
  582. return fmt.Errorf("profile: actuator %s kind must not be UNSPECIFIED", a.ID)
  583. }
  584. if strings.EqualFold(a.ControlMode, "UNSPECIFIED") || a.ControlMode == "" {
  585. return fmt.Errorf("profile: actuator %s control_mode must not be UNSPECIFIED", a.ID)
  586. }
  587. if strings.EqualFold(a.FeedbackMode, "UNSPECIFIED") || a.FeedbackMode == "" {
  588. return fmt.Errorf("profile: actuator %s feedback_mode must not be UNSPECIFIED", a.ID)
  589. }
  590. if err := add("actuator", a.ID, a.Aliases); err != nil {
  591. return err
  592. }
  593. }
  594. return nil
  595. }
  596. func (p *Profile) LookupActuator(id string) *Actuator {
  597. for i := range p.Actuators {
  598. a := &p.Actuators[i]
  599. if a.ID == id {
  600. return a
  601. }
  602. for _, al := range a.Aliases {
  603. if al == id {
  604. return a
  605. }
  606. }
  607. }
  608. return nil
  609. }
  610. func (p *Profile) LookupSensor(id string) *Sensor {
  611. for i := range p.Sensors {
  612. s := &p.Sensors[i]
  613. if s.ID == id {
  614. return s
  615. }
  616. for _, al := range s.Aliases {
  617. if al == id {
  618. return s
  619. }
  620. }
  621. }
  622. return nil
  623. }
  624. func (p *Profile) InterByteTimeout() time.Duration {
  625. ms := p.Timeouts.FrameInterByteMS
  626. if ms <= 0 {
  627. ms = p.UART.InterByteTimeoutMS
  628. }
  629. if ms <= 0 {
  630. ms = 10
  631. }
  632. return time.Duration(ms) * time.Millisecond
  633. }
  634. func (p *Profile) GetResponseTimeout() time.Duration {
  635. ms := p.Timeouts.HostGetResponseMS
  636. if ms <= 0 {
  637. ms = 5000
  638. }
  639. return time.Duration(ms) * time.Millisecond
  640. }
  641. func (p *Profile) FirmwareWatchdog() time.Duration {
  642. return time.Duration(p.Watchdog.TimeoutSeconds) * time.Second
  643. }
  644. func (p *Profile) MinSamplePeriod() time.Duration {
  645. // UART + sequential 27-channel scan: do not let clients request faster than 50ms.
  646. return 50 * time.Millisecond
  647. }
  648. func (p *Profile) RecommendedSamplePeriod() time.Duration {
  649. scan := time.Duration(p.Timeouts.TemperatureScanBusyMS) * time.Millisecond
  650. if scan <= 0 {
  651. scan = 5 * time.Second
  652. }
  653. // Host cannot honestly recommend faster than the blocking temperature scan.
  654. return scan
  655. }
  656. // ProfileIdentityDigest is a profile-file digest. It is NOT the API
  657. // Capability Hash; callers must use caphash.HashCanonicalCapabilities /
  658. // device.BuildCanonicalCapabilities.
  659. func (p *Profile) ProfileIdentityDigest() string {
  660. type view struct {
  661. ProfileID string
  662. ProfileRevision string
  663. Contract string
  664. Sensors []string
  665. Actuators []string
  666. Honesty Honesty
  667. Ack bool
  668. Readiness string
  669. API string
  670. Safety Safety
  671. Slew []float64
  672. Units []string
  673. Ranges []Range
  674. }
  675. v := view{
  676. ProfileID: p.ProfileID, ProfileRevision: p.ProfileRevision, Contract: p.SourceContractSHA256,
  677. Honesty: p.Honesty, Ack: p.Protocol.Ack, Readiness: p.Startup.ReadinessProbe, API: p.APIVersion,
  678. Safety: p.Safety,
  679. }
  680. for _, s := range p.Sensors {
  681. v.Sensors = append(v.Sensors, s.ID)
  682. v.Units = append(v.Units, s.Unit)
  683. v.Ranges = append(v.Ranges, s.ValidRange)
  684. }
  685. for _, a := range p.Actuators {
  686. v.Actuators = append(v.Actuators, a.ID)
  687. v.Slew = append(v.Slew, a.MaxSlewPerSecond)
  688. v.Units = append(v.Units, a.Unit)
  689. v.Ranges = append(v.Ranges, a.CommandRange)
  690. }
  691. b, _ := json.Marshal(v)
  692. sum := sha256.Sum256(b)
  693. return hex.EncodeToString(sum[:])
  694. }
  695. func (p *Profile) SafeSetAll() protocol.SetAll {
  696. s := protocol.SetAll{
  697. DoorZ: uint8(p.Safety.DoorClosePercent),
  698. DoorX: uint8(p.Safety.DoorClosePercent),
  699. DoorY: uint8(p.Safety.DoorClosePercent),
  700. }
  701. for i := range s.Fan {
  702. s.Fan[i] = uint8(p.Safety.Fan)
  703. }
  704. for i := range s.PTC {
  705. s.PTC[i] = uint8(p.Safety.PTC)
  706. }
  707. return s
  708. }
  709. func (p *Profile) Baud() int {
  710. if p.UART.Baud == 0 {
  711. return 115200
  712. }
  713. return p.UART.Baud
  714. }