| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310 |
- //go:build linux
- package devsim
- import (
- "errors"
- "io"
- "os"
- "sync"
- "time"
- "golang.org/x/sys/unix"
- "hth/internal/protocol"
- "hth/internal/serialtransport"
- )
- type Options struct {
- CRCError bool
- HalfFrame bool
- Delay time.Duration
- NoResponse bool
- InvalidTemp bool
- StartupDone bool
- DropGETTemp bool // emulate calibration: drop GET_TEMPERATURE
- WrongType bool // reply with the other GET payload type
- LengthError bool
- TempFill byte // if non-zero, fill GET_TEMPERATURE payload with this byte
- }
- type Sim struct {
- Master *os.File
- hold int
- Name string
- mu sync.Mutex
- opt Options
- closed bool
- setAlls []protocol.SetAll
- frames [][]byte
- typeHits [256]int
- parser *protocol.StreamParser
- state protocol.SetAll
- travel uint16
- lastWerr error
- lastWn int
- lastType byte
- }
- func Start(opt Options) (*Sim, error) {
- m, hold, name, err := serialtransport.OpenPTY()
- if err != nil {
- return nil, err
- }
- sim := &Sim{
- Master: m,
- hold: hold,
- Name: name,
- opt: opt,
- parser: protocol.NewStreamParser(protocol.DefaultMaxPayload, 10*time.Millisecond),
- travel: 1000,
- }
- for i := range sim.state.Fan {
- sim.state.Fan[i] = 10
- }
- go sim.loop()
- return sim, nil
- }
- func (s *Sim) Close() {
- s.mu.Lock()
- s.closed = true
- s.mu.Unlock()
- _ = s.Master.Close()
- if s.hold != 0 {
- _ = unix.Close(s.hold)
- s.hold = 0
- }
- }
- func (s *Sim) Disconnect() {
- _ = s.Master.Close()
- if s.hold != 0 {
- _ = unix.Close(s.hold)
- s.hold = 0
- }
- }
- func (s *Sim) SetAlls() []protocol.SetAll {
- s.mu.Lock()
- defer s.mu.Unlock()
- out := make([]protocol.SetAll, len(s.setAlls))
- copy(out, s.setAlls)
- return out
- }
- func (s *Sim) FrameCountSETALL() int {
- s.mu.Lock()
- defer s.mu.Unlock()
- return len(s.setAlls)
- }
- func (s *Sim) LastWrite() (int, byte, error) {
- s.mu.Lock()
- defer s.mu.Unlock()
- return s.lastWn, s.lastType, s.lastWerr
- }
- func (s *Sim) CountType(t byte) int {
- s.mu.Lock()
- defer s.mu.Unlock()
- return s.typeHits[t]
- }
- func (s *Sim) SetOptions(opt Options) {
- s.mu.Lock()
- s.opt = opt
- s.mu.Unlock()
- }
- func (s *Sim) InjectRaw(b []byte) {
- s.mu.Lock()
- m := s.Master
- closed := s.closed
- s.mu.Unlock()
- if closed || m == nil {
- return
- }
- _, _ = m.Write(b)
- }
- func (s *Sim) AssertHeartbeatDoors(want protocol.SetAll) error {
- s.mu.Lock()
- defer s.mu.Unlock()
- if len(s.setAlls) < 2 {
- return errors.New("need at least two SET_ALL frames")
- }
- first := s.setAlls[0]
- for i, g := range s.setAlls[1:] {
- if g.DoorX != first.DoorX || g.DoorY != first.DoorY || g.DoorZ != first.DoorZ {
- return errors.New("heartbeat rewrote doors")
- }
- _ = i
- }
- if want.DoorX != 0 || want.DoorY != 0 || want.DoorZ != 0 {
- if first.DoorX != want.DoorX || first.DoorY != want.DoorY || first.DoorZ != want.DoorZ {
- return errors.New("doors do not match requested percents")
- }
- }
- return nil
- }
- func (s *Sim) loop() {
- buf := make([]byte, 256)
- for {
- _ = s.Master.SetReadDeadline(time.Now().Add(50 * time.Millisecond))
- n, err := s.Master.Read(buf)
- s.mu.Lock()
- closed := s.closed
- s.mu.Unlock()
- if closed {
- return
- }
- if n > 0 {
- s.handle(buf[:n])
- }
- if err != nil {
- if errors.Is(err, os.ErrDeadlineExceeded) {
- continue
- }
- if errors.Is(err, io.EOF) || errors.Is(err, unix.EIO) {
- time.Sleep(10 * time.Millisecond)
- continue
- }
- return
- }
- }
- }
- func (s *Sim) handle(b []byte) {
- s.mu.Lock()
- opt := s.opt
- parsed := s.parser.Push(b, time.Now())
- s.mu.Unlock()
- for _, item := range parsed {
- if item.Err != nil {
- continue
- }
- s.mu.Lock()
- s.frames = append(s.frames, append([]byte(nil), item.Raw...))
- s.typeHits[item.Frame.Type]++
- s.mu.Unlock()
- switch item.Frame.Type {
- case protocol.TypeSetAll:
- sa, err := protocol.DecodeSetAll(item.Frame)
- if err != nil {
- continue
- }
- s.mu.Lock()
- s.setAlls = append(s.setAlls, sa)
- s.state = sa
- s.lastType = protocol.TypeSetAll
- s.mu.Unlock()
- case protocol.TypeGetTemperature:
- s.mu.Lock()
- s.lastType = protocol.TypeGetTemperature
- s.mu.Unlock()
- if opt.DropGETTemp {
- continue
- }
- s.respondTemp(opt)
- case protocol.TypeGetMotorStatus:
- s.mu.Lock()
- s.lastType = protocol.TypeGetMotorStatus
- s.mu.Unlock()
- s.respondMotor(opt)
- }
- }
- }
- func (s *Sim) respondTemp(opt Options) {
- if opt.NoResponse {
- return
- }
- if opt.Delay > 0 {
- time.Sleep(opt.Delay)
- }
- raw := make([]byte, protocol.TemperaturePayloadLen)
- for i := range raw {
- if opt.InvalidTemp {
- raw[i] = 0xFF
- } else if opt.TempFill != 0 {
- raw[i] = opt.TempFill
- } else {
- raw[i] = 25
- }
- }
- frame, err := protocol.EncodeTemperature(raw)
- if err != nil {
- return
- }
- s.writeResp(frame, opt)
- }
- func (s *Sim) respondMotor(opt Options) {
- if opt.NoResponse {
- return
- }
- if opt.Delay > 0 {
- time.Sleep(opt.Delay)
- }
- s.mu.Lock()
- st := s.state
- startup := opt.StartupDone
- travel := s.travel
- s.mu.Unlock()
- ms := protocol.MotorStatus{StartupComplete: startup, CalibratedMask: 0x07}
- ms.X = axis(st.DoorX, travel)
- ms.Y = axis(st.DoorY, travel)
- ms.Z = axis(st.DoorZ, travel)
- frame, err := protocol.EncodeMotorStatus(ms)
- if err != nil {
- return
- }
- s.writeResp(frame, opt)
- }
- func axis(req uint8, travel uint16) protocol.AxisStatus {
- pos := uint16(float64(travel) * float64(req) / 100)
- 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: travel}
- }
- func (s *Sim) writeResp(frame []byte, opt Options) {
- out := append([]byte(nil), frame...)
- if opt.WrongType && len(out) > 2 {
- if out[2] == protocol.TypeTemperatureData {
- if alt, err := protocol.EncodeMotorStatus(protocol.MotorStatus{StartupComplete: true}); err == nil {
- out = alt
- }
- } else if out[2] == protocol.TypeMotorStatusData {
- raw := make([]byte, protocol.TemperaturePayloadLen)
- if alt, err := protocol.EncodeTemperature(raw); err == nil {
- out = alt
- }
- }
- }
- if opt.LengthError && len(out) > 3 {
- out[3] = byte(int(out[3]) + 3)
- }
- if opt.CRCError && len(out) >= 2 {
- out[len(out)-1] ^= 0xFF
- }
- if opt.HalfFrame && len(out) > 4 {
- out = out[:len(out)/2]
- }
- n, err := s.Master.Write(out)
- s.mu.Lock()
- s.lastWn = n
- s.lastWerr = err
- if len(frame) > 2 {
- s.lastType = frame[2]
- }
- s.mu.Unlock()
- }
|