Skip to content

Instantly share code, notes, and snippets.

@rur0
Created January 24, 2020 22:52
Show Gist options
  • Save rur0/047501cc3b5c1a90ed453a8996130c5f to your computer and use it in GitHub Desktop.
Save rur0/047501cc3b5c1a90ed453a8996130c5f to your computer and use it in GitHub Desktop.
package main
import (
"encoding/hex"
"fmt"
"reflect"
)
/*
+---------------------------+--------+--------------+
| size_of(msg_id + payload) | msg_id | payload(opt) |
+---------------------------+--------+--------------+
| 1 byte | 1 byte | 0-18 bytes |
+---------------------------+--------+--------------+
*/
type Message struct {
Size byte
MsgID byte
Payload []byte
}
// serialise expect struct. returns message to transmit in bytes.
func serialise(msg interface{}) []byte {
val := reflect.ValueOf(msg)
var byteBuf []byte
// always skip first iteration as its going to be the size.
for i := 1; i < val.NumField(); i++ {
byteBuf = append(byteBuf, val.Field(i).Interface().(byte))
}
// we pre-pend the size of the msg_id + payload.
byteBuf = append([]byte{byte(len(byteBuf))}, byteBuf...)
return byteBuf
}
type AnkiVehicleSdkMode struct {
Size byte
MsgID byte
On byte
Flags byte
}
func main() {
msg := AnkiVehicleSdkMode{
Size: 3,
MsgID: 144,
On: 1,
Flags: 1,
}
fmt.Printf(hex.Dump(serialise(msg)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment