| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855 |
- package profile
- import (
- "bytes"
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "io"
- "math"
- "os"
- "path/filepath"
- "strings"
- "time"
- "hth/internal/ids"
- "hth/internal/protocol"
- )
- const SchemaID = "hth-device-profile-v1"
- type Range struct {
- Min float64 `json:"min"`
- Max float64 `json:"max"`
- }
- type Sensor struct {
- ID string `json:"id"`
- Aliases []string `json:"aliases"`
- DisplayName string `json:"display_name"`
- Kind string `json:"kind"`
- Unit string `json:"unit"`
- SourceIndex int `json:"source_index"`
- HoodID string `json:"hood_id"`
- ChamberID string `json:"chamber_id"`
- DIMMID string `json:"dimm_id"`
- Connector string `json:"connector"`
- ValidRange Range `json:"valid_range"`
- Resolution float64 `json:"resolution"`
- SourceTimestamp bool `json:"source_timestamp"`
- MappingConfidence string `json:"mapping_confidence"`
- CalibrationVersion string `json:"calibration_version"`
- FeedbackMode string `json:"feedback_mode"`
- Notes string `json:"notes"`
- }
- type Actuator struct {
- ID string `json:"id"`
- Aliases []string `json:"aliases"`
- DisplayName string `json:"display_name"`
- Kind string `json:"kind"`
- Unit string `json:"unit"`
- CommandRange Range `json:"command_range"`
- Resolution float64 `json:"resolution"`
- ControlMode string `json:"control_mode"`
- FeedbackMode string `json:"feedback_mode"`
- Idempotent bool `json:"idempotent"`
- OneShot bool `json:"one_shot"`
- SafetyDefault float64 `json:"safety_default"`
- MaxSlewPerSecond float64 `json:"max_slew_per_second"`
- ActualFeedback bool `json:"actual_feedback"`
- HoodID string `json:"hood_id"`
- ChamberID string `json:"chamber_id"`
- Connector string `json:"connector"`
- SetAllOffset int `json:"set_all_offset"`
- PhysicalPTCIndex []int `json:"physical_ptc_indices"`
- Notes string `json:"notes"`
- }
- type Honesty struct {
- FirmwareVersion string `json:"firmware_version"`
- FanRPM string `json:"fan_rpm"`
- PTCActualPower string `json:"ptc_actual_power"`
- EncoderPosition string `json:"encoder_position"`
- Ack bool `json:"ack"`
- DIMMTemperatureMap string `json:"dimm_temperature_map"`
- HardwareValidation string `json:"hardware_validation"`
- }
- type Safety struct {
- Fan int `json:"fan"`
- PTC int `json:"ptc"`
- DoorClosePercent int `json:"door_close_percent"`
- Notes string `json:"notes"`
- }
- type Watchdog struct {
- TimeoutSeconds int `json:"timeout_seconds"`
- FedBy string `json:"fed_by"`
- GetFeedsWatchdog bool `json:"get_feeds_watchdog"`
- EnableAfterStartupComplete bool `json:"enable_after_startup_complete"`
- Target struct {
- Fan int `json:"fan"`
- PTC int `json:"ptc"`
- } `json:"target"`
- HeartbeatRepeatsDoorPercent bool `json:"heartbeat_repeats_door_percent"`
- HeartbeatMustNotRewriteDoorsToZero bool `json:"heartbeat_must_not_rewrite_doors_to_zero"`
- HostHeartbeatPeriodMS int `json:"host_heartbeat_period_ms"`
- }
- type UART struct {
- Baud int `json:"baud"`
- DataBits int `json:"data_bits"`
- Parity string `json:"parity"`
- StopBits int `json:"stop_bits"`
- FlowControl string `json:"flow_control"`
- InterByteTimeoutMS int `json:"inter_byte_timeout_ms"`
- }
- type Timeouts struct {
- FrameInterByteMS int `json:"frame_inter_byte_ms"`
- HostGetResponseMS int `json:"host_get_response_ms"`
- TemperatureScanBusyMS int `json:"temperature_scan_busy_ms"`
- }
- type ProtocolSetAll struct {
- PayloadLength int `json:"payload_length"`
- FanOffset int `json:"fan_offset"`
- ChamberPTCOffset int `json:"chamber_ptc_offset"`
- ChamberPTCCount int `json:"chamber_ptc_count"`
- ZDoorOffset int `json:"z_door_offset"`
- XDoorOffset int `json:"x_door_offset"`
- YDoorOffset int `json:"y_door_offset"`
- LegacyPayloadLengthRejected int `json:"legacy_payload_length_rejected"`
- DutyMin int `json:"duty_min"`
- DutyMax int `json:"duty_max"`
- DoorPercentMin int `json:"door_percent_min"`
- DoorPercentMax int `json:"door_percent_max"`
- Response string `json:"response"`
- IdempotentSameTarget bool `json:"idempotent_same_target"`
- RetryPolicy string `json:"retry_policy"`
- }
- type CRC struct {
- Name string `json:"name"`
- Polynomial int `json:"polynomial"`
- Initial int `json:"initial"`
- ReflectInput bool `json:"reflect_input"`
- ReflectOutput bool `json:"reflect_output"`
- XorOutput int `json:"xor_output"`
- Coverage string `json:"coverage"`
- WireOrder string `json:"wire_order"`
- }
- type Protocol struct {
- HeaderHex string `json:"header_hex"`
- CRC CRC `json:"crc"`
- Ack bool `json:"ack"`
- StatusQuery bool `json:"status_query"`
- MaxPayloadLength int `json:"max_payload_length"`
- SetAll ProtocolSetAll `json:"set_all"`
- GetTemperature struct {
- PayloadLength int `json:"payload_length"`
- ResponsePayloadLength int `json:"response_payload_length"`
- } `json:"get_temperature"`
- GetMotorStatus struct {
- PayloadLength int `json:"payload_length"`
- ResponsePayloadLength int `json:"response_payload_length"`
- } `json:"get_motor_status"`
- Commands map[string]int `json:"commands"`
- }
- type Startup struct {
- GetTemperatureDropped bool `json:"get_temperature_dropped"`
- GetMotorStatusAllowed bool `json:"get_motor_status_allowed"`
- SetAllUpdatesThermalOnly bool `json:"set_all_updates_thermal_only"`
- DoorPercentIgnored bool `json:"door_percent_ignored"`
- ReadinessProbe string `json:"readiness_probe"`
- }
- type Temperature struct {
- ValueCount int `json:"value_count"`
- InvalidValue int `json:"invalid_value"`
- MaximumCelsius int `json:"maximum_celsius"`
- Unit string `json:"unit"`
- SourceTimestamp bool `json:"source_timestamp"`
- SequentialScan bool `json:"sequential_scan"`
- }
- type Motors struct {
- Order []string `json:"order"`
- ControlMode string `json:"control_mode"`
- PositionFeedback string `json:"position_feedback"`
- BusyReadable bool `json:"busy_readable"`
- PercentMin int `json:"percent_min"`
- PercentMax int `json:"percent_max"`
- OpenEndpointPercent int `json:"open_endpoint_percent"`
- CloseEndpointPercent int `json:"close_endpoint_percent"`
- }
- type Topology struct {
- HoodCount int `json:"hood_count"`
- ChamberCount int `json:"chamber_count"`
- DoorChamber int `json:"door_chamber"`
- }
- type Profile struct {
- Schema string `json:"schema"`
- ProfileID string `json:"profile_id"`
- ProfileRevision string `json:"profile_revision"`
- ProjectID string `json:"project_id"`
- APIVersion string `json:"api_version"`
- SourceContractSchema string `json:"source_contract_schema"`
- SourceContractSHA256 string `json:"source_contract_sha256"`
- SourceGoldenSHA256 string `json:"source_golden_sha256"`
- UART UART `json:"uart"`
- Protocol Protocol `json:"protocol"`
- Timeouts Timeouts `json:"timeouts"`
- Watchdog Watchdog `json:"watchdog"`
- Startup Startup `json:"startup"`
- Temperature Temperature `json:"temperature"`
- Motors Motors `json:"motors"`
- Topology Topology `json:"topology"`
- Safety Safety `json:"safety"`
- Sensors []Sensor `json:"sensors"`
- Actuators []Actuator `json:"actuators"`
- Honesty Honesty `json:"honesty"`
- GoldenVectors map[string]string `json:"golden_vectors"`
- GoldenNotes map[string]string `json:"golden_notes"`
- Path string `json:"-"`
- FileSHA256 string `json:"-"`
- Raw []byte `json:"-"`
- }
- func Load(path string) (*Profile, error) {
- return load(path, false)
- }
- func LoadStrict(path string) (*Profile, error) {
- return load(path, true)
- }
- func load(path string, strict bool) (*Profile, error) {
- raw, err := os.ReadFile(path)
- if err != nil {
- return nil, fmt.Errorf("profile: read %s: %w", path, err)
- }
- sum := sha256.Sum256(raw)
- if err := rejectDuplicateJSONKeys(raw); err != nil {
- return nil, fmt.Errorf("profile: %s: %w", path, err)
- }
- dec := json.NewDecoder(strings.NewReader(string(raw)))
- if strict {
- dec.DisallowUnknownFields()
- }
- var p Profile
- if err := dec.Decode(&p); err != nil {
- return nil, fmt.Errorf("profile: parse %s: %w", path, err)
- }
- var extra json.RawMessage
- if err := dec.Decode(&extra); err != io.EOF {
- if err == nil {
- return nil, fmt.Errorf("profile: trailing JSON after first object in %s", path)
- }
- return nil, fmt.Errorf("profile: trailing data after first object in %s: %w", path, err)
- }
- p.Path = path
- p.FileSHA256 = hex.EncodeToString(sum[:])
- p.Raw = raw
- if err := p.Validate(); err != nil {
- return nil, err
- }
- if strict {
- if err := p.ValidateProd2U(); err != nil {
- return nil, err
- }
- }
- return &p, nil
- }
- func (p *Profile) Validate() error {
- if p.Schema != SchemaID {
- return fmt.Errorf("profile: schema %q want %q", p.Schema, SchemaID)
- }
- if p.ProfileID == "" || p.ProfileRevision == "" {
- return fmt.Errorf("profile: missing profile_id/revision")
- }
- if p.Safety.Notes == "" {
- return fmt.Errorf("profile: safety.notes required (must document door 0 = full open)")
- }
- if p.Safety.Fan < 0 || p.Safety.Fan > 100 || p.Safety.PTC < 0 || p.Safety.PTC > 100 {
- return fmt.Errorf("profile: safety fan/ptc out of 0..100")
- }
- if p.Safety.DoorClosePercent < 0 || p.Safety.DoorClosePercent > 100 {
- return fmt.Errorf("profile: safety door_close_percent out of 0..100")
- }
- if p.Watchdog.TimeoutSeconds <= 0 {
- return fmt.Errorf("profile: watchdog.timeout_seconds required")
- }
- if p.Watchdog.GetFeedsWatchdog {
- return fmt.Errorf("profile: GET must not feed watchdog")
- }
- if !p.Watchdog.HeartbeatRepeatsDoorPercent || !p.Watchdog.HeartbeatMustNotRewriteDoorsToZero {
- return fmt.Errorf("profile: heartbeat must repeat real door percents and must not rewrite doors to 0")
- }
- if p.Protocol.Ack {
- return fmt.Errorf("profile: current Prod2U contract has no ACK")
- }
- if p.Protocol.SetAll.PayloadLength != protocol.SetAllPayloadLen {
- return fmt.Errorf("profile: SET_ALL payload_length want %d", protocol.SetAllPayloadLen)
- }
- if p.Protocol.SetAll.RetryPolicy != "never_when_outcome_unknown" {
- return fmt.Errorf("profile: retry_policy must be never_when_outcome_unknown")
- }
- if p.Temperature.ValueCount != protocol.TemperaturePayloadLen {
- return fmt.Errorf("profile: temperature.value_count want %d", protocol.TemperaturePayloadLen)
- }
- if p.Temperature.InvalidValue != int(protocol.TempInvalid) {
- return fmt.Errorf("profile: invalid_value must be 0xFF")
- }
- if p.Honesty.FirmwareVersion != "NOT_SUPPORTED" || p.Honesty.FanRPM != "NOT_SUPPORTED" ||
- p.Honesty.EncoderPosition != "NOT_SUPPORTED" || p.Honesty.PTCActualPower != "NOT_SUPPORTED" {
- return fmt.Errorf("profile: honesty must mark firmware/rpm/encoder/ptc actual as NOT_SUPPORTED")
- }
- if p.Honesty.DIMMTemperatureMap != "UNKNOWN" {
- return fmt.Errorf("profile: dimm map must be UNKNOWN")
- }
- for i := 0; i < p.Temperature.ValueCount; i++ {
- want := ids.TempChannel(i)
- found := false
- for _, s := range p.Sensors {
- if s.ID == want {
- if s.DIMMID != "" {
- return fmt.Errorf("profile: do not invent DIMM map on %s", want)
- }
- found = true
- break
- }
- }
- if !found {
- return fmt.Errorf("profile: missing sensor %s", want)
- }
- }
- 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} {
- if p.LookupActuator(id) == nil {
- return fmt.Errorf("profile: missing actuator %s", id)
- }
- }
- if p.Motors.ControlMode != "PERCENT_CLOSE" {
- return fmt.Errorf("profile: motors.control_mode must be PERCENT_CLOSE (legacy jog forbidden)")
- }
- if p.Startup.ReadinessProbe != "motor_status_startup_complete" {
- return fmt.Errorf("profile: readiness_probe must be motor_status_startup_complete")
- }
- if err := p.validateIDs(); err != nil {
- return err
- }
- if p.UART.Baud != 0 && p.UART.Baud != 115200 {
- return fmt.Errorf("profile: uart.baud must be 115200 (host serial path is fixed 115200 8N1)")
- }
- if p.UART.DataBits != 0 && p.UART.DataBits != 8 {
- return fmt.Errorf("profile: uart data_bits must be 8")
- }
- if p.UART.Parity != "" && !strings.EqualFold(p.UART.Parity, "none") && p.UART.Parity != "N" {
- return fmt.Errorf("profile: uart parity must be none")
- }
- if p.UART.StopBits != 0 && p.UART.StopBits != 1 {
- return fmt.Errorf("profile: uart stop_bits must be 1")
- }
- if p.UART.FlowControl != "" && !strings.EqualFold(p.UART.FlowControl, "none") {
- return fmt.Errorf("profile: uart flow_control must be none")
- }
- if err := p.validateProtocolCRC(); err != nil {
- return err
- }
- if !sha256Hex(p.SourceContractSHA256) {
- return fmt.Errorf("profile: source_contract_sha256 required as 64-char hex")
- }
- if !sha256Hex(p.SourceGoldenSHA256) {
- return fmt.Errorf("profile: source_golden_sha256 required as 64-char hex")
- }
- if err := p.validateEvidenceFiles(); err != nil {
- return err
- }
- return nil
- }
- func ValidateProd2U(p *Profile) error {
- return p.ValidateProd2U()
- }
- func (p *Profile) ValidateProd2U() error {
- if p.Protocol.HeaderHex == "" || !strings.EqualFold(strings.ReplaceAll(p.Protocol.HeaderHex, " ", ""), "A55A") {
- return fmt.Errorf("profile: Prod2U header_hex must be A55A")
- }
- crc := p.Protocol.CRC
- if crc.Name != "CRC-16/CCITT-FALSE" {
- return fmt.Errorf("profile: Prod2U crc.name must be CRC-16/CCITT-FALSE")
- }
- if crc.Polynomial != 0x1021 {
- return fmt.Errorf("profile: Prod2U crc.polynomial must be 0x1021")
- }
- if crc.Initial != 0xFFFF {
- return fmt.Errorf("profile: Prod2U crc.initial must be 0xFFFF")
- }
- if crc.ReflectInput || crc.ReflectOutput {
- return fmt.Errorf("profile: Prod2U crc RefIn/RefOut must be false")
- }
- if crc.XorOutput != 0 {
- return fmt.Errorf("profile: Prod2U crc.xor_output must be 0")
- }
- if crc.Coverage != "type_length_payload" {
- return fmt.Errorf("profile: Prod2U crc.coverage must be type_length_payload")
- }
- if !strings.EqualFold(crc.WireOrder, "little") && !strings.EqualFold(crc.WireOrder, "le") {
- return fmt.Errorf("profile: Prod2U crc.wire_order must be little")
- }
- wantCmd := map[string]int{
- "set_all": 1, "get_temperature": 2, "get_motor_status": 3,
- "temperature_data": 0x82, "motor_status_data": 0x83,
- }
- seenCode := map[int]string{}
- for name, code := range wantCmd {
- got, ok := p.Protocol.Commands[name]
- if !ok {
- return fmt.Errorf("profile: Prod2U missing command %s", name)
- }
- if got != code {
- return fmt.Errorf("profile: Prod2U command %s type want %d got %d", name, code, got)
- }
- if prev, ok := seenCode[code]; ok {
- return fmt.Errorf("profile: Prod2U command type 0x%02x used by %s and %s", code, prev, name)
- }
- seenCode[code] = name
- }
- for name, code := range p.Protocol.Commands {
- if want, ok := wantCmd[name]; ok {
- if code != want {
- return fmt.Errorf("profile: Prod2U command %s type want %d got %d", name, want, code)
- }
- continue
- }
- if prev, ok := seenCode[code]; ok {
- return fmt.Errorf("profile: Prod2U command type 0x%02x used by %s and %s", code, prev, name)
- }
- seenCode[code] = name
- }
- if p.Protocol.GetTemperature.PayloadLength != 0 {
- return fmt.Errorf("profile: Prod2U get_temperature request payload_length must be 0")
- }
- if p.Protocol.GetTemperature.ResponsePayloadLength != protocol.TemperaturePayloadLen {
- return fmt.Errorf("profile: Prod2U get_temperature response payload_length want %d", protocol.TemperaturePayloadLen)
- }
- if p.Protocol.GetMotorStatus.PayloadLength != 0 {
- return fmt.Errorf("profile: Prod2U get_motor_status request payload_length must be 0")
- }
- if p.Protocol.GetMotorStatus.ResponsePayloadLength != protocol.MotorStatusPayloadLen {
- return fmt.Errorf("profile: Prod2U get_motor_status response payload_length want %d", protocol.MotorStatusPayloadLen)
- }
- if p.Protocol.SetAll.PayloadLength != protocol.SetAllPayloadLen {
- return fmt.Errorf("profile: Prod2U SET_ALL payload_length want %d", protocol.SetAllPayloadLen)
- }
- if p.UART.Baud != 115200 {
- return fmt.Errorf("profile: Prod2U uart.baud must be 115200")
- }
- if p.UART.DataBits != 8 {
- return fmt.Errorf("profile: Prod2U uart.data_bits must be 8")
- }
- if !strings.EqualFold(p.UART.Parity, "none") && p.UART.Parity != "N" {
- return fmt.Errorf("profile: Prod2U uart.parity must be none/N")
- }
- if p.UART.StopBits != 1 {
- return fmt.Errorf("profile: Prod2U uart.stop_bits must be 1")
- }
- if !strings.EqualFold(p.UART.FlowControl, "none") {
- return fmt.Errorf("profile: Prod2U uart.flow_control must be none")
- }
- return nil
- }
- func rejectDuplicateJSONKeys(raw []byte) error {
- dec := json.NewDecoder(bytes.NewReader(raw))
- type frame struct {
- keys map[string]struct{}
- expectKey bool
- isObject bool
- }
- var stack []frame
- for {
- tok, err := dec.Token()
- if err == io.EOF {
- return nil
- }
- if err != nil {
- return err
- }
- switch t := tok.(type) {
- case json.Delim:
- switch t {
- case '{':
- stack = append(stack, frame{keys: map[string]struct{}{}, expectKey: true, isObject: true})
- case '[':
- stack = append(stack, frame{})
- case '}', ']':
- if len(stack) == 0 {
- return fmt.Errorf("duplicate-key scan: unmatched closer")
- }
- stack = stack[:len(stack)-1]
- if len(stack) > 0 && stack[len(stack)-1].isObject {
- stack[len(stack)-1].expectKey = true
- }
- }
- case string:
- if len(stack) == 0 {
- continue
- }
- top := &stack[len(stack)-1]
- if top.isObject && top.expectKey {
- if _, ok := top.keys[t]; ok {
- return fmt.Errorf("duplicate JSON key %q (fail closed)", t)
- }
- top.keys[t] = struct{}{}
- top.expectKey = false
- continue
- }
- if top.isObject && !top.expectKey {
- top.expectKey = true
- }
- default:
- if len(stack) > 0 && stack[len(stack)-1].isObject && !stack[len(stack)-1].expectKey {
- stack[len(stack)-1].expectKey = true
- }
- }
- }
- }
- func (p *Profile) validateEvidenceFiles() error {
- if p.Path == "" {
- return nil
- }
- dir := filepath.Dir(p.Path)
- for i := 0; i < 8; i++ {
- dir = filepath.Dir(dir)
- pairs := []struct {
- rel string
- want string
- kind string
- }{
- {filepath.Join("src", "generated", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
- {filepath.Join("evidence", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
- {filepath.Join("src", "generated", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
- {filepath.Join("evidence", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
- }
- for _, pair := range pairs {
- path := filepath.Join(dir, pair.rel)
- raw, err := os.ReadFile(path)
- if err != nil {
- continue
- }
- sum := sha256.Sum256(raw)
- got := hex.EncodeToString(sum[:])
- if !strings.EqualFold(got, pair.want) {
- return fmt.Errorf("profile: %s does not match %s (got %s want %s)", pair.kind, path, got, pair.want)
- }
- }
- if filepath.Base(dir) == "/" || dir == filepath.Dir(dir) {
- break
- }
- }
- return nil
- }
- func sha256Hex(s string) bool {
- if len(s) != 64 {
- return false
- }
- for _, c := range s {
- if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
- return false
- }
- }
- return true
- }
- func isFinite(v float64) bool {
- return !math.IsNaN(v) && !math.IsInf(v, 0)
- }
- func (p *Profile) validateProtocolCRC() error {
- if p.Protocol.HeaderHex != "" && !strings.EqualFold(strings.ReplaceAll(p.Protocol.HeaderHex, " ", ""), "A55A") {
- return fmt.Errorf("profile: protocol.header_hex must be A55A")
- }
- crc := p.Protocol.CRC
- if crc.Name != "" && !strings.Contains(strings.ToUpper(crc.Name), "CCITT") && !strings.Contains(strings.ToUpper(crc.Name), "CRC-16") {
- return fmt.Errorf("profile: crc.name must be CRC-16/CCITT-FALSE")
- }
- if crc.Polynomial != 0 && crc.Polynomial != 0x1021 {
- return fmt.Errorf("profile: crc.polynomial must be 0x1021")
- }
- if crc.Initial != 0 && crc.Initial != 0xFFFF {
- return fmt.Errorf("profile: crc.initial must be 0xFFFF")
- }
- if crc.ReflectInput || crc.ReflectOutput {
- return fmt.Errorf("profile: crc RefIn/RefOut must be false")
- }
- if crc.XorOutput != 0 {
- return fmt.Errorf("profile: crc xor_output must be 0")
- }
- if crc.Coverage != "" && crc.Coverage != "header+type+length+payload" && crc.Coverage != "type+length+payload" && crc.Coverage != "after_header" {
- // accept documented coverage strings used by the generated profile
- if !strings.Contains(strings.ToLower(crc.Coverage), "payload") && crc.Coverage != "frame_without_crc" {
- return fmt.Errorf("profile: crc.coverage %q not recognized", crc.Coverage)
- }
- }
- if crc.WireOrder != "" && !strings.EqualFold(crc.WireOrder, "little") && !strings.EqualFold(crc.WireOrder, "le") {
- return fmt.Errorf("profile: crc.wire_order must be little-endian")
- }
- seenCmd := map[int]string{}
- for name, code := range p.Protocol.Commands {
- if prev, ok := seenCmd[code]; ok {
- return fmt.Errorf("profile: command type 0x%02x used by %s and %s", code, prev, name)
- }
- seenCmd[code] = name
- }
- if p.Protocol.GetTemperature.ResponsePayloadLength != 0 && p.Protocol.GetTemperature.ResponsePayloadLength != protocol.TemperaturePayloadLen {
- return fmt.Errorf("profile: get_temperature response length want %d", protocol.TemperaturePayloadLen)
- }
- if p.Protocol.GetMotorStatus.ResponsePayloadLength != 0 && p.Protocol.GetMotorStatus.ResponsePayloadLength != protocol.MotorStatusPayloadLen {
- return fmt.Errorf("profile: get_motor_status response length want %d", protocol.MotorStatusPayloadLen)
- }
- return nil
- }
- func (p *Profile) validateIDs() error {
- seenID := map[string]string{}
- seenAlias := map[string]string{}
- srcIdx := map[int]string{}
- add := func(kind, id string, aliases []string) error {
- if id == "" {
- return fmt.Errorf("profile: empty %s id", kind)
- }
- if prev, ok := seenID[id]; ok {
- return fmt.Errorf("profile: duplicate id %s (%s and %s)", id, prev, kind)
- }
- if prev, ok := seenAlias[id]; ok {
- return fmt.Errorf("profile: id %q collides with earlier alias of %s", id, prev)
- }
- seenID[id] = kind
- local := map[string]struct{}{}
- for _, al := range aliases {
- if al == "" {
- continue
- }
- if _, dup := local[al]; dup {
- return fmt.Errorf("profile: duplicate alias %q on %s", al, id)
- }
- local[al] = struct{}{}
- if prev, ok := seenAlias[al]; ok {
- return fmt.Errorf("profile: duplicate alias %q on %s and %s", al, prev, id)
- }
- if prev, ok := seenID[al]; ok {
- return fmt.Errorf("profile: alias %q collides with id of %s", al, prev)
- }
- seenAlias[al] = id
- }
- return nil
- }
- for _, s := range p.Sensors {
- if s.ValidRange.Min > s.ValidRange.Max {
- return fmt.Errorf("profile: sensor %s min>max", s.ID)
- }
- if s.Resolution <= 0 {
- return fmt.Errorf("profile: sensor %s resolution must be > 0", s.ID)
- }
- if err := add("sensor", s.ID, s.Aliases); err != nil {
- return err
- }
- if prev, ok := srcIdx[s.SourceIndex]; ok && s.Kind == "TEMPERATURE" {
- return fmt.Errorf("profile: sensor source_index %d reused by %s and %s", s.SourceIndex, prev, s.ID)
- }
- if s.Kind == "TEMPERATURE" {
- srcIdx[s.SourceIndex] = s.ID
- }
- if !isFinite(s.Resolution) || !isFinite(s.ValidRange.Min) || !isFinite(s.ValidRange.Max) {
- return fmt.Errorf("profile: sensor %s has non-finite numeric field", s.ID)
- }
- if strings.EqualFold(s.Kind, "UNSPECIFIED") || s.Kind == "" {
- return fmt.Errorf("profile: sensor %s kind must not be UNSPECIFIED", s.ID)
- }
- if strings.EqualFold(s.FeedbackMode, "UNSPECIFIED") || s.FeedbackMode == "" {
- return fmt.Errorf("profile: sensor %s feedback_mode must not be UNSPECIFIED", s.ID)
- }
- }
- offsets := map[int]string{}
- for _, a := range p.Actuators {
- if a.CommandRange.Min > a.CommandRange.Max {
- return fmt.Errorf("profile: actuator %s min>max", a.ID)
- }
- if a.Resolution <= 0 {
- return fmt.Errorf("profile: actuator %s resolution must be > 0", a.ID)
- }
- if a.MaxSlewPerSecond < 0 {
- return fmt.Errorf("profile: actuator %s slew must be >= 0", a.ID)
- }
- if a.SafetyDefault < a.CommandRange.Min || a.SafetyDefault > a.CommandRange.Max {
- return fmt.Errorf("profile: actuator %s safety_default out of range", a.ID)
- }
- if a.SetAllOffset < 0 {
- return fmt.Errorf("profile: SET_ALL offset %d for %s is negative", a.SetAllOffset, a.ID)
- }
- if p.Protocol.SetAll.PayloadLength > 0 && a.SetAllOffset >= p.Protocol.SetAll.PayloadLength {
- return fmt.Errorf("profile: SET_ALL offset %d for %s exceeds payload_length %d", a.SetAllOffset, a.ID, p.Protocol.SetAll.PayloadLength)
- }
- if other, ok := offsets[a.SetAllOffset]; ok {
- return fmt.Errorf("profile: SET_ALL offset %d for %s already occupied by %s", a.SetAllOffset, a.ID, other)
- }
- offsets[a.SetAllOffset] = a.ID
- if !isFinite(a.Resolution) || !isFinite(a.CommandRange.Min) || !isFinite(a.CommandRange.Max) || !isFinite(a.SafetyDefault) || !isFinite(a.MaxSlewPerSecond) {
- return fmt.Errorf("profile: actuator %s has non-finite numeric field", a.ID)
- }
- if strings.EqualFold(a.Kind, "UNSPECIFIED") || a.Kind == "" {
- return fmt.Errorf("profile: actuator %s kind must not be UNSPECIFIED", a.ID)
- }
- if strings.EqualFold(a.ControlMode, "UNSPECIFIED") || a.ControlMode == "" {
- return fmt.Errorf("profile: actuator %s control_mode must not be UNSPECIFIED", a.ID)
- }
- if strings.EqualFold(a.FeedbackMode, "UNSPECIFIED") || a.FeedbackMode == "" {
- return fmt.Errorf("profile: actuator %s feedback_mode must not be UNSPECIFIED", a.ID)
- }
- if err := add("actuator", a.ID, a.Aliases); err != nil {
- return err
- }
- }
- return nil
- }
- func (p *Profile) LookupActuator(id string) *Actuator {
- for i := range p.Actuators {
- a := &p.Actuators[i]
- if a.ID == id {
- return a
- }
- for _, al := range a.Aliases {
- if al == id {
- return a
- }
- }
- }
- return nil
- }
- func (p *Profile) LookupSensor(id string) *Sensor {
- for i := range p.Sensors {
- s := &p.Sensors[i]
- if s.ID == id {
- return s
- }
- for _, al := range s.Aliases {
- if al == id {
- return s
- }
- }
- }
- return nil
- }
- func (p *Profile) InterByteTimeout() time.Duration {
- ms := p.Timeouts.FrameInterByteMS
- if ms <= 0 {
- ms = p.UART.InterByteTimeoutMS
- }
- if ms <= 0 {
- ms = 10
- }
- return time.Duration(ms) * time.Millisecond
- }
- func (p *Profile) GetResponseTimeout() time.Duration {
- ms := p.Timeouts.HostGetResponseMS
- if ms <= 0 {
- ms = 5000
- }
- return time.Duration(ms) * time.Millisecond
- }
- func (p *Profile) FirmwareWatchdog() time.Duration {
- return time.Duration(p.Watchdog.TimeoutSeconds) * time.Second
- }
- func (p *Profile) MinSamplePeriod() time.Duration {
- // UART + sequential 27-channel scan: do not let clients request faster than 50ms.
- return 50 * time.Millisecond
- }
- func (p *Profile) RecommendedSamplePeriod() time.Duration {
- scan := time.Duration(p.Timeouts.TemperatureScanBusyMS) * time.Millisecond
- if scan <= 0 {
- scan = 5 * time.Second
- }
- // Host cannot honestly recommend faster than the blocking temperature scan.
- return scan
- }
- // ProfileIdentityDigest is a profile-file digest. It is NOT the API
- // Capability Hash; callers must use caphash.HashCanonicalCapabilities /
- // device.BuildCanonicalCapabilities.
- func (p *Profile) ProfileIdentityDigest() string {
- type view struct {
- ProfileID string
- ProfileRevision string
- Contract string
- Sensors []string
- Actuators []string
- Honesty Honesty
- Ack bool
- Readiness string
- API string
- Safety Safety
- Slew []float64
- Units []string
- Ranges []Range
- }
- v := view{
- ProfileID: p.ProfileID, ProfileRevision: p.ProfileRevision, Contract: p.SourceContractSHA256,
- Honesty: p.Honesty, Ack: p.Protocol.Ack, Readiness: p.Startup.ReadinessProbe, API: p.APIVersion,
- Safety: p.Safety,
- }
- for _, s := range p.Sensors {
- v.Sensors = append(v.Sensors, s.ID)
- v.Units = append(v.Units, s.Unit)
- v.Ranges = append(v.Ranges, s.ValidRange)
- }
- for _, a := range p.Actuators {
- v.Actuators = append(v.Actuators, a.ID)
- v.Slew = append(v.Slew, a.MaxSlewPerSecond)
- v.Units = append(v.Units, a.Unit)
- v.Ranges = append(v.Ranges, a.CommandRange)
- }
- b, _ := json.Marshal(v)
- sum := sha256.Sum256(b)
- return hex.EncodeToString(sum[:])
- }
- func (p *Profile) SafeSetAll() protocol.SetAll {
- s := protocol.SetAll{
- DoorZ: uint8(p.Safety.DoorClosePercent),
- DoorX: uint8(p.Safety.DoorClosePercent),
- DoorY: uint8(p.Safety.DoorClosePercent),
- }
- for i := range s.Fan {
- s.Fan[i] = uint8(p.Safety.Fan)
- }
- for i := range s.PTC {
- s.PTC[i] = uint8(p.Safety.PTC)
- }
- return s
- }
- func (p *Profile) Baud() int {
- if p.UART.Baud == 0 {
- return 115200
- }
- return p.UART.Baud
- }
|