parser.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package protocol
  2. import (
  3. "bytes"
  4. "time"
  5. )
  6. // StreamParser resynchronizes on A5 5A after noise, half-frames, or bad CRC.
  7. type StreamParser struct {
  8. buf []byte
  9. maxPayload int
  10. interByte time.Duration
  11. lastByte time.Time
  12. haveTime bool
  13. }
  14. type Parsed struct {
  15. Frame Frame
  16. Raw []byte
  17. Err error
  18. }
  19. func NewStreamParser(maxPayload int, interByte time.Duration) *StreamParser {
  20. if maxPayload <= 0 {
  21. maxPayload = DefaultMaxPayload
  22. }
  23. return &StreamParser{maxPayload: maxPayload, interByte: interByte}
  24. }
  25. func (p *StreamParser) Buffered() int {
  26. return len(p.buf)
  27. }
  28. func (p *StreamParser) Reset() {
  29. p.buf = p.buf[:0]
  30. p.haveTime = false
  31. }
  32. func (p *StreamParser) Push(b []byte, now time.Time) []Parsed {
  33. var out []Parsed
  34. if p.haveTime && p.interByte > 0 && !p.lastByte.IsZero() && now.Sub(p.lastByte) > p.interByte && len(p.buf) > 0 {
  35. p.buf = p.buf[:0]
  36. }
  37. if len(b) > 0 {
  38. p.lastByte = now
  39. p.haveTime = true
  40. p.buf = append(p.buf, b...)
  41. }
  42. for {
  43. idx := bytes.Index(p.buf, []byte{Header0, Header1})
  44. if idx < 0 {
  45. if len(p.buf) > 0 && p.buf[len(p.buf)-1] == Header0 {
  46. p.buf = p.buf[len(p.buf)-1:]
  47. } else {
  48. p.buf = p.buf[:0]
  49. }
  50. return out
  51. }
  52. if idx > 0 {
  53. p.buf = p.buf[idx:]
  54. }
  55. if len(p.buf) < MinFrameLen {
  56. return out
  57. }
  58. n := int(p.buf[3])
  59. if n > p.maxPayload {
  60. out = append(out, Parsed{Err: ErrOversize})
  61. p.buf = p.buf[2:]
  62. continue
  63. }
  64. need := MinFrameLen + n
  65. if len(p.buf) < need {
  66. return out
  67. }
  68. raw := append([]byte(nil), p.buf[:need]...)
  69. frame, err := Decode(raw)
  70. out = append(out, Parsed{Frame: frame, Raw: raw, Err: err})
  71. p.buf = p.buf[need:]
  72. }
  73. }
  74. func (p *StreamParser) InterByteTimeout(now time.Time) {
  75. if p.haveTime && p.interByte > 0 && now.Sub(p.lastByte) > p.interByte {
  76. p.buf = p.buf[:0]
  77. }
  78. }