mock.go 9.1 KB

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