aboutsummaryrefslogtreecommitdiffstats
path: root/sw/cal/can.go
blob: c1397b010638d6db2f9a2f71a411edd3434082be (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main

import (
	"context"
	"time"

	"go.einride.tech/can"

	"git.samanthony.xyz/can_gauge_interface/sw/cal/canbus"
)

const (
	stdMask = 0x7FF
	extMask = 0x1FFFFFFF

	timeout    = 1 * time.Second
	maxRetries = 8
)

func sendCtrlFrame[C can.FrameMarshaler, R can.FrameUnmarshaler](cmd C, req can.FrameMarshaler, reply R, bus canbus.Bus, isReply func(R) bool, verify func(C, R) bool) error {
	cmdFrame, err := cmd.MarshalFrame()
	if err != nil {
		return err
	}

	for retry := 0; retry < maxRetries; retry++ {
		// Write
		ctx, _ := context.WithTimeout(context.Background(), timeout)
		if err := bus.Send(ctx, cmdFrame); err != nil {
			return err
		}

		// Read back
		reqFrame, err := req.MarshalFrame()
		if err != nil {
			return err
		}
		ctx, _ = context.WithTimeout(context.Background(), timeout)
		if err := bus.Send(ctx, reqFrame); err != nil {
			return err
		}
		ctx, _ = context.WithTimeout(context.Background(), timeout)
		replyFrame, err := bus.Receive(ctx)
		if err != nil {
			return err
		}
		err = reply.UnmarshalFrame(replyFrame)
		if err == errWrongId || !isReply(reply) {
			continue
		} else if err != nil {
			return err
		}

		// Verify
		if verify(cmd, reply) {
			return nil
		}
	}
	return errVerifyFail
}