client_linux.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. //go:build linux
  2. package thermaltransport
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "strings"
  10. "sync"
  11. "time"
  12. "golang.org/x/sys/unix"
  13. "hth/internal/protocol6400"
  14. "hth/internal/serialtransport"
  15. )
  16. type Client struct {
  17. mu sync.Mutex
  18. file *os.File
  19. path string
  20. profile string
  21. timeout time.Duration
  22. retries int
  23. parser *protocol6400.StreamParser
  24. locked bool
  25. }
  26. func Open(path, profile string, timeout time.Duration, retries int) (*Client, error) {
  27. file, err := os.OpenFile(path, os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
  28. if err != nil {
  29. return nil, err
  30. }
  31. locked := false
  32. if !strings.HasPrefix(path, "/dev/pts/") {
  33. if err := serialtransport.FlockExclusive(int(file.Fd())); err != nil {
  34. file.Close()
  35. return nil, fmt.Errorf("exclusive serial ownership: %w", err)
  36. }
  37. locked = true
  38. if err := serialtransport.ConfigureBaud8N1(int(file.Fd()), protocol6400.HostBaud); err != nil {
  39. serialtransport.Funlock(int(file.Fd()))
  40. file.Close()
  41. return nil, err
  42. }
  43. } else if err := serialtransport.ConfigurePTYRaw(int(file.Fd())); err != nil {
  44. file.Close()
  45. return nil, err
  46. }
  47. return &Client{file: file, path: path, profile: profile, timeout: timeout, retries: retries, parser: protocol6400.NewStreamParser(10 * time.Millisecond), locked: locked}, nil
  48. }
  49. func (c *Client) Close() error {
  50. c.mu.Lock()
  51. defer c.mu.Unlock()
  52. if c.file == nil {
  53. return nil
  54. }
  55. if c.locked {
  56. _ = serialtransport.Funlock(int(c.file.Fd()))
  57. }
  58. err := c.file.Close()
  59. c.file = nil
  60. return err
  61. }
  62. func (c *Client) transactSequenceLocked(ctx context.Context, request []byte, responseTypes []byte) ([]protocol6400.Frame, error) {
  63. if c.file == nil {
  64. return nil, os.ErrClosed
  65. }
  66. if len(responseTypes) == 0 {
  67. return nil, errors.New("thermal transport: empty response sequence")
  68. }
  69. deadline := time.Now().Add(c.timeout)
  70. if value, ok := ctx.Deadline(); ok && value.Before(deadline) {
  71. deadline = value
  72. }
  73. _ = c.file.SetDeadline(deadline)
  74. c.parser.Reset()
  75. written, err := c.file.Write(request)
  76. if err != nil {
  77. return nil, err
  78. }
  79. if written != len(request) {
  80. return nil, io.ErrShortWrite
  81. }
  82. buffer := make([]byte, 256)
  83. frames := make([]protocol6400.Frame, 0, len(responseTypes))
  84. for {
  85. if err := ctx.Err(); err != nil {
  86. return nil, err
  87. }
  88. n, err := c.file.Read(buffer)
  89. now := time.Now()
  90. if n > 0 {
  91. for _, item := range c.parser.Push(buffer[:n], now) {
  92. if item.Err != nil {
  93. return nil, item.Err
  94. }
  95. if len(frames) >= len(responseTypes) || item.Frame.Type != responseTypes[len(frames)] {
  96. return nil, fmt.Errorf(
  97. "unexpected response 0x%02x at stage %d", item.Frame.Type, len(frames),
  98. )
  99. }
  100. frames = append(frames, item.Frame)
  101. }
  102. if len(frames) == len(responseTypes) {
  103. return frames, nil
  104. }
  105. }
  106. if err != nil {
  107. if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
  108. return nil, context.DeadlineExceeded
  109. }
  110. if errors.Is(err, io.EOF) && strings.HasPrefix(c.path, "/dev/pts/") {
  111. continue
  112. }
  113. return nil, err
  114. }
  115. }
  116. }
  117. func (c *Client) transactSequence(ctx context.Context, request []byte, responseTypes ...byte) ([]protocol6400.Frame, error) {
  118. c.mu.Lock()
  119. defer c.mu.Unlock()
  120. var last error
  121. for attempt := 0; attempt <= c.retries; attempt++ {
  122. frames, err := c.transactSequenceLocked(ctx, request, responseTypes)
  123. if err == nil {
  124. return frames, nil
  125. }
  126. last = err
  127. if ctx.Err() != nil {
  128. break
  129. }
  130. }
  131. return nil, last
  132. }
  133. func (c *Client) transact(ctx context.Context, request []byte, responseType byte) (protocol6400.Frame, error) {
  134. frames, err := c.transactSequence(ctx, request, responseType)
  135. if err != nil {
  136. return protocol6400.Frame{}, err
  137. }
  138. return frames[0], nil
  139. }
  140. func (c *Client) SetTarget(ctx context.Context, target byte) error {
  141. request, err := protocol6400.SetTargetRequest(target)
  142. if err != nil {
  143. return err
  144. }
  145. _, err = c.transact(ctx, request, protocol6400.RspSetTargetAck)
  146. return err
  147. }
  148. func (c *Client) Stop(ctx context.Context) error { return c.SetTarget(ctx, 0) }
  149. func (c *Client) GetSnapshot(ctx context.Context) (protocol6400.Snapshot, []byte, error) {
  150. frames, err := c.transactSequence(
  151. ctx,
  152. protocol6400.GetSnapshotRequest(),
  153. protocol6400.RspGetSnapshotAck,
  154. protocol6400.RspSnapshotData,
  155. )
  156. if err != nil {
  157. return protocol6400.Snapshot{}, nil, err
  158. }
  159. frame := frames[1]
  160. value, err := protocol6400.DecodeSnapshot(frame.Payload)
  161. return value, frame.Payload, err
  162. }
  163. func (c *Client) RunStimulus(ctx context.Context, value protocol6400.Stimulus) error {
  164. request, err := protocol6400.StimulusRequest(c.profile, value)
  165. if err != nil {
  166. return err
  167. }
  168. _, err = c.transact(ctx, request, protocol6400.RspStimulusAck)
  169. return err
  170. }