package backend import ( "context" "errors" "math" "sync" "time" "hth/internal/protocol" ) // Mock is a deterministic UART-equivalent backend. // The optional first-order thermal update is NOT a physics model; it exists // only for interface and control-loop tests. type Mock struct { mu sync.Mutex Seed int64 StartupComplete bool FirstOrderThermal bool Slow time.Duration SlowGet time.Duration disconnected bool closed bool shortOnce bool ambiguousOnce bool hangGetOnce bool disconnectOnce bool zeroRemain int hangingGet bool hangGen uint64 ignoreInterrupt bool zeroOnce bool invalid [protocol.TemperaturePayloadLen]bool temps [protocol.TemperaturePayloadLen]float64 setAll protocol.SetAll writes []protocol.SetAll ticks int tempGets int motorGets int openedAt time.Time StartupDelay time.Duration travel uint16 pos [3]uint16 // x,y,z current } func NewMock(seed int64, startupComplete bool) *Mock { m := &Mock{Seed: seed, StartupComplete: startupComplete, travel: 1000, FirstOrderThermal: true} for i := range m.temps { m.temps[i] = 25 } for i := range m.setAll.Fan { m.setAll.Fan[i] = 10 } return m } func (m *Mock) Kind() string { return "mock" } func (m *Mock) PollMode() PollMode { return PollUART } func (m *Mock) Open(context.Context) error { m.mu.Lock() m.openedAt = time.Now() m.closed = false m.disconnected = false m.mu.Unlock() return nil } func (m *Mock) Close() error { m.mu.Lock() m.closed = true m.hangGen++ m.mu.Unlock() return nil } // Interrupt unblocks a hung Get that ignores context without closing the // port. Real serial Interrupt only kicks the reader so the next SET_ALL // (including shutdown Safe) can still be written. Close and Interrupt must // not wait for an in-flight protocol mutex. func (m *Mock) Interrupt() { m.mu.Lock() defer m.mu.Unlock() if m.ignoreInterrupt { return } m.hangGen++ } func (m *Mock) SetIgnoreInterrupt(v bool) { m.mu.Lock() m.ignoreInterrupt = v m.mu.Unlock() } func (m *Mock) ForceZeroByteWrite() { m.mu.Lock() m.zeroOnce = true m.mu.Unlock() } func (m *Mock) ForceZeroByteWrites(n int) { m.mu.Lock() m.zeroRemain = n m.mu.Unlock() } func (m *Mock) ForceDisconnectOnce() { m.mu.Lock() m.disconnectOnce = true m.mu.Unlock() } func (m *Mock) TempGetCount() int { m.mu.Lock() defer m.mu.Unlock() return m.tempGets } func (m *Mock) MotorGetCount() int { m.mu.Lock() defer m.mu.Unlock() return m.motorGets } func (m *Mock) SetDisconnected(v bool) { m.mu.Lock() m.disconnected = v m.mu.Unlock() } func (m *Mock) ForceShortWrite() { m.mu.Lock() m.shortOnce = true m.mu.Unlock() } func (m *Mock) ForceAmbiguousWrite() { m.mu.Lock() m.ambiguousOnce = true m.mu.Unlock() } func (m *Mock) SetInvalidChannel(i int, inv bool) { m.mu.Lock() if i >= 0 && i < len(m.invalid) { m.invalid[i] = inv } m.mu.Unlock() } func (m *Mock) SetSlow(d time.Duration) { m.mu.Lock() m.Slow = d m.mu.Unlock() } func (m *Mock) SetSlowGet(d time.Duration) { m.mu.Lock() m.SlowGet = d m.mu.Unlock() } func (m *Mock) SetStartupComplete(v bool) { m.mu.Lock() m.StartupComplete = v m.mu.Unlock() } // SetHangGetOnce makes the next GetTemperature ignore context until Close/Interrupt. func (m *Mock) SetHangGetOnce() { m.mu.Lock() m.hangGetOnce = true m.mu.Unlock() } func (m *Mock) HangingGet() bool { m.mu.Lock() defer m.mu.Unlock() return m.hangingGet } func (m *Mock) Writes() []protocol.SetAll { m.mu.Lock() defer m.mu.Unlock() out := make([]protocol.SetAll, len(m.writes)) copy(out, m.writes) return out } func (m *Mock) LastSetAll() protocol.SetAll { m.mu.Lock() defer m.mu.Unlock() return m.setAll } func (m *Mock) WriteCount() int { m.mu.Lock() defer m.mu.Unlock() return len(m.writes) } func (m *Mock) WriteSetAll(ctx context.Context, s protocol.SetAll) (WriteResult, error) { m.mu.Lock() slow := m.Slow m.mu.Unlock() if slow > 0 { deadline := time.NewTimer(slow) defer deadline.Stop() ticker := time.NewTicker(5 * time.Millisecond) defer ticker.Stop() for { m.mu.Lock() closed := m.closed m.mu.Unlock() if closed { return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected } select { case <-ctx.Done(): return WriteResult{Outcome: WriteNotStarted}, ctx.Err() case <-deadline.C: goto afterSlow case <-ticker.C: } } } afterSlow: if err := ctx.Err(); err != nil { return WriteResult{Outcome: WriteNotStarted}, err } m.mu.Lock() defer m.mu.Unlock() if m.disconnected || m.closed { return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected } if m.disconnectOnce { m.disconnectOnce = false m.disconnected = true return WriteResult{Outcome: WriteDisconnected, N: 0}, ErrNotConnected } if m.zeroRemain > 0 { m.zeroRemain-- return WriteResult{Outcome: WriteNotStarted, N: 0}, ErrWriteNotStarted } if m.zeroOnce { m.zeroOnce = false return WriteResult{Outcome: WriteNotStarted, N: 0}, ErrWriteNotStarted } if m.shortOnce { m.shortOnce = false return WriteResult{Outcome: WriteShort, N: 3}, nil } if m.ambiguousOnce { m.ambiguousOnce = false n := protocol.MinFrameLen + protocol.SetAllPayloadLen return WriteResult{Outcome: WriteAmbiguous, N: n}, errors.New("injected full write error") } m.setAll = s m.writes = append(m.writes, s) m.pos[0] = uint16(float64(m.travel) * float64(s.DoorX) / 100) m.pos[1] = uint16(float64(m.travel) * float64(s.DoorY) / 100) m.pos[2] = uint16(float64(m.travel) * float64(s.DoorZ) / 100) return WriteResult{Outcome: WriteFull, N: protocol.MinFrameLen + protocol.SetAllPayloadLen}, nil } func (m *Mock) GetTemperature(ctx context.Context) (*TempReport, error) { sent := time.Now() m.mu.Lock() if m.hangGetOnce { m.hangGetOnce = false m.hangingGet = true } hang := m.hangingGet slow := m.SlowGet if slow == 0 { slow = m.Slow } m.mu.Unlock() if hang { m.mu.Lock() gen := m.hangGen m.mu.Unlock() for { m.mu.Lock() moved := m.hangGen != gen m.mu.Unlock() if moved { m.mu.Lock() m.hangingGet = false m.mu.Unlock() return nil, ErrNotConnected } time.Sleep(5 * time.Millisecond) } } if slow > 0 { select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(slow): } } m.mu.Lock() defer m.mu.Unlock() if m.disconnected || m.closed { return nil, ErrNotConnected } m.tempGets++ m.ticks++ if m.FirstOrderThermal { m.stepThermal(1.0) } raw := make([]byte, protocol.TemperaturePayloadLen) for i := range raw { if m.invalid[i] { raw[i] = protocol.TempInvalid } else { v := int(math.Round(m.temps[i])) if v < 0 { v = 0 } if v > 150 { v = 150 } raw[i] = byte(v) } } frame, err := protocol.EncodeTemperature(raw) if err != nil { return nil, err } dec, err := protocol.Decode(frame) if err != nil { return nil, err } samples, err := protocol.DecodeTemperature(dec) if err != nil { return nil, err } done := time.Now() return &TempReport{Samples: samples, Raw: frame, Window: TimeWindow{ RequestSent: sent, RequestComplete: sent.Add(200 * time.Microsecond), ResponseStart: sent.Add(time.Millisecond), ResponseComplete: done, HostReceive: done, }}, nil } func (m *Mock) GetMotorStatus(ctx context.Context) (*MotorReport, error) { if err := ctx.Err(); err != nil { return nil, err } sent := time.Now() m.mu.Lock() defer m.mu.Unlock() if m.disconnected || m.closed { return nil, ErrNotConnected } m.motorGets++ startup := m.StartupComplete if !startup && m.StartupDelay > 0 && !m.openedAt.IsZero() && time.Since(m.openedAt) >= m.StartupDelay { startup = true } st := protocol.MotorStatus{StartupComplete: startup, CalibratedMask: 0x07} st.X = m.axis(m.setAll.DoorX, m.pos[0]) st.Y = m.axis(m.setAll.DoorY, m.pos[1]) st.Z = m.axis(m.setAll.DoorZ, m.pos[2]) raw, err := protocol.EncodeMotorStatus(st) if err != nil { return nil, err } f, err := protocol.Decode(raw) if err != nil { return nil, err } ms, err := protocol.DecodeMotorStatus(f) if err != nil { return nil, err } done := time.Now() return &MotorReport{Status: ms, Raw: raw, Window: TimeWindow{ RequestSent: sent, RequestComplete: sent.Add(200 * time.Microsecond), ResponseStart: sent.Add(time.Millisecond), ResponseComplete: done, HostReceive: done, }}, nil } func (m *Mock) axis(req uint8, pos uint16) protocol.AxisStatus { flags := protocol.FlagCalibrated | protocol.FlagTargetValid if req == 0 { flags |= protocol.FlagOpenLimit } if req == 100 { flags |= protocol.FlagCloseLimit } return protocol.AxisStatus{ State: protocol.AxisIdle, Flags: flags, RequestedPercent: req, CurrentPosition: pos, TargetPosition: pos, TravelSteps: m.travel, } } func (m *Mock) stepThermal(dt float64) { var heat, cool float64 for _, v := range m.setAll.PTC { heat += float64(v) } for _, v := range m.setAll.Fan { cool += float64(v) } heat /= 400 cool /= 400 target := 25 + 80*heat - 30*cool alpha := 1 - math.Exp(-dt/30) for i := range m.temps { m.temps[i] += (target - m.temps[i]) * alpha } }