idx range and can/json generators

This commit is contained in:
saji 2023-05-16 21:58:20 -05:00
parent 553469230b
commit 41ada2851f
2 changed files with 25 additions and 16 deletions

View file

@ -272,11 +272,14 @@ type {{$structName}} struct {
{{- end }} {{- end }}
} }
func (p *{{$structName}}) Id() uint32 { func (p *{{$structName}}) Id() (uint32, error) {
{{- if .Repeat }} {{- 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 }} {{- else }}
return {{ printf "0x%X" .Id }} return {{ printf "0x%X" .Id }}, nil
{{- end }} {{- end }}
} }
@ -383,8 +386,8 @@ func FromJson (raw []byte) (Packet, error) {
} }
return nil, errors.New("aaa") return nil, errors.New("aaa")
} }
{{range .Packets -}} {{range .Packets -}}
{{template "packet" .}} {{template "packet" .}}
{{- end}} {{- end}}

View file

@ -36,7 +36,7 @@ func float32FromBytes(b []byte, bigEndian bool) (f float32) {
type Packet interface { type Packet interface {
MarshalPacket() ([]byte, error) MarshalPacket() ([]byte, error)
UnmarshalPacket(p []byte) error UnmarshalPacket(p []byte) error
Id() uint32 Id() (uint32, error)
Size() uint 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. // Ider is a packet that can get its ID, based on the index of the packet, if any.
type Ider interface { type Ider interface {
Id() uint32 Id() (uint32, error)
} }
// Sizer allows for fast allocation. // Sizer allows for fast allocation.
@ -60,17 +60,19 @@ type Sizer interface {
Size() uint Size() uint
} }
// CanSend takes a packet and makes a Can frame. // CanSend takes a packet and makes CAN framing data.
func CanSend(p Packet) error { 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 ---- // ---- JSON encoding business ----
type JSONPacket struct { type JSONPacket struct {
Id uint32 Id uint32
Data json.RawMessage Data json.RawMessage
@ -84,12 +86,16 @@ func ToJson(p Packet) (*JSONPacket, error) {
return nil, err return nil, err
} }
jp := &JSONPacket{ id, err := p.Id()
Id: p.Id(), if err != nil {
Data: d, return nil, err
} }
jp := &JSONPacket{Id: id, Data: d}
return jp, nil return jp, nil
} }
// we need to be able to parse the JSON as well. // 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