mock.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. package backend
  2. import (
  3. "context"
  4. "errors"
  5. "math"
  6. "sync"
  7. "time"
  8. "hth/internal/protocol"
  9. )
  10. // Mock is a deterministic UART-equivalent backend.
  11. // The optional first-order thermal update is NOT a physics model; it exists
  12. // only for interface and control-loop tests.
  13. type Mock struct {
  14. mu sync.Mutex
  15. Seed int64
  16. StartupComplete bool
  17. FirstOrderThermal bool
  18. Slow time.Duration
  19. SlowGet time.Duration
  20. disconnected bool
  21. closed bool
  22. shortOnce bool
  23. ambiguousOnce bool
  24. hangGetOnce bool
  25. hangingGet bool
  26. hangGen uint64
  27. ignoreInterrupt bool
  28. zeroOnce bool
  29. invalid [protocol.TemperaturePayloadLen]bool
  30. temps [protocol.TemperaturePayloadLen]float64
  31. setAll protocol.SetAll
  32. writes []protocol.SetAll
  33. ticks int
  34. tempGets int
  35. motorGets int
  36. openedAt time.Time
  37. StartupDelay time.Duration
  38. travel uint16
  39. pos [3]uint16 // x,y,z current
  40. }
  41. func NewMock(seed int64, startupComplete bool) *Mock {
  42. m := &Mock{Seed: seed, StartupComplete: startupComplete, travel: 1000, FirstOrderThermal: true}
  43. for i := range m.temps {
  44. m.temps[i] = 25
  45. }
  46. for i := range m.setAll.Fan {
  47. m.setAll.Fan[i] = 10
  48. }
  49. return m
  50. }
  51. func (m *Mock) Kind() string { return "mock" }
  52. func (m *Mock) PollMode() PollMode { return PollUART }
  53. func (m *Mock) Open(context.Context) error {
  54. m.mu.Lock()
  55. m.openedAt = time.Now()
  56. m.closed = false
  57. m.disconnected = false
  58. m.mu.Unlock()
  59. return nil
  60. }
  61. func (m *Mock) Close() error {
  62. m.mu.Lock()
  63. m.closed = true
  64. m.hangGen++
  65. m.mu.Unlock()
  66. return nil
  67. }
  68. // Interrupt unblocks a hung Get that ignores context. Close and Interrupt
  69. // must not wait for an in-flight protocol mutex.
  70. func (m *Mock) Interrupt() {
  71. m.mu.Lock()
  72. ignore := m.ignoreInterrupt
  73. m.mu.Unlock()
  74. if ignore {
  75. return
  76. }
  77. _ = m.Close()
  78. }
  79. func (m *Mock) SetIgnoreInterrupt(v bool) {
  80. m.mu.Lock()
  81. m.ignoreInterrupt = v
  82. m.mu.Unlock()
  83. }
  84. func (m *Mock) ForceZeroByteWrite() {
  85. m.mu.Lock()
  86. m.zeroOnce = true
  87. m.mu.Unlock()
  88. }
  89. func (m *Mock) TempGetCount() int {
  90. m.mu.Lock()
  91. defer m.mu.Unlock()
  92. return m.tempGets
  93. }
  94. func (m *Mock) MotorGetCount() int {
  95. m.mu.Lock()
  96. defer m.mu.Unlock()
  97. return m.motorGets
  98. }
  99. func (m *Mock) SetDisconnected(v bool) {
  100. m.mu.Lock()
  101. m.disconnected = v
  102. m.mu.Unlock()
  103. }
  104. func (m *Mock) ForceShortWrite() {
  105. m.mu.Lock()
  106. m.shortOnce = true
  107. m.mu.Unlock()
  108. }
  109. func (m *Mock) ForceAmbiguousWrite() {
  110. m.mu.Lock()
  111. m.ambiguousOnce = true
  112. m.mu.Unlock()
  113. }
  114. func (m *Mock) SetInvalidChannel(i int, inv bool) {
  115. m.mu.Lock()
  116. if i >= 0 && i < len(m.invalid) {
  117. m.invalid[i] = inv
  118. }
  119. m.mu.Unlock()
  120. }
  121. func (m *Mock) SetSlow(d time.Duration) {
  122. m.mu.Lock()
  123. m.Slow = d
  124. m.mu.Unlock()
  125. }
  126. func (m *Mock) SetSlowGet(d time.Duration) {
  127. m.mu.Lock()
  128. m.SlowGet = d
  129. m.mu.Unlock()
  130. }
  131. func (m *Mock) SetStartupComplete(v bool) {
  132. m.mu.Lock()
  133. m.StartupComplete = v
  134. m.mu.Unlock()
  135. }
  136. // SetHangGetOnce makes the next GetTemperature ignore context until Close/Interrupt.
  137. func (m *Mock) SetHangGetOnce() {
  138. m.mu.Lock()
  139. m.hangGetOnce = true
  140. m.mu.Unlock()
  141. }
  142. func (m *Mock) Writes() []protocol.SetAll {
  143. m.mu.Lock()
  144. defer m.mu.Unlock()
  145. out := make([]protocol.SetAll, len(m.writes))
  146. copy(out, m.writes)
  147. return out
  148. }
  149. func (m *Mock) LastSetAll() protocol.SetAll {
  150. m.mu.Lock()
  151. defer m.mu.Unlock()
  152. return m.setAll
  153. }
  154. func (m *Mock) WriteCount() int {
  155. m.mu.Lock()
  156. defer m.mu.Unlock()
  157. return len(m.writes)
  158. }
  159. func (m *Mock) WriteSetAll(ctx context.Context, s protocol.SetAll) (WriteResult, error) {
  160. m.mu.Lock()
  161. slow := m.Slow
  162. m.mu.Unlock()
  163. if slow > 0 {
  164. deadline := time.NewTimer(slow)
  165. defer deadline.Stop()
  166. ticker := time.NewTicker(5 * time.Millisecond)
  167. defer ticker.Stop()
  168. for {
  169. m.mu.Lock()
  170. closed := m.closed
  171. m.mu.Unlock()
  172. if closed {
  173. return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected
  174. }
  175. select {
  176. case <-ctx.Done():
  177. return WriteResult{Outcome: WriteNotStarted}, ctx.Err()
  178. case <-deadline.C:
  179. goto afterSlow
  180. case <-ticker.C:
  181. }
  182. }
  183. }
  184. afterSlow:
  185. if err := ctx.Err(); err != nil {
  186. return WriteResult{Outcome: WriteNotStarted}, err
  187. }
  188. m.mu.Lock()
  189. defer m.mu.Unlock()
  190. if m.disconnected || m.closed {
  191. return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected
  192. }
  193. if m.zeroOnce {
  194. m.zeroOnce = false
  195. return WriteResult{Outcome: WriteNotStarted, N: 0}, ErrWriteNotStarted
  196. }
  197. if m.shortOnce {
  198. m.shortOnce = false
  199. return WriteResult{Outcome: WriteShort, N: 3}, nil
  200. }
  201. if m.ambiguousOnce {
  202. m.ambiguousOnce = false
  203. n := protocol.MinFrameLen + protocol.SetAllPayloadLen
  204. return WriteResult{Outcome: WriteAmbiguous, N: n}, errors.New("injected full write error")
  205. }
  206. m.setAll = s
  207. m.writes = append(m.writes, s)
  208. m.pos[0] = uint16(float64(m.travel) * float64(s.DoorX) / 100)
  209. m.pos[1] = uint16(float64(m.travel) * float64(s.DoorY) / 100)
  210. m.pos[2] = uint16(float64(m.travel) * float64(s.DoorZ) / 100)
  211. return WriteResult{Outcome: WriteFull, N: protocol.MinFrameLen + protocol.SetAllPayloadLen}, nil
  212. }
  213. func (m *Mock) GetTemperature(ctx context.Context) (*TempReport, error) {
  214. sent := time.Now()
  215. m.mu.Lock()
  216. if m.hangGetOnce {
  217. m.hangGetOnce = false
  218. m.hangingGet = true
  219. }
  220. hang := m.hangingGet
  221. slow := m.SlowGet
  222. if slow == 0 {
  223. slow = m.Slow
  224. }
  225. m.mu.Unlock()
  226. if hang {
  227. m.mu.Lock()
  228. gen := m.hangGen
  229. m.mu.Unlock()
  230. for {
  231. m.mu.Lock()
  232. moved := m.hangGen != gen
  233. m.mu.Unlock()
  234. if moved {
  235. m.mu.Lock()
  236. m.hangingGet = false
  237. m.mu.Unlock()
  238. return nil, ErrNotConnected
  239. }
  240. time.Sleep(5 * time.Millisecond)
  241. }
  242. }
  243. if slow > 0 {
  244. select {
  245. case <-ctx.Done():
  246. return nil, ctx.Err()
  247. case <-time.After(slow):
  248. }
  249. }
  250. m.mu.Lock()
  251. defer m.mu.Unlock()
  252. if m.disconnected || m.closed {
  253. return nil, ErrNotConnected
  254. }
  255. m.tempGets++
  256. m.ticks++
  257. if m.FirstOrderThermal {
  258. m.stepThermal(1.0)
  259. }
  260. raw := make([]byte, protocol.TemperaturePayloadLen)
  261. for i := range raw {
  262. if m.invalid[i] {
  263. raw[i] = protocol.TempInvalid
  264. } else {
  265. v := int(math.Round(m.temps[i]))
  266. if v < 0 {
  267. v = 0
  268. }
  269. if v > 150 {
  270. v = 150
  271. }
  272. raw[i] = byte(v)
  273. }
  274. }
  275. frame, err := protocol.EncodeTemperature(raw)
  276. if err != nil {
  277. return nil, err
  278. }
  279. dec, err := protocol.Decode(frame)
  280. if err != nil {
  281. return nil, err
  282. }
  283. samples, err := protocol.DecodeTemperature(dec)
  284. if err != nil {
  285. return nil, err
  286. }
  287. done := time.Now()
  288. return &TempReport{Samples: samples, Raw: frame, Window: TimeWindow{
  289. RequestSent: sent, RequestComplete: sent.Add(200 * time.Microsecond),
  290. ResponseStart: sent.Add(time.Millisecond),
  291. ResponseComplete: done, HostReceive: done,
  292. }}, nil
  293. }
  294. func (m *Mock) GetMotorStatus(ctx context.Context) (*MotorReport, error) {
  295. if err := ctx.Err(); err != nil {
  296. return nil, err
  297. }
  298. sent := time.Now()
  299. m.mu.Lock()
  300. defer m.mu.Unlock()
  301. if m.disconnected || m.closed {
  302. return nil, ErrNotConnected
  303. }
  304. m.motorGets++
  305. startup := m.StartupComplete
  306. if !startup && m.StartupDelay > 0 && !m.openedAt.IsZero() && time.Since(m.openedAt) >= m.StartupDelay {
  307. startup = true
  308. }
  309. st := protocol.MotorStatus{StartupComplete: startup, CalibratedMask: 0x07}
  310. st.X = m.axis(m.setAll.DoorX, m.pos[0])
  311. st.Y = m.axis(m.setAll.DoorY, m.pos[1])
  312. st.Z = m.axis(m.setAll.DoorZ, m.pos[2])
  313. raw, err := protocol.EncodeMotorStatus(st)
  314. if err != nil {
  315. return nil, err
  316. }
  317. f, err := protocol.Decode(raw)
  318. if err != nil {
  319. return nil, err
  320. }
  321. ms, err := protocol.DecodeMotorStatus(f)
  322. if err != nil {
  323. return nil, err
  324. }
  325. done := time.Now()
  326. return &MotorReport{Status: ms, Raw: raw, Window: TimeWindow{
  327. RequestSent: sent, RequestComplete: sent.Add(200 * time.Microsecond),
  328. ResponseStart: sent.Add(time.Millisecond), ResponseComplete: done, HostReceive: done,
  329. }}, nil
  330. }
  331. func (m *Mock) axis(req uint8, pos uint16) protocol.AxisStatus {
  332. flags := protocol.FlagCalibrated | protocol.FlagTargetValid
  333. if req == 0 {
  334. flags |= protocol.FlagOpenLimit
  335. }
  336. if req == 100 {
  337. flags |= protocol.FlagCloseLimit
  338. }
  339. return protocol.AxisStatus{
  340. State: protocol.AxisIdle,
  341. Flags: flags,
  342. RequestedPercent: req,
  343. CurrentPosition: pos,
  344. TargetPosition: pos,
  345. TravelSteps: m.travel,
  346. }
  347. }
  348. func (m *Mock) stepThermal(dt float64) {
  349. var heat, cool float64
  350. for _, v := range m.setAll.PTC {
  351. heat += float64(v)
  352. }
  353. for _, v := range m.setAll.Fan {
  354. cool += float64(v)
  355. }
  356. heat /= 400
  357. cool /= 400
  358. target := 25 + 80*heat - 30*cool
  359. alpha := 1 - math.Exp(-dt/30)
  360. for i := range m.temps {
  361. m.temps[i] += (target - m.temps[i]) * alpha
  362. }
  363. }