| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- //go:build linux
- package thermalbackend
- import (
- "context"
- "errors"
- "sync"
- "time"
- "hth/internal/protocol6400"
- "hth/internal/thermaltransport"
- )
- type Serial struct {
- mu sync.Mutex
- path string
- profile string
- timeout time.Duration
- retries int
- client *thermaltransport.Client
- }
- func NewSerial(path, profile string, timeout time.Duration, retries int) *Serial {
- return &Serial{path: path, profile: profile, timeout: timeout, retries: retries}
- }
- func (s *Serial) Kind() string { return "serial" }
- func (s *Serial) Profile() string { return s.profile }
- // Open is intentionally lazy. hthd remains available while a configured
- // device is absent; the next RPC performs a bounded reconnect attempt.
- func (s *Serial) Open(context.Context) error { return nil }
- func (s *Serial) ensureLocked() error {
- if s.client != nil {
- return nil
- }
- client, err := thermaltransport.Open(s.path, s.profile, s.timeout, s.retries)
- if err != nil {
- return err
- }
- s.client = client
- return nil
- }
- func (s *Serial) invalidateLocked() {
- if s.client != nil {
- _ = s.client.Close()
- s.client = nil
- }
- }
- func (s *Serial) Close() error {
- s.mu.Lock()
- defer s.mu.Unlock()
- if s.client == nil {
- return nil
- }
- err := s.client.Close()
- s.client = nil
- return err
- }
- func (s *Serial) SetTarget(ctx context.Context, target byte) error {
- if _, err := protocol6400.SetTargetRequest(target); err != nil {
- return err
- }
- s.mu.Lock()
- defer s.mu.Unlock()
- if err := s.ensureLocked(); err != nil {
- return err
- }
- err := s.client.SetTarget(ctx, target)
- if err != nil && !errors.Is(err, protocol6400.ErrTargetRange) {
- s.invalidateLocked()
- }
- return err
- }
- func (s *Serial) GetSnapshot(ctx context.Context) (protocol6400.Snapshot, []byte, error) {
- s.mu.Lock()
- defer s.mu.Unlock()
- if err := s.ensureLocked(); err != nil {
- return protocol6400.Snapshot{}, nil, err
- }
- value, payload, err := s.client.GetSnapshot(ctx)
- if err != nil {
- s.invalidateLocked()
- }
- return value, payload, err
- }
- func (s *Serial) RunStimulus(ctx context.Context, value protocol6400.Stimulus) error {
- if _, err := protocol6400.StimulusRequest(s.profile, value); err != nil {
- return err
- }
- s.mu.Lock()
- defer s.mu.Unlock()
- if err := s.ensureLocked(); err != nil {
- return err
- }
- err := s.client.RunStimulus(ctx, value)
- if err != nil && !errors.Is(err, protocol6400.ErrNotSupported) &&
- !errors.Is(err, protocol6400.ErrDutyRange) && !errors.Is(err, protocol6400.ErrDuration) {
- s.invalidateLocked()
- }
- return err
- }
|