Skip to content

Commit

Permalink
add SentenceParser.OnBaseSentence
Browse files Browse the repository at this point in the history
  • Loading branch information
icholy committed Jul 18, 2024
1 parent 5969ead commit 63b7454
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
10 changes: 10 additions & 0 deletions sentence.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ type SentenceParser struct {
// \g:2-3-1234*hh\!ABVDM,1,1,1,B,.....,0*hh
// \g:3-3-1234*hh\$ABVSI,r3669961,1,013536.96326433,1386,-98,,*hh
OnTagBlock func(tagBlock TagBlock) error

// OnBaseSentence is a callback for accessing/modifying the base sentence
// before further parsing is done.
OnBaseSentence func(sentence *BaseSentence) error
}

func (p *SentenceParser) parseBaseSentence(raw string) (BaseSentence, error) {
Expand Down Expand Up @@ -264,6 +268,12 @@ func (p *SentenceParser) Parse(raw string) (Sentence, error) {
return nil, err
}

if p.OnBaseSentence != nil {
if err := p.OnBaseSentence(&s); err != nil {
return nil, err
}
}

// Custom parser allow overriding of existing parsers
if parser, ok := p.CustomParsers[s.Type]; ok {
return parser(s)
Expand Down
64 changes: 64 additions & 0 deletions sentence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package nmea
import (
"encoding/hex"
"errors"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -613,3 +614,66 @@ func TestSentenceParser_CheckCRC(t *testing.T) {
})
}
}

func TestSentenceParser_OnBaseSentence(t *testing.T) {
var testErr = errors.New("this is a test")
tests := []struct {
name string
fn func(*BaseSentence) error
raw string
sentence Sentence
err error
}{
{
name: "can modify prefix",
fn: func(s *BaseSentence) error {
if s.Type == "VDM" && strings.HasPrefix(s.Raw, "$") {
s.Raw = "!" + s.Raw[1:]
}
return nil
},
raw: "\\s:somewhere,c:1720289719*4D\\$AIVDM,1,1,,A,,0*26",
sentence: VDMVDO{
BaseSentence: BaseSentence{
Talker: "AI",
Type: "VDM",
Fields: []string{"1", "1", "", "A", "", "0"},
Checksum: "26",
Raw: "!AIVDM,1,1,,A,,0*26",
TagBlock: TagBlock{
Time: 1720289719,
RelativeTime: 0,
Destination: "",
Grouping: "",
LineCount: 0,
Source: "somewhere",
Text: "",
},
},
NumFragments: 1,
FragmentNumber: 1,
MessageID: 0,
Channel: "A",
Payload: []uint8{},
},
},
{
name: "should return error",
fn: func(_ *BaseSentence) error { return testErr },
raw: "$GNRMC,142754.0,A,4302.539570,N,07920.379823,W,0.0,,070617,0.0,E,A*21",
err: testErr,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
p := SentenceParser{OnBaseSentence: tt.fn}
s, err := p.Parse(tt.raw)
if tt.err == nil {
assert.NoError(t, err)
assert.Equal(t, tt.sentence, s)
} else {
assert.Equal(t, tt.err, err)
}
})
}
}

0 comments on commit 63b7454

Please sign in to comment.