package protocol import ( "bytes" "time" ) // StreamParser resynchronizes on A5 5A after noise, half-frames, or bad CRC. type StreamParser struct { buf []byte maxPayload int interByte time.Duration lastByte time.Time haveTime bool } type Parsed struct { Frame Frame Raw []byte Err error } func NewStreamParser(maxPayload int, interByte time.Duration) *StreamParser { if maxPayload <= 0 { maxPayload = DefaultMaxPayload } return &StreamParser{maxPayload: maxPayload, interByte: interByte} } func (p *StreamParser) Buffered() int { return len(p.buf) } func (p *StreamParser) Reset() { p.buf = p.buf[:0] p.haveTime = false } func (p *StreamParser) Push(b []byte, now time.Time) []Parsed { var out []Parsed if p.haveTime && p.interByte > 0 && !p.lastByte.IsZero() && now.Sub(p.lastByte) > p.interByte && len(p.buf) > 0 { p.buf = p.buf[:0] } if len(b) > 0 { p.lastByte = now p.haveTime = true p.buf = append(p.buf, b...) } for { idx := bytes.Index(p.buf, []byte{Header0, Header1}) if idx < 0 { if len(p.buf) > 0 && p.buf[len(p.buf)-1] == Header0 { p.buf = p.buf[len(p.buf)-1:] } else { p.buf = p.buf[:0] } return out } if idx > 0 { p.buf = p.buf[idx:] } if len(p.buf) < MinFrameLen { return out } n := int(p.buf[3]) if n > p.maxPayload { out = append(out, Parsed{Err: ErrOversize}) p.buf = p.buf[2:] continue } need := MinFrameLen + n if len(p.buf) < need { return out } raw := append([]byte(nil), p.buf[:need]...) frame, err := Decode(raw) out = append(out, Parsed{Frame: frame, Raw: raw, Err: err}) p.buf = p.buf[need:] } } func (p *StreamParser) InterByteTimeout(now time.Time) { if p.haveTime && p.interByte > 0 && now.Sub(p.lastByte) > p.interByte { p.buf = p.buf[:0] } }