From 41ada2851f233d8b10e66a626d1f6950c25da400 Mon Sep 17 00:00:00 2001 From: saji Date: Tue, 16 May 2023 21:58:20 -0500 Subject: [PATCH] idx range and can/json generators --- skylab/gen_skylab.go | 11 +++++++---- skylab/skylab.go | 30 ++++++++++++++++++------------ 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/skylab/gen_skylab.go b/skylab/gen_skylab.go index e0659aa..905e13c 100644 --- a/skylab/gen_skylab.go +++ b/skylab/gen_skylab.go @@ -272,11 +272,14 @@ type {{$structName}} struct { {{- end }} } -func (p *{{$structName}}) Id() uint32 { +func (p *{{$structName}}) Id() (uint32, error) { {{- if .Repeat }} - return {{ printf "0x%X" .Id }} + p.Idx + if p.Idx >= {{.Repeat}} { + return 0, errors.New("invalid packet index") + } + return {{ printf "0x%X" .Id }} + p.Idx, nil {{- else }} - return {{ printf "0x%X" .Id }} + return {{ printf "0x%X" .Id }}, nil {{- end }} } @@ -383,8 +386,8 @@ func FromJson (raw []byte) (Packet, error) { } return nil, errors.New("aaa") - } + {{range .Packets -}} {{template "packet" .}} {{- end}} diff --git a/skylab/skylab.go b/skylab/skylab.go index c44715c..6e37e75 100644 --- a/skylab/skylab.go +++ b/skylab/skylab.go @@ -36,7 +36,7 @@ func float32FromBytes(b []byte, bigEndian bool) (f float32) { type Packet interface { MarshalPacket() ([]byte, error) UnmarshalPacket(p []byte) error - Id() uint32 + Id() (uint32, error) Size() uint } @@ -52,7 +52,7 @@ type Unmarshaler interface { // Ider is a packet that can get its ID, based on the index of the packet, if any. type Ider interface { - Id() uint32 + Id() (uint32, error) } // Sizer allows for fast allocation. @@ -60,17 +60,19 @@ type Sizer interface { Size() uint } -// CanSend takes a packet and makes a Can frame. -func CanSend(p Packet) error { +// CanSend takes a packet and makes CAN framing data. +func CanSend(p Packet) (id uint32, data []byte, err error) { - return nil + id, err = p.Id() + if err != nil { + return + } + data, err = p.MarshalPacket() + return } - - // ---- JSON encoding business ---- - type JSONPacket struct { Id uint32 Data json.RawMessage @@ -84,12 +86,16 @@ func ToJson(p Packet) (*JSONPacket, error) { return nil, err } - jp := &JSONPacket{ - Id: p.Id(), - Data: d, + id, err := p.Id() + if err != nil { + return nil, err } + + jp := &JSONPacket{Id: id, Data: d} + return jp, nil } // we need to be able to parse the JSON as well. -// this is done using the generator since we can use the switch/case thing. +// this is done using the generator since we can use the switch/case thing +// since it's the fastest