app.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. package app
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log/slog"
  7. "os"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "google.golang.org/grpc/codes"
  12. "google.golang.org/grpc/status"
  13. "google.golang.org/protobuf/types/known/durationpb"
  14. "hth/internal/backend"
  15. "hth/internal/config"
  16. "hth/internal/device"
  17. hthv1 "hth/internal/gen/hth/api/v1"
  18. "hth/internal/grpcserver"
  19. "hth/internal/profile"
  20. "hth/internal/protocol"
  21. "hth/internal/protocol6400"
  22. "hth/internal/safety"
  23. "hth/internal/sdnotify"
  24. "hth/internal/telemetry"
  25. "hth/internal/thermalservice"
  26. )
  27. var APIVersion = "hth.api.v1"
  28. type App struct {
  29. Cfg *config.Config
  30. Profile *profile.Profile
  31. Dev *device.Device
  32. Thermal *thermalservice.Service
  33. srv atomic.Pointer[grpcserver.Servers]
  34. stopRequested atomic.Bool
  35. log *slog.Logger
  36. inst string
  37. stopOnce sync.Once
  38. }
  39. func CheckConfig(path, backendOverride string) error {
  40. _, _, err := loadValidated(path, backendOverride)
  41. if err != nil {
  42. return err
  43. }
  44. fmt.Println("config: OK")
  45. return nil
  46. }
  47. func loadValidated(path, backendOverride string) (*config.Config, *profile.Profile, error) {
  48. if path == "" {
  49. return nil, nil, fmt.Errorf("config path required")
  50. }
  51. cfg, err := config.Load(path)
  52. if err != nil {
  53. return nil, nil, err
  54. }
  55. if err := cfg.ApplyBackendOverride(backendOverride); err != nil {
  56. return nil, nil, err
  57. }
  58. if cfg.IsThermal6400() {
  59. if err := cfg.Validate(nil); err != nil {
  60. return nil, nil, err
  61. }
  62. return cfg, nil, nil
  63. }
  64. p, err := profile.LoadStrict(cfg.Profile)
  65. if err != nil {
  66. return nil, nil, err
  67. }
  68. if err := cfg.Validate(p); err != nil {
  69. return nil, nil, err
  70. }
  71. contract, err := safety.BuildEffectiveSafetyContract(p, cfg.Safety)
  72. if err != nil {
  73. return nil, nil, fmt.Errorf("effective safety contract: %w", err)
  74. }
  75. payload, err := contract.Frame.Payload()
  76. if err != nil {
  77. return nil, nil, fmt.Errorf("effective safety payload: %w", err)
  78. }
  79. if _, err := protocol.Encode(protocol.TypeSetAll, payload); err != nil {
  80. return nil, nil, err
  81. }
  82. return cfg, p, nil
  83. }
  84. func New(path, backendOverride string, log *slog.Logger) (*App, error) {
  85. cfg, p, err := loadValidated(path, backendOverride)
  86. if err != nil {
  87. return nil, err
  88. }
  89. if log == nil {
  90. log = slog.New(slog.NewTextHandler(os.Stderr, nil))
  91. }
  92. if cfg.IsThermal6400() {
  93. b, err := newThermalBackend(cfg)
  94. if err != nil {
  95. return nil, err
  96. }
  97. thermal := thermalservice.New(cfg.DeviceID, cfg.Thermal.FirmwareProfile, b, cfg.ThermalTimeout(), cfg.ThermalRetries())
  98. return &App{Cfg: cfg, Thermal: thermal, log: log, inst: fmt.Sprintf("hthd-%d", time.Now().UnixNano())}, nil
  99. }
  100. b, err := newBackend(cfg, p)
  101. if err != nil {
  102. return nil, err
  103. }
  104. inst := fmt.Sprintf("hthd-%d", time.Now().UnixNano())
  105. dev := device.New(device.Params{Config: cfg, Profile: p, Backend: b, Logger: log, InstanceID: inst})
  106. return &App{Cfg: cfg, Profile: p, Dev: dev, log: log, inst: inst}, nil
  107. }
  108. func (a *App) grpcServers() *grpcserver.Servers {
  109. return a.srv.Load()
  110. }
  111. func (a *App) adoptServers(srv *grpcserver.Servers) bool {
  112. if a.stopRequested.Load() {
  113. return true
  114. }
  115. a.srv.Store(srv)
  116. return a.stopRequested.Load()
  117. }
  118. func (a *App) Run(ctx context.Context) error {
  119. if a.Thermal != nil {
  120. if err := a.Thermal.Open(ctx); err != nil {
  121. return err
  122. }
  123. } else {
  124. a.Dev.Start(ctx)
  125. }
  126. if a.stopRequested.Load() {
  127. if a.Dev != nil {
  128. a.Dev.Stop()
  129. }
  130. if a.Thermal != nil {
  131. _ = a.Thermal.Close()
  132. }
  133. return nil
  134. }
  135. srv, err := grpcserver.Start(a.Cfg, a)
  136. if err != nil {
  137. if a.Dev != nil {
  138. a.Dev.Stop()
  139. }
  140. if a.Thermal != nil {
  141. _ = a.Thermal.Close()
  142. }
  143. return err
  144. }
  145. if a.adoptServers(srv) {
  146. srv.Stop()
  147. if a.Dev != nil {
  148. a.Dev.Stop()
  149. }
  150. if a.Thermal != nil {
  151. _ = a.Thermal.Close()
  152. }
  153. return nil
  154. }
  155. a.log.Info("hthd listening", "observe", a.Cfg.Sockets.Observe, "control", a.Cfg.Sockets.Control, "backend", a.Cfg.Backend, "api", APIVersion)
  156. if err := sdnotify.Ready(); err != nil {
  157. a.log.Warn("sd_notify READY failed", "err", err)
  158. }
  159. var wdStop chan struct{}
  160. if sdnotify.WatchdogEnabled() {
  161. wdStop = make(chan struct{})
  162. iv := sdnotify.WatchdogInterval()
  163. if iv <= 0 {
  164. iv = 10 * time.Second
  165. }
  166. go func() {
  167. t := time.NewTicker(iv)
  168. defer t.Stop()
  169. for {
  170. select {
  171. case <-wdStop:
  172. return
  173. case <-t.C:
  174. if a.watchdogOK() {
  175. _ = sdnotify.Watchdog()
  176. }
  177. }
  178. }
  179. }()
  180. }
  181. select {
  182. case <-ctx.Done():
  183. case err := <-srv.ErrC:
  184. a.log.Error("grpc server exited", "err", err)
  185. if wdStop != nil {
  186. close(wdStop)
  187. }
  188. a.shutdown()
  189. _ = sdnotify.Stopping()
  190. sdnotify.Close()
  191. return err
  192. }
  193. if wdStop != nil {
  194. close(wdStop)
  195. }
  196. a.shutdown()
  197. _ = sdnotify.Stopping()
  198. sdnotify.Close()
  199. return nil
  200. }
  201. func (a *App) WatchdogShouldPet() bool {
  202. return a.watchdogOK()
  203. }
  204. func (a *App) watchdogOK() bool {
  205. srv := a.grpcServers()
  206. if srv == nil {
  207. return false
  208. }
  209. if !srv.ObserveAlive() || !srv.ControlAlive() {
  210. return false
  211. }
  212. if a.Thermal != nil {
  213. return true
  214. }
  215. if a.Dev == nil {
  216. return false
  217. }
  218. maxTxn := a.Dev.MaxSerialTxn()
  219. if a.Dev.SerialBusy() > maxTxn {
  220. return false
  221. }
  222. prog := a.Dev.ActorProgress()
  223. if prog.IsZero() || time.Since(prog) > maxTxn+2*time.Second {
  224. return false
  225. }
  226. return true
  227. }
  228. func (a *App) shutdown() {
  229. a.stopOnce.Do(func() {
  230. a.stopRequested.Store(true)
  231. if a.Dev != nil {
  232. a.Dev.Stop()
  233. }
  234. if a.Thermal != nil {
  235. _ = a.Thermal.Close()
  236. }
  237. if srv := a.grpcServers(); srv != nil {
  238. srv.Stop()
  239. }
  240. })
  241. }
  242. func (a *App) Stop() {
  243. a.shutdown()
  244. }
  245. func (a *App) device(id string) (*device.Device, error) {
  246. if id == "" {
  247. id = a.Cfg.DeviceID
  248. }
  249. if a.Dev == nil || a.Dev.ID() != id {
  250. return nil, status.Errorf(codes.NotFound, "device %s", id)
  251. }
  252. return a.Dev, nil
  253. }
  254. func (a *App) ListDevices(context.Context) (*hthv1.ListDevicesResponse, error) {
  255. if a.Thermal != nil {
  256. return &hthv1.ListDevicesResponse{Devices: []*hthv1.DeviceInfo{{
  257. Identity: &hthv1.DeviceIdentity{
  258. DeviceId: a.Cfg.DeviceID, DisplayName: a.Cfg.DisplayName,
  259. ProfileId: a.Thermal.Profile(), ProtocolContractHash: protocol6400.ContractSHA256,
  260. BackendKind: a.Thermal.BackendKind(),
  261. },
  262. Lifecycle: hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY,
  263. DeviceEpoch: 1,
  264. }}}, nil
  265. }
  266. return &hthv1.ListDevicesResponse{Devices: []*hthv1.DeviceInfo{a.Dev.Info()}}, nil
  267. }
  268. func (a *App) Capabilities(ctx context.Context, id string) (*hthv1.Capabilities, error) {
  269. if a.Thermal != nil {
  270. if id != "" && id != a.Cfg.DeviceID {
  271. return nil, status.Errorf(codes.NotFound, "device %s", id)
  272. }
  273. return &hthv1.Capabilities{
  274. DeviceId: a.Cfg.DeviceID, ProfileId: a.Thermal.Profile(),
  275. ProtocolContractHash: protocol6400.ContractSHA256, ApiVersion: APIVersion,
  276. AckSupported: true, StatusQuerySupported: true,
  277. Timing: &hthv1.TimingCapabilities{
  278. ControlDispatchWorstCaseMs: uint32(a.Cfg.Thermal.TransactionTimeoutMS * (a.Cfg.Thermal.Retries + 1)),
  279. RecommendedRpcDeadlineMs: uint32(a.Cfg.Thermal.TransactionTimeoutMS*(a.Cfg.Thermal.Retries+1) + 250),
  280. RecommendedSamplePeriodMs: 200,
  281. RecommendedSnapshotSubscriptionPeriodMs: 200,
  282. MaxPendingContinuousActions: 1,
  283. },
  284. Notes: "6400 autonomous target/ACK/snapshot API; ACK confirms commit, not thermal attainment",
  285. }, nil
  286. }
  287. d, err := a.device(id)
  288. if err != nil {
  289. return nil, err
  290. }
  291. return d.Capabilities(), nil
  292. }
  293. func (a *App) Snapshot(ctx context.Context, id string) (*hthv1.Snapshot, error) {
  294. d, err := a.device(id)
  295. if err != nil {
  296. return nil, err
  297. }
  298. return d.Snapshot(), nil
  299. }
  300. func (a *App) SubscribeTelemetry(ctx context.Context, id string, resume uint64, emit func(*hthv1.Snapshot) error) error {
  301. d, err := a.device(id)
  302. if err != nil {
  303. return err
  304. }
  305. peer := peerKey(ctx)
  306. sub, replay, gap, err := d.SubscribeTelemetry(resume, peer)
  307. if err != nil {
  308. if errors.Is(err, telemetry.ErrResumeOutOfRange) {
  309. return status.Error(codes.OutOfRange, err.Error())
  310. }
  311. return status.Error(codes.ResourceExhausted, err.Error())
  312. }
  313. defer sub.Cancel()
  314. if gap != nil {
  315. s := d.Snapshot()
  316. if s != nil {
  317. s.DataGap = true
  318. s.DroppedTelemetryCount = gap.DroppedCount
  319. if err := emit(s); err != nil {
  320. return err
  321. }
  322. }
  323. }
  324. for _, s := range replay {
  325. if err := emit(s); err != nil {
  326. return err
  327. }
  328. }
  329. for {
  330. select {
  331. case <-ctx.Done():
  332. return nil
  333. case s, ok := <-sub.C:
  334. if !ok {
  335. return nil
  336. }
  337. if err := emit(s); err != nil {
  338. return err
  339. }
  340. }
  341. }
  342. }
  343. func (a *App) SubscribeEvents(ctx context.Context, id string, resume uint64, emit func(*hthv1.Event) error) error {
  344. d, err := a.device(id)
  345. if err != nil {
  346. return err
  347. }
  348. peer := peerKey(ctx)
  349. sub, replay, gap, err := d.SubscribeEvents(resume, peer)
  350. if err != nil {
  351. if errors.Is(err, telemetry.ErrResumeOutOfRange) {
  352. return status.Error(codes.OutOfRange, err.Error())
  353. }
  354. return status.Error(codes.ResourceExhausted, err.Error())
  355. }
  356. defer sub.Cancel()
  357. if gap != nil && gap.EventId != 0 {
  358. return status.Error(codes.Internal, "event stream gap must not carry a global event_id")
  359. }
  360. if gap != nil && len(replay) > 0 && replay[0].GetDeliveryGap() == nil {
  361. replay[0].DeliveryGap = &hthv1.DeliveryGap{
  362. DroppedCount: gap.DroppedCount,
  363. LastContiguousEventId: gap.LastContiguousEventId,
  364. RequestedResumeAfterEventId: gap.ResumeAfterEventId,
  365. OldestAvailableEventId: 0,
  366. }
  367. }
  368. for _, e := range replay {
  369. if err := emit(e); err != nil {
  370. return err
  371. }
  372. }
  373. for {
  374. select {
  375. case <-ctx.Done():
  376. return nil
  377. case e, ok := <-sub.C:
  378. if !ok {
  379. return nil
  380. }
  381. if err := emit(e); err != nil {
  382. return err
  383. }
  384. }
  385. }
  386. }
  387. func (a *App) Faults(ctx context.Context, id string, include bool) (*hthv1.GetFaultsResponse, error) {
  388. d, err := a.device(id)
  389. if err != nil {
  390. return nil, err
  391. }
  392. return &hthv1.GetFaultsResponse{
  393. Faults: d.Faults(include),
  394. DeviceFaultQuerySupported: false,
  395. HostFaultReportingSupported: true,
  396. DeviceNativeFaultQuerySupported: false,
  397. DeviceFaultSource: "host_inferred; MOTOR_STATUS axis flags only; no device fault queue",
  398. }, nil
  399. }
  400. func (a *App) WatchHealth(ctx context.Context, emit func(*hthv1.HealthStatus) error) error {
  401. t := time.NewTicker(500 * time.Millisecond)
  402. defer t.Stop()
  403. send := func() error {
  404. srv := a.grpcServers()
  405. host := hthv1.HostHealth_HOST_HEALTH_SERVING
  406. if srv != nil && (!srv.ObserveAlive() || !srv.ControlAlive()) {
  407. host = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
  408. }
  409. msg := "process=SERVING"
  410. if a.Dev != nil {
  411. lc := a.Dev.Snapshot().GetLifecycle()
  412. msg += fmt.Sprintf(" device_lifecycle=%s", lc.String())
  413. switch a.Cfg.Backend {
  414. case config.BackendReplay:
  415. if a.Dev.ReplayComplete() {
  416. msg += " replay_completion=COMPLETE device_readiness=REPLAY_COMPLETE control_availability=READ_ONLY"
  417. } else {
  418. msg += " replay_completion=IN_PROGRESS control_availability=READ_ONLY"
  419. }
  420. case config.BackendSerial, config.BackendMock:
  421. snap := a.Dev.Snapshot()
  422. if snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
  423. snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING ||
  424. snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING {
  425. msg += " device_readiness=" + snap.GetDeviceReadiness().String() + " control_availability=SAFE_LATCHED"
  426. } else if lc == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY {
  427. msg += " device_readiness=READY control_availability=AVAILABLE"
  428. } else {
  429. msg += " device_readiness=NOT_READY control_availability=UNAVAILABLE"
  430. }
  431. }
  432. }
  433. if srv != nil {
  434. if srv.ObserveAlive() {
  435. msg += " observe_server=ALIVE"
  436. } else {
  437. msg += " observe_server=DOWN"
  438. }
  439. if srv.ControlAlive() {
  440. msg += " control_server=ALIVE"
  441. } else {
  442. msg += " control_server=DOWN"
  443. }
  444. }
  445. listed, _ := a.ListDevices(ctx)
  446. hs := &hthv1.HealthStatus{Host: host, Devices: listed.GetDevices(), Message: msg}
  447. if srv != nil {
  448. if srv.ObserveAlive() {
  449. hs.ObserveService = hthv1.HostHealth_HOST_HEALTH_SERVING
  450. } else {
  451. hs.ObserveService = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
  452. }
  453. if srv.ControlAlive() {
  454. hs.ControlService = hthv1.HostHealth_HOST_HEALTH_SERVING
  455. } else {
  456. hs.ControlService = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
  457. }
  458. }
  459. if a.Dev != nil {
  460. snap := a.Dev.Snapshot()
  461. hs.TransportState = snap.GetTransportState()
  462. hs.DeviceReadiness = snap.GetDeviceReadiness()
  463. hs.SafetyControlMode = snap.GetSafetyControlMode()
  464. }
  465. return emit(hs)
  466. }
  467. if err := send(); err != nil {
  468. return err
  469. }
  470. for {
  471. select {
  472. case <-ctx.Done():
  473. return nil
  474. case <-t.C:
  475. if err := send(); err != nil {
  476. return err
  477. }
  478. }
  479. }
  480. }
  481. func (a *App) AcquireLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.ControlLease, error) {
  482. d, err := a.device(req.DeviceId)
  483. if err != nil {
  484. return nil, err
  485. }
  486. ttl := time.Duration(0)
  487. if req.Ttl != nil {
  488. ttl = req.Ttl.AsDuration()
  489. }
  490. return d.AcquireLease(ctx, req.Holder, ttl)
  491. }
  492. func (a *App) RenewLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.ControlLease, error) {
  493. d, err := a.device(req.DeviceId)
  494. if err != nil {
  495. return nil, err
  496. }
  497. ttl := time.Duration(0)
  498. if req.Ttl != nil {
  499. ttl = req.Ttl.AsDuration()
  500. }
  501. return d.RenewLease(ctx, req.LeaseId, req.LeaseEpoch, ttl)
  502. }
  503. func (a *App) ReleaseLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) error {
  504. d, err := a.device(req.DeviceId)
  505. if err != nil {
  506. return err
  507. }
  508. return d.ReleaseLease(ctx, req.LeaseId, req.LeaseEpoch)
  509. }
  510. func (a *App) ValidateAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error) {
  511. id := ""
  512. if batch != nil {
  513. id = batch.DeviceId
  514. }
  515. d, err := a.device(id)
  516. if err != nil {
  517. return nil, err
  518. }
  519. return d.ValidateAction(ctx, batch), nil
  520. }
  521. func (a *App) ApplyAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error) {
  522. id := ""
  523. if batch != nil {
  524. id = batch.DeviceId
  525. }
  526. d, err := a.device(id)
  527. if err != nil {
  528. return nil, err
  529. }
  530. return d.ApplyAction(ctx, batch), nil
  531. }
  532. func (a *App) EnterSafeMode(ctx context.Context, req *hthv1.EnterSafeModeRequest) (*hthv1.ActionResult, error) {
  533. d, err := a.device(req.DeviceId)
  534. if err != nil {
  535. return nil, err
  536. }
  537. return d.EnterSafeMode(ctx, req.LeaseId, req.LeaseEpoch, req.Reason), nil
  538. }
  539. func (a *App) ResumeFromSafe(ctx context.Context, req *hthv1.ResumeFromSafeRequest) (*hthv1.ActionResult, error) {
  540. d, err := a.device(req.DeviceId)
  541. if err != nil {
  542. return nil, err
  543. }
  544. return d.ResumeFromSafe(ctx, req.LeaseId, req.LeaseEpoch, req.Batch), nil
  545. }
  546. func (a *App) StepReplay(ctx context.Context, id string) (*hthv1.StepReplayResponse, error) {
  547. d, err := a.device(id)
  548. if err != nil {
  549. return nil, err
  550. }
  551. res := d.StepReplay(ctx)
  552. resp := &hthv1.StepReplayResponse{
  553. Advanced: res.GetAccepted(),
  554. Message: res.GetMessage(),
  555. Snapshot: d.LastStepSnapshot(),
  556. Event: d.LastStepEvent(),
  557. }
  558. if resp.Snapshot == nil {
  559. resp.Snapshot = d.Snapshot()
  560. }
  561. if res.GetMessage() == "EOF" {
  562. resp.Advanced = false
  563. resp.Message = "EOF replay_completion=COMPLETE"
  564. }
  565. return resp, nil
  566. }
  567. func (a *App) StepReplayObserve(ctx context.Context, id string) (*hthv1.StepReplayResponse, error) {
  568. if a.Cfg == nil || !a.Cfg.Replay.AllowObserveStep {
  569. return nil, status.Error(codes.PermissionDenied, "StepReplay is a replay-admin ControlService RPC; observe clients cannot mutate global replay")
  570. }
  571. return a.StepReplay(ctx, id)
  572. }
  573. func (a *App) SetThermalTarget(ctx context.Context, req *hthv1.SetThermalTargetRequest) (*hthv1.ThermalCommandResult, error) {
  574. if a.Thermal == nil {
  575. return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
  576. }
  577. return a.Thermal.SetTarget(ctx, req)
  578. }
  579. func (a *App) StopThermal(ctx context.Context, req *hthv1.StopThermalRequest) (*hthv1.ThermalCommandResult, error) {
  580. if a.Thermal == nil {
  581. return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
  582. }
  583. return a.Thermal.Stop(ctx, req)
  584. }
  585. func (a *App) GetThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
  586. if a.Thermal == nil {
  587. return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
  588. }
  589. return a.Thermal.GetSnapshot(ctx, req)
  590. }
  591. func (a *App) CaptureThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
  592. if a.Thermal == nil {
  593. return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
  594. }
  595. return a.Thermal.CaptureSnapshot(ctx, req)
  596. }
  597. func (a *App) RunThermalStimulus(ctx context.Context, req *hthv1.RunThermalStimulusRequest) (*hthv1.ThermalCommandResult, error) {
  598. if a.Thermal == nil {
  599. return nil, status.Error(codes.Unimplemented, "6400 thermal service is not enabled for the Legacy product")
  600. }
  601. return a.Thermal.RunStimulus(ctx, req)
  602. }
  603. func newBackend(cfg *config.Config, p *profile.Profile) (backend.Backend, error) {
  604. switch cfg.Backend {
  605. case config.BackendMock:
  606. m := backend.NewMock(cfg.Mock.Seed, cfg.Mock.StartupComplete)
  607. m.FirstOrderThermal = cfg.Mock.FirstOrderThermal
  608. if cfg.Mock.SlowGetMS > 0 {
  609. m.SetSlowGet(time.Duration(cfg.Mock.SlowGetMS) * time.Millisecond)
  610. }
  611. return m, nil
  612. case config.BackendReplay:
  613. rp := backend.NewReplay(cfg.Replay.Path, cfg.Replay.Speed, cfg.Replay.Step, cfg.Replay.FromEventID)
  614. rp.SetContract(p.APIVersion, device.CapabilityHashOf(cfg, p))
  615. return rp, nil
  616. case config.BackendSerial:
  617. return newSerialBackend(cfg, p)
  618. default:
  619. return nil, fmt.Errorf("unknown backend %s", cfg.Backend)
  620. }
  621. }
  622. func DoctorText(cfg *config.Config, p *profile.Profile) string {
  623. if cfg != nil && cfg.IsThermal6400() {
  624. return fmt.Sprintf(
  625. "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",
  626. APIVersion, cfg.Product, cfg.Thermal.FirmwareProfile, protocol6400.ContractSHA256,
  627. cfg.Backend, cfg.Serial.Path, cfg.Sockets.Observe, cfg.Sockets.Control,
  628. cfg.Thermal.TransactionTimeoutMS, cfg.Thermal.Retries,
  629. )
  630. }
  631. ov := config.Safety{}
  632. if cfg != nil {
  633. ov = cfg.Safety
  634. }
  635. contract, err := safety.BuildEffectiveSafetyContract(p, ov)
  636. if err != nil {
  637. return fmt.Sprintf("effective_safety_contract=INVALID %v\n", err)
  638. }
  639. safe := contract.Frame
  640. raw, _ := safe.Encode()
  641. return fmt.Sprintf(
  642. "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",
  643. APIVersion, p.ProfileID, p.ProfileRevision, p.FileSHA256, p.SourceContractSHA256, device.CapabilityHashOf(cfg, p),
  644. cfg.Backend, cfg.Serial.Path, cfg.Sockets.Observe, cfg.Sockets.Control,
  645. cfg.Watchdog.HeartbeatPeriodMS, p.Watchdog.TimeoutSeconds,
  646. safe.Fan[0], safe.PTC[0], safe.DoorX, raw,
  647. )
  648. }
  649. func TTL(d *durationpb.Duration) time.Duration {
  650. if d == nil {
  651. return 0
  652. }
  653. return d.AsDuration()
  654. }
  655. func peerKey(ctx context.Context) string {
  656. cred, ok := grpcserver.PeerFromContext(ctx)
  657. if !ok || cred.PID == 0 {
  658. return ""
  659. }
  660. return fmt.Sprintf("uid=%d,gid=%d,pid=%d", cred.UID, cred.GID, cred.PID)
  661. }