| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423 |
- 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
- }
- }
|