| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701 |
- package app
- import (
- "context"
- "errors"
- "fmt"
- "log/slog"
- "os"
- "sync"
- "sync/atomic"
- "time"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
- "google.golang.org/protobuf/types/known/durationpb"
- "hth/internal/backend"
- "hth/internal/config"
- "hth/internal/device"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/grpcserver"
- "hth/internal/profile"
- "hth/internal/protocol"
- "hth/internal/protocol6400"
- "hth/internal/safety"
- "hth/internal/sdnotify"
- "hth/internal/telemetry"
- "hth/internal/thermalservice"
- )
- var APIVersion = "hth.api.v1"
- type App struct {
- Cfg *config.Config
- Profile *profile.Profile
- Dev *device.Device
- Thermal *thermalservice.Service
- srv atomic.Pointer[grpcserver.Servers]
- stopRequested atomic.Bool
- log *slog.Logger
- inst string
- stopOnce sync.Once
- }
- func CheckConfig(path, backendOverride string) error {
- _, _, err := loadValidated(path, backendOverride)
- if err != nil {
- return err
- }
- fmt.Println("config: OK")
- return nil
- }
- func loadValidated(path, backendOverride string) (*config.Config, *profile.Profile, error) {
- if path == "" {
- return nil, nil, fmt.Errorf("config path required")
- }
- cfg, err := config.Load(path)
- if err != nil {
- return nil, nil, err
- }
- if err := cfg.ApplyBackendOverride(backendOverride); err != nil {
- return nil, nil, err
- }
- if cfg.IsThermal6400() {
- if err := cfg.Validate(nil); err != nil {
- return nil, nil, err
- }
- return cfg, nil, nil
- }
- p, err := profile.LoadStrict(cfg.Profile)
- if err != nil {
- return nil, nil, err
- }
- if err := cfg.Validate(p); err != nil {
- return nil, nil, err
- }
- contract, err := safety.BuildEffectiveSafetyContract(p, cfg.Safety)
- if err != nil {
- return nil, nil, fmt.Errorf("effective safety contract: %w", err)
- }
- payload, err := contract.Frame.Payload()
- if err != nil {
- return nil, nil, fmt.Errorf("effective safety payload: %w", err)
- }
- if _, err := protocol.Encode(protocol.TypeSetAll, payload); err != nil {
- return nil, nil, err
- }
- return cfg, p, nil
- }
- func New(path, backendOverride string, log *slog.Logger) (*App, error) {
- cfg, p, err := loadValidated(path, backendOverride)
- if err != nil {
- return nil, err
- }
- if log == nil {
- log = slog.New(slog.NewTextHandler(os.Stderr, nil))
- }
- if cfg.IsThermal6400() {
- b, err := newThermalBackend(cfg)
- if err != nil {
- return nil, err
- }
- thermal := thermalservice.New(cfg.DeviceID, cfg.Thermal.FirmwareProfile, b, cfg.ThermalTimeout(), cfg.ThermalRetries())
- return &App{Cfg: cfg, Thermal: thermal, log: log, inst: fmt.Sprintf("hthd-%d", time.Now().UnixNano())}, nil
- }
- b, err := newBackend(cfg, p)
- if err != nil {
- return nil, err
- }
- inst := fmt.Sprintf("hthd-%d", time.Now().UnixNano())
- dev := device.New(device.Params{Config: cfg, Profile: p, Backend: b, Logger: log, InstanceID: inst})
- return &App{Cfg: cfg, Profile: p, Dev: dev, log: log, inst: inst}, nil
- }
- func (a *App) grpcServers() *grpcserver.Servers {
- return a.srv.Load()
- }
- func (a *App) adoptServers(srv *grpcserver.Servers) bool {
- if a.stopRequested.Load() {
- return true
- }
- a.srv.Store(srv)
- return a.stopRequested.Load()
- }
- func (a *App) Run(ctx context.Context) error {
- if a.Thermal != nil {
- if err := a.Thermal.Open(ctx); err != nil {
- return err
- }
- } else {
- a.Dev.Start(ctx)
- }
- if a.stopRequested.Load() {
- if a.Dev != nil {
- a.Dev.Stop()
- }
- if a.Thermal != nil {
- _ = a.Thermal.Close()
- }
- return nil
- }
- srv, err := grpcserver.Start(a.Cfg, a)
- if err != nil {
- if a.Dev != nil {
- a.Dev.Stop()
- }
- if a.Thermal != nil {
- _ = a.Thermal.Close()
- }
- return err
- }
- if a.adoptServers(srv) {
- srv.Stop()
- if a.Dev != nil {
- a.Dev.Stop()
- }
- if a.Thermal != nil {
- _ = a.Thermal.Close()
- }
- return nil
- }
- a.log.Info("hthd listening", "observe", a.Cfg.Sockets.Observe, "control", a.Cfg.Sockets.Control, "backend", a.Cfg.Backend, "api", APIVersion)
- if err := sdnotify.Ready(); err != nil {
- a.log.Warn("sd_notify READY failed", "err", err)
- }
- var wdStop chan struct{}
- if sdnotify.WatchdogEnabled() {
- wdStop = make(chan struct{})
- iv := sdnotify.WatchdogInterval()
- if iv <= 0 {
- iv = 10 * time.Second
- }
- go func() {
- t := time.NewTicker(iv)
- defer t.Stop()
- for {
- select {
- case <-wdStop:
- return
- case <-t.C:
- if a.watchdogOK() {
- _ = sdnotify.Watchdog()
- }
- }
- }
- }()
- }
- select {
- case <-ctx.Done():
- case err := <-srv.ErrC:
- a.log.Error("grpc server exited", "err", err)
- if wdStop != nil {
- close(wdStop)
- }
- a.shutdown()
- _ = sdnotify.Stopping()
- sdnotify.Close()
- return err
- }
- if wdStop != nil {
- close(wdStop)
- }
- a.shutdown()
- _ = sdnotify.Stopping()
- sdnotify.Close()
- return nil
- }
- func (a *App) WatchdogShouldPet() bool {
- return a.watchdogOK()
- }
- func (a *App) watchdogOK() bool {
- srv := a.grpcServers()
- if srv == nil {
- return false
- }
- if !srv.ObserveAlive() || !srv.ControlAlive() {
- return false
- }
- if a.Thermal != nil {
- return true
- }
- if a.Dev == nil {
- return false
- }
- maxTxn := a.Dev.MaxSerialTxn()
- if a.Dev.SerialBusy() > maxTxn {
- return false
- }
- prog := a.Dev.ActorProgress()
- if prog.IsZero() || time.Since(prog) > maxTxn+2*time.Second {
- return false
- }
- return true
- }
- func (a *App) shutdown() {
- a.stopOnce.Do(func() {
- a.stopRequested.Store(true)
- if a.Dev != nil {
- a.Dev.Stop()
- }
- if a.Thermal != nil {
- _ = a.Thermal.Close()
- }
- if srv := a.grpcServers(); srv != nil {
- srv.Stop()
- }
- })
- }
- func (a *App) Stop() {
- a.shutdown()
- }
- func (a *App) device(id string) (*device.Device, error) {
- if id == "" {
- id = a.Cfg.DeviceID
- }
- if a.Dev == nil || a.Dev.ID() != id {
- return nil, status.Errorf(codes.NotFound, "device %s", id)
- }
- return a.Dev, nil
- }
- func (a *App) ListDevices(context.Context) (*hthv1.ListDevicesResponse, error) {
- if a.Thermal != nil {
- return &hthv1.ListDevicesResponse{Devices: []*hthv1.DeviceInfo{{
- Identity: &hthv1.DeviceIdentity{
- DeviceId: a.Cfg.DeviceID, DisplayName: a.Cfg.DisplayName,
- ProfileId: a.Thermal.Profile(), ProtocolContractHash: protocol6400.ContractSHA256,
- BackendKind: a.Thermal.BackendKind(),
- },
- Lifecycle: hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY,
- DeviceEpoch: 1,
- }}}, nil
- }
- return &hthv1.ListDevicesResponse{Devices: []*hthv1.DeviceInfo{a.Dev.Info()}}, nil
- }
- func (a *App) Capabilities(ctx context.Context, id string) (*hthv1.Capabilities, error) {
- if a.Thermal != nil {
- if id != "" && id != a.Cfg.DeviceID {
- return nil, status.Errorf(codes.NotFound, "device %s", id)
- }
- return &hthv1.Capabilities{
- DeviceId: a.Cfg.DeviceID, ProfileId: a.Thermal.Profile(),
- ProtocolContractHash: protocol6400.ContractSHA256, ApiVersion: APIVersion,
- AckSupported: true, StatusQuerySupported: true,
- Timing: &hthv1.TimingCapabilities{
- ControlDispatchWorstCaseMs: uint32(a.Cfg.Thermal.TransactionTimeoutMS * (a.Cfg.Thermal.Retries + 1)),
- RecommendedRpcDeadlineMs: uint32(a.Cfg.Thermal.TransactionTimeoutMS*(a.Cfg.Thermal.Retries+1) + 250),
- RecommendedSamplePeriodMs: 200,
- RecommendedSnapshotSubscriptionPeriodMs: 200,
- MaxPendingContinuousActions: 1,
- },
- Notes: "6400 autonomous target/ACK/snapshot API; ACK confirms commit, not thermal attainment",
- }, nil
- }
- d, err := a.device(id)
- if err != nil {
- return nil, err
- }
- return d.Capabilities(), nil
- }
- func (a *App) Snapshot(ctx context.Context, id string) (*hthv1.Snapshot, error) {
- d, err := a.device(id)
- if err != nil {
- return nil, err
- }
- return d.Snapshot(), nil
- }
- func (a *App) SubscribeTelemetry(ctx context.Context, id string, resume uint64, emit func(*hthv1.Snapshot) error) error {
- d, err := a.device(id)
- if err != nil {
- return err
- }
- peer := peerKey(ctx)
- sub, replay, gap, err := d.SubscribeTelemetry(resume, peer)
- if err != nil {
- if errors.Is(err, telemetry.ErrResumeOutOfRange) {
- return status.Error(codes.OutOfRange, err.Error())
- }
- return status.Error(codes.ResourceExhausted, err.Error())
- }
- defer sub.Cancel()
- if gap != nil {
- s := d.Snapshot()
- if s != nil {
- s.DataGap = true
- s.DroppedTelemetryCount = gap.DroppedCount
- if err := emit(s); err != nil {
- return err
- }
- }
- }
- for _, s := range replay {
- if err := emit(s); err != nil {
- return err
- }
- }
- for {
- select {
- case <-ctx.Done():
- return nil
- case s, ok := <-sub.C:
- if !ok {
- return nil
- }
- if err := emit(s); err != nil {
- return err
- }
- }
- }
- }
- func (a *App) SubscribeEvents(ctx context.Context, id string, resume uint64, emit func(*hthv1.Event) error) error {
- d, err := a.device(id)
- if err != nil {
- return err
- }
- peer := peerKey(ctx)
- sub, replay, gap, err := d.SubscribeEvents(resume, peer)
- if err != nil {
- if errors.Is(err, telemetry.ErrResumeOutOfRange) {
- return status.Error(codes.OutOfRange, err.Error())
- }
- return status.Error(codes.ResourceExhausted, err.Error())
- }
- defer sub.Cancel()
- if gap != nil && gap.EventId != 0 {
- return status.Error(codes.Internal, "event stream gap must not carry a global event_id")
- }
- if gap != nil && len(replay) > 0 && replay[0].GetDeliveryGap() == nil {
- replay[0].DeliveryGap = &hthv1.DeliveryGap{
- DroppedCount: gap.DroppedCount,
- LastContiguousEventId: gap.LastContiguousEventId,
- RequestedResumeAfterEventId: gap.ResumeAfterEventId,
- OldestAvailableEventId: 0,
- }
- }
- for _, e := range replay {
- if err := emit(e); err != nil {
- return err
- }
- }
- for {
- select {
- case <-ctx.Done():
- return nil
- case e, ok := <-sub.C:
- if !ok {
- return nil
- }
- if err := emit(e); err != nil {
- return err
- }
- }
- }
- }
- func (a *App) Faults(ctx context.Context, id string, include bool) (*hthv1.GetFaultsResponse, error) {
- d, err := a.device(id)
- if err != nil {
- return nil, err
- }
- return &hthv1.GetFaultsResponse{
- Faults: d.Faults(include),
- DeviceFaultQuerySupported: false,
- HostFaultReportingSupported: true,
- DeviceNativeFaultQuerySupported: false,
- DeviceFaultSource: "host_inferred; MOTOR_STATUS axis flags only; no device fault queue",
- }, nil
- }
- func (a *App) WatchHealth(ctx context.Context, emit func(*hthv1.HealthStatus) error) error {
- t := time.NewTicker(500 * time.Millisecond)
- defer t.Stop()
- send := func() error {
- srv := a.grpcServers()
- host := hthv1.HostHealth_HOST_HEALTH_SERVING
- if srv != nil && (!srv.ObserveAlive() || !srv.ControlAlive()) {
- host = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
- }
- msg := "process=SERVING"
- if a.Dev != nil {
- lc := a.Dev.Snapshot().GetLifecycle()
- msg += fmt.Sprintf(" device_lifecycle=%s", lc.String())
- switch a.Cfg.Backend {
- case config.BackendReplay:
- if a.Dev.ReplayComplete() {
- msg += " replay_completion=COMPLETE device_readiness=REPLAY_COMPLETE control_availability=READ_ONLY"
- } else {
- msg += " replay_completion=IN_PROGRESS control_availability=READ_ONLY"
- }
- case config.BackendSerial, config.BackendMock:
- snap := a.Dev.Snapshot()
- if snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
- snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING ||
- snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING {
- msg += " device_readiness=" + snap.GetDeviceReadiness().String() + " control_availability=SAFE_LATCHED"
- } else if lc == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY {
- msg += " device_readiness=READY control_availability=AVAILABLE"
- } else {
- msg += " device_readiness=NOT_READY control_availability=UNAVAILABLE"
- }
- }
- }
- if srv != nil {
- if srv.ObserveAlive() {
- msg += " observe_server=ALIVE"
- } else {
- msg += " observe_server=DOWN"
- }
- if srv.ControlAlive() {
- msg += " control_server=ALIVE"
- } else {
- msg += " control_server=DOWN"
- }
- }
- listed, _ := a.ListDevices(ctx)
- hs := &hthv1.HealthStatus{Host: host, Devices: listed.GetDevices(), Message: msg}
- if srv != nil {
- if srv.ObserveAlive() {
- hs.ObserveService = hthv1.HostHealth_HOST_HEALTH_SERVING
- } else {
- hs.ObserveService = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
- }
- if srv.ControlAlive() {
- hs.ControlService = hthv1.HostHealth_HOST_HEALTH_SERVING
- } else {
- hs.ControlService = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
- }
- }
- if a.Dev != nil {
- snap := a.Dev.Snapshot()
- hs.TransportState = snap.GetTransportState()
- hs.DeviceReadiness = snap.GetDeviceReadiness()
- hs.SafetyControlMode = snap.GetSafetyControlMode()
- }
- return emit(hs)
- }
- if err := send(); err != nil {
- return err
- }
- for {
- select {
- case <-ctx.Done():
- return nil
- case <-t.C:
- if err := send(); err != nil {
- return err
- }
- }
- }
- }
- func (a *App) AcquireLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.ControlLease, error) {
- d, err := a.device(req.DeviceId)
- if err != nil {
- return nil, err
- }
- ttl := time.Duration(0)
- if req.Ttl != nil {
- ttl = req.Ttl.AsDuration()
- }
- return d.AcquireLease(ctx, req.Holder, ttl)
- }
- func (a *App) RenewLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.ControlLease, error) {
- d, err := a.device(req.DeviceId)
- if err != nil {
- return nil, err
- }
- ttl := time.Duration(0)
- if req.Ttl != nil {
- ttl = req.Ttl.AsDuration()
- }
- return d.RenewLease(ctx, req.LeaseId, req.LeaseEpoch, ttl)
- }
- func (a *App) ReleaseLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) error {
- d, err := a.device(req.DeviceId)
- if err != nil {
- return err
- }
- return d.ReleaseLease(ctx, req.LeaseId, req.LeaseEpoch)
- }
- func (a *App) ValidateAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error) {
- id := ""
- if batch != nil {
- id = batch.DeviceId
- }
- d, err := a.device(id)
- if err != nil {
- return nil, err
- }
- return d.ValidateAction(ctx, batch), nil
- }
- func (a *App) ApplyAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error) {
- id := ""
- if batch != nil {
- id = batch.DeviceId
- }
- d, err := a.device(id)
- if err != nil {
- return nil, err
- }
- return d.ApplyAction(ctx, batch), nil
- }
- func (a *App) EnterSafeMode(ctx context.Context, req *hthv1.EnterSafeModeRequest) (*hthv1.ActionResult, error) {
- d, err := a.device(req.DeviceId)
- if err != nil {
- return nil, err
- }
- return d.EnterSafeMode(ctx, req.LeaseId, req.LeaseEpoch, req.Reason), nil
- }
- func (a *App) ResumeFromSafe(ctx context.Context, req *hthv1.ResumeFromSafeRequest) (*hthv1.ActionResult, error) {
- d, err := a.device(req.DeviceId)
- if err != nil {
- return nil, err
- }
- return d.ResumeFromSafe(ctx, req.LeaseId, req.LeaseEpoch, req.Batch), nil
- }
- func (a *App) StepReplay(ctx context.Context, id string) (*hthv1.StepReplayResponse, error) {
- d, err := a.device(id)
- if err != nil {
- return nil, err
- }
- res := d.StepReplay(ctx)
- resp := &hthv1.StepReplayResponse{
- Advanced: res.GetAccepted(),
- Message: res.GetMessage(),
- Snapshot: d.LastStepSnapshot(),
- Event: d.LastStepEvent(),
- }
- if resp.Snapshot == nil {
- resp.Snapshot = d.Snapshot()
- }
- if res.GetMessage() == "EOF" {
- resp.Advanced = false
- resp.Message = "EOF replay_completion=COMPLETE"
- }
- return resp, nil
- }
- func (a *App) StepReplayObserve(ctx context.Context, id string) (*hthv1.StepReplayResponse, error) {
- if a.Cfg == nil || !a.Cfg.Replay.AllowObserveStep {
- return nil, status.Error(codes.PermissionDenied, "StepReplay is a replay-admin ControlService RPC; observe clients cannot mutate global replay")
- }
- return a.StepReplay(ctx, id)
- }
- func (a *App) SetThermalTarget(ctx context.Context, req *hthv1.SetThermalTargetRequest) (*hthv1.ThermalCommandResult, error) {
- if a.Thermal == nil {
- return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
- }
- return a.Thermal.SetTarget(ctx, req)
- }
- func (a *App) StopThermal(ctx context.Context, req *hthv1.StopThermalRequest) (*hthv1.ThermalCommandResult, error) {
- if a.Thermal == nil {
- return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
- }
- return a.Thermal.Stop(ctx, req)
- }
- func (a *App) GetThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
- if a.Thermal == nil {
- return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
- }
- return a.Thermal.GetSnapshot(ctx, req)
- }
- func (a *App) CaptureThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
- if a.Thermal == nil {
- return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
- }
- return a.Thermal.CaptureSnapshot(ctx, req)
- }
- func (a *App) RunThermalStimulus(ctx context.Context, req *hthv1.RunThermalStimulusRequest) (*hthv1.ThermalCommandResult, error) {
- if a.Thermal == nil {
- return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
- }
- return a.Thermal.RunStimulus(ctx, req)
- }
- func newBackend(cfg *config.Config, p *profile.Profile) (backend.Backend, error) {
- switch cfg.Backend {
- case config.BackendMock:
- m := backend.NewMock(cfg.Mock.Seed, cfg.Mock.StartupComplete)
- m.FirstOrderThermal = cfg.Mock.FirstOrderThermal
- if cfg.Mock.SlowGetMS > 0 {
- m.SetSlowGet(time.Duration(cfg.Mock.SlowGetMS) * time.Millisecond)
- }
- return m, nil
- case config.BackendReplay:
- rp := backend.NewReplay(cfg.Replay.Path, cfg.Replay.Speed, cfg.Replay.Step, cfg.Replay.FromEventID)
- rp.SetContract(p.APIVersion, device.CapabilityHashOf(cfg, p))
- return rp, nil
- case config.BackendSerial:
- return newSerialBackend(cfg, p)
- default:
- return nil, fmt.Errorf("unknown backend %s", cfg.Backend)
- }
- }
- func DoctorText(cfg *config.Config, p *profile.Profile) string {
- if cfg != nil && cfg.IsThermal6400() {
- return fmt.Sprintf(
- "api_version=%s\nproduct=%s\nfirmware_profile=%s\ncontract_sha256=%s\nbackend=%s\nserial_path=%s\nobserve=%s\ncontrol=%s\ntransaction_timeout=%dms retries=%d\nhardware_validation=NOT_RUN\n",
- APIVersion, cfg.Product, cfg.Thermal.FirmwareProfile, protocol6400.ContractSHA256,
- cfg.Backend, cfg.Serial.Path, cfg.Sockets.Observe, cfg.Sockets.Control,
- cfg.Thermal.TransactionTimeoutMS, cfg.Thermal.Retries,
- )
- }
- ov := config.Safety{}
- if cfg != nil {
- ov = cfg.Safety
- }
- contract, err := safety.BuildEffectiveSafetyContract(p, ov)
- if err != nil {
- return fmt.Sprintf("effective_safety_contract=INVALID %v\n", err)
- }
- safe := contract.Frame
- raw, _ := safe.Encode()
- return fmt.Sprintf(
- "api_version=%s\nprofile_id=%s rev=%s\nprofile_sha256=%s\ncontract_sha256=%s\ncapability_hash=%s\nbackend=%s\nserial_path=%s\nobserve=%s\ncontrol=%s\nheartbeat=%dms firmware_watchdog=%ds\nsafety_fan=%d safety_ptc=%d safety_door=%d (door 0=FULL OPEN)\nsafe_frame=%x\n",
- APIVersion, p.ProfileID, p.ProfileRevision, p.FileSHA256, p.SourceContractSHA256, device.CapabilityHashOf(cfg, p),
- cfg.Backend, cfg.Serial.Path, cfg.Sockets.Observe, cfg.Sockets.Control,
- cfg.Watchdog.HeartbeatPeriodMS, p.Watchdog.TimeoutSeconds,
- safe.Fan[0], safe.PTC[0], safe.DoorX, raw,
- )
- }
- func TTL(d *durationpb.Duration) time.Duration {
- if d == nil {
- return 0
- }
- return d.AsDuration()
- }
- func peerKey(ctx context.Context) string {
- cred, ok := grpcserver.PeerFromContext(ctx)
- if !ok || cred.PID == 0 {
- return ""
- }
- return fmt.Sprintf("uid=%d,gid=%d,pid=%d", cred.UID, cred.GID, cred.PID)
- }
|