gotelem/skylab/make_skylab.go

369 lines
9.6 KiB
Go
Raw Permalink Normal View History

2023-05-13 15:38:35 +00:00
//go:build ignore
// +build ignore
// this file is a generator for skylab code.
package main
import (
"encoding/json"
2023-05-13 15:38:35 +00:00
"fmt"
"os"
2023-05-17 21:34:14 +00:00
"path/filepath"
2023-05-13 15:38:35 +00:00
"strings"
"text/template"
2023-05-16 11:24:38 +00:00
"time"
2023-05-13 15:38:35 +00:00
"gopkg.in/yaml.v3"
)
2023-05-16 11:24:38 +00:00
// SkylabFile is a yaml file from skylab.
type SkylabFile struct {
2024-03-05 02:41:15 +00:00
Packets []PacketDef `yaml:"packets,omitempty" json:"packets,omitempty"`
Boards []BoardDef `yaml:"boards,omitempty" json:"boards,omitempty"`
2023-05-16 11:24:38 +00:00
}
type BoardDef struct {
2024-03-05 02:41:15 +00:00
Name string `yaml:"name,omitempty" json:"name,omitempty"`
Transmit []string `yaml:"transmit,omitempty" json:"transmit,omitempty"`
Receive []string `yaml:"receive,omitempty" json:"receive,omitempty"`
2023-05-16 11:24:38 +00:00
}
2023-05-13 15:38:35 +00:00
// data field.
type FieldDef struct {
2024-03-05 02:41:15 +00:00
Name string `yaml:"name,omitempty" json:"name,omitempty"`
Type string `yaml:"type,omitempty" json:"type,omitempty"`
Units string `yaml:"units,omitempty" json:"units,omitempty"`
Conversion float32 `yaml:"conversion,omitempty" json:"conversion,omitempty"`
2023-05-13 15:38:35 +00:00
Bits []struct {
2024-03-05 02:41:15 +00:00
Name string `yaml:"name,omitempty" json:"name,omitempty"`
} `yaml:"bits,omitempty" json:"bits,omitempty"`
2023-05-13 15:38:35 +00:00
}
// a PacketDef is a full can packet.
type PacketDef struct {
2024-03-05 02:41:15 +00:00
Name string `yaml:"name,omitempty" json:"name,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Id uint32 `yaml:"id,omitempty" json:"id,omitempty"`
Endian string `yaml:"endian,omitempty" json:"endian,omitempty"`
IsExtended bool `yaml:"is_extended,omitempty" json:"is_extended,omitempty"`
Repeat int `yaml:"repeat,omitempty" json:"repeat,omitempty"`
Offset int `yaml:"offset,omitempty" json:"offset,omitempty"`
Data []FieldDef `yaml:"data,omitempty" json:"data,omitempty"`
2023-05-13 15:38:35 +00:00
}
// we need to generate bitfield types.
2023-05-16 11:24:38 +00:00
// constants for packet IDs or a map.
2023-05-13 15:38:35 +00:00
var typeMap = map[string]string{
"uint16_t": "uint16",
"uint32_t": "uint32",
"uint64_t": "uint64",
"uint8_t": "uint8",
"float": "float32",
"int16_t": "int16",
"int32_t": "int32",
"int64_t": "int64",
"int8_t": "int8",
}
var typeSizeMap = map[string]uint{
"uint16_t": 2,
"uint32_t": 4,
"uint64_t": 8,
"uint8_t": 1,
"float": 4,
"int16_t": 2,
"int32_t": 4,
"int64_t": 8,
"int8_t": 1,
"bitfield": 1,
}
2023-05-29 00:39:03 +00:00
func MapType(ctype string) string {
return typeMap[ctype]
}
func (d *FieldDef) ToStructMember(parentName string) string {
2023-05-29 00:39:03 +00:00
2023-05-16 11:24:38 +00:00
if d.Type == "bitfield" {
bfStructName := parentName + toCamelInitCase(d.Name, true)
return toCamelInitCase(d.Name, true) + " " + bfStructName
} else {
2023-05-13 15:38:35 +00:00
return toCamelInitCase(d.Name, true) + " " + typeMap[d.Type]
}
}
func (d *FieldDef) MakeMarshal(offset int) string {
2023-05-14 21:19:57 +00:00
2023-05-16 11:24:38 +00:00
fieldName := toCamelInitCase(d.Name, true)
2023-05-14 21:19:57 +00:00
if d.Type == "uint8_t" || d.Type == "int8_t" {
2023-05-16 11:24:38 +00:00
return fmt.Sprintf("b[%d] = p.%s", offset, fieldName)
2023-05-14 21:19:57 +00:00
} else if d.Type == "bitfield" {
2023-05-29 00:39:03 +00:00
return fmt.Sprintf("b[%d] = p.%s.MarshalByte()", offset, fieldName)
2023-05-14 21:19:57 +00:00
} else if d.Type == "float" {
2023-05-16 11:24:38 +00:00
return fmt.Sprintf("float32ToBytes(b[%d:], p.%s, false)", offset, fieldName)
2023-05-14 21:19:57 +00:00
2023-05-29 00:39:03 +00:00
} else if t, ok := typeMap[d.Type]; ok {
2023-05-14 21:19:57 +00:00
// it's uint or int of some kind, use endian to write it.
2023-05-18 22:47:14 +00:00
if strings.HasPrefix(t, "i") {
// this means it's a signed integer.
// encoding/binary does not support putting signed ints, instead
// we should cast it to unsigned and then use the unsigned int functions.
return fmt.Sprintf("binary.LittleEndian.PutU%s(b[%d:], u%s(p.%s))", t, offset, t, fieldName)
2023-05-29 00:39:03 +00:00
}
2023-05-16 11:24:38 +00:00
return fmt.Sprintf("binary.LittleEndian.Put%s(b[%d:], p.%s)", toCamelInitCase(t, true), offset, fieldName)
2023-05-14 21:19:57 +00:00
}
return "panic(\"failed to do it\")\n"
}
func (d *FieldDef) MakeUnmarshal(offset int) string {
2023-05-14 21:19:57 +00:00
2023-05-16 11:24:38 +00:00
fieldName := toCamelInitCase(d.Name, true)
if d.Type == "uint8_t" || d.Type == "int8_t" {
return fmt.Sprintf("p.%s = b[%d]", fieldName, offset)
} else if d.Type == "bitfield" {
2023-05-29 00:39:03 +00:00
return fmt.Sprintf("p.%s.UnmarshalByte(b[%d])", fieldName, offset)
2023-05-16 11:24:38 +00:00
} else if d.Type == "float" {
2023-05-14 21:19:57 +00:00
2023-05-16 11:24:38 +00:00
return fmt.Sprintf("p.%s = float32FromBytes(b[%d:], false)", fieldName, offset)
2023-05-14 21:19:57 +00:00
2023-05-18 22:47:14 +00:00
} else if t, ok := typeMap[d.Type]; ok {
2023-05-16 15:48:30 +00:00
// it's uint or int of some kind, use endian to read it.
2023-05-16 11:24:38 +00:00
// FIXME: support big endian
2023-05-18 22:47:14 +00:00
if strings.HasPrefix(t, "i") {
// this means it's a signed integer.
// encoding/binary does not support putting signed ints, instead
// we should cast it to unsigned and then use the unsigned int functions.
return fmt.Sprintf("p.%s = %s(binary.LittleEndian.U%s(b[%d:]))", fieldName, t, t, offset)
2023-05-29 00:39:03 +00:00
}
2023-05-16 11:24:38 +00:00
return fmt.Sprintf("p.%s = binary.LittleEndian.%s(b[%d:])", fieldName, toCamelInitCase(t, true), offset)
}
panic("unhandled type")
2023-05-14 21:19:57 +00:00
}
func (p PacketDef) CalcSize() int {
2023-05-13 15:38:35 +00:00
// makes a function that returns the size of the code.
var size int = 0
for _, val := range p.Data {
size += int(typeSizeMap[val.Type])
}
return size
}
func (p PacketDef) MakeMarshal() string {
var buf strings.Builder
var offset int = 0
// we have a b []byte as the correct-size byte array to store in.
// and the packet itself is represented as `p`
for _, val := range p.Data {
2023-05-14 21:19:57 +00:00
buf.WriteRune('\t')
buf.WriteString(val.MakeMarshal(offset))
buf.WriteRune('\n')
// shift our offset so that our next write is good.
offset += int(typeSizeMap[val.Type])
}
2023-05-13 15:38:35 +00:00
2023-05-14 21:19:57 +00:00
return buf.String()
}
2023-05-13 15:38:35 +00:00
2023-05-14 21:19:57 +00:00
func (p PacketDef) MakeUnmarshal() string {
var buf strings.Builder
var offset int = 0
for _, val := range p.Data {
2023-05-13 15:38:35 +00:00
2023-05-14 21:19:57 +00:00
buf.WriteRune('\t')
buf.WriteString(val.MakeUnmarshal(offset))
buf.WriteRune('\n')
2023-05-13 15:38:35 +00:00
offset += int(typeSizeMap[val.Type])
}
2023-05-14 21:19:57 +00:00
return buf.String()
2023-05-13 15:38:35 +00:00
}
// stolen camelCaser code. initCase = true means CamelCase, false means camelCase
func toCamelInitCase(s string, initCase bool) string {
s = strings.TrimSpace(s)
if s == "" {
return s
}
n := strings.Builder{}
n.Grow(len(s))
capNext := initCase
for i, v := range []byte(s) {
vIsCap := v >= 'A' && v <= 'Z'
vIsLow := v >= 'a' && v <= 'z'
if capNext {
if vIsLow {
v += 'A'
v -= 'a'
}
} else if i == 0 {
if vIsCap {
v += 'a'
v -= 'A'
}
}
if vIsCap || vIsLow {
n.WriteByte(v)
capNext = false
} else if vIsNum := v >= '0' && v <= '9'; vIsNum {
n.WriteByte(v)
capNext = true
} else {
capNext = v == '_' || v == ' ' || v == '-' || v == '.'
}
}
return n.String()
}
2023-05-29 00:39:03 +00:00
// N takes a start and stop value and returns a stream of
2023-05-16 11:24:38 +00:00
// [start, end), including the starting value but excluding the end value.
func N(start, end int) (stream chan int) {
2023-05-29 00:39:03 +00:00
stream = make(chan int)
go func() {
for i := start; i < end; i++ {
stream <- i
}
close(stream)
}()
return
2023-05-16 11:24:38 +00:00
}
// Nx takes a start, a quantity, and an offset and returns a stream
// of `times` values which count from start and increment by `offset` each
// time.
2023-05-29 00:39:03 +00:00
func Nx(start, times, offset int) (elems []int) {
2023-05-16 11:24:38 +00:00
elems = make([]int, times)
for i := 0; i < times; i++ {
2023-05-29 00:39:03 +00:00
elems[i] = start + offset*i
2023-05-16 11:24:38 +00:00
}
2023-05-29 00:39:03 +00:00
return
2023-05-16 11:24:38 +00:00
}
2023-05-14 21:19:57 +00:00
2023-05-16 11:24:38 +00:00
// dumb function for type conversion between uint32 to integer
// used for converting packet id to int for other functions internally.
func uint32ToInt(i uint32) (o int) {
return int(i)
}
// strJoin is a remapping of strings.Join so that we can use
2023-05-16 15:48:30 +00:00
// it in a pipeline.
2023-05-29 00:39:03 +00:00
//
// {{.Names | strJoin ", " }}
2023-05-16 11:24:38 +00:00
func strJoin(delim string, elems []string) string {
return strings.Join(elems, delim)
}
// mapf takes a slice of items and runs printf on each using the given format.
// it is basically mapping a slice of things to a slice of strings using a format string).
func mapf(format string, els []int) []string {
resp := make([]string, len(els))
for idx := range els {
resp[idx] = fmt.Sprintf(format, els[idx])
}
return resp
}
2023-05-14 21:19:57 +00:00
func idToString(p PacketDef) string {
if p.Repeat > 0 {
resp := make([]string, p.Repeat)
for idx := 0; idx < p.Repeat; idx++ {
2024-03-05 02:41:15 +00:00
resp[idx] = fmt.Sprintf("can.CanID{ Id: 0x%X, Extended: %t }", int(p.Id)+idx*p.Offset, p.IsExtended)
}
return strings.Join(resp, ",")
} else {
2024-03-05 02:41:15 +00:00
return fmt.Sprintf("can.CanID{ Id: 0x%X, Extended: %t }", p.Id, p.IsExtended)
}
}
2023-05-13 15:38:35 +00:00
func main() {
2023-05-16 11:24:38 +00:00
// read path as the first arg, glob it for yamls, read each yaml into a skylabFile.
// then take each skylab file, put all the packets into one big array.
// then we need to make a header template.
2023-05-13 15:38:35 +00:00
v := &SkylabFile{}
2023-05-18 22:47:14 +00:00
basePath, err := filepath.Abs(os.Args[1])
if err != nil {
panic(err)
}
fmt.Printf("skylab packet definition path is %s\n", basePath)
2023-05-17 21:34:14 +00:00
2023-05-18 22:47:14 +00:00
fGlob := filepath.Join(basePath, "*.y?ml")
2023-05-17 21:34:14 +00:00
files, err := filepath.Glob(fGlob)
2023-05-13 15:38:35 +00:00
if err != nil {
2023-05-17 21:34:14 +00:00
panic(err)
}
2023-05-18 22:47:14 +00:00
fmt.Printf("found %d files\n", len(files))
2023-05-17 21:34:14 +00:00
for _, f := range files {
fd, err := os.Open(f)
if err != nil {
2023-05-18 22:47:14 +00:00
fmt.Printf("failed to open file %s:%v\n", filepath.Base(f), err)
2023-05-17 21:34:14 +00:00
}
dec := yaml.NewDecoder(fd)
newFile := &SkylabFile{}
err = dec.Decode(newFile)
if err != nil {
panic(err)
}
2023-05-18 22:47:14 +00:00
fmt.Printf("%s: adding %d packets and %d boards\n", filepath.Base(f), len(newFile.Packets), len(newFile.Boards))
2023-05-17 21:34:14 +00:00
v.Packets = append(v.Packets, newFile.Packets...)
v.Boards = append(v.Boards, newFile.Boards...)
2023-05-13 15:38:35 +00:00
}
2023-05-29 00:39:03 +00:00
// we add any functions mapping we need here.
2023-05-13 15:38:35 +00:00
fnMap := template.FuncMap{
"camelCase": toCamelInitCase,
"Time": time.Now,
"N": N,
"Nx": Nx,
"int": uint32ToInt,
"strJoin": strJoin,
"mapf": mapf,
"maptype": MapType,
"json": json.Marshal,
"idToString": idToString,
2023-05-13 15:38:35 +00:00
}
2023-05-17 21:34:14 +00:00
tmpl, err := template.New("golang.go.tmpl").Funcs(fnMap).ParseGlob("templates/*.go.tmpl")
2023-05-13 15:38:35 +00:00
if err != nil {
panic(err)
}
2023-05-16 11:24:38 +00:00
f, err := os.Create("skylab_gen.go")
2023-05-19 21:57:05 +00:00
defer f.Close()
2023-05-16 11:24:38 +00:00
if err != nil {
panic(err)
}
err = tmpl.Execute(f, v)
2023-05-13 15:38:35 +00:00
2023-05-19 21:57:05 +00:00
if err != nil {
panic(err)
}
tests := tmpl.Lookup("golang_tests.go.tmpl")
if tests == nil {
panic("tests not found")
}
testF, err := os.Create("skylab_gen_test.go")
defer f.Close()
2023-05-13 15:38:35 +00:00
if err != nil {
panic(err)
}
2023-05-19 21:57:05 +00:00
tests.Execute(testF, v)
2023-05-13 15:38:35 +00:00
}