This repository has been archived by the owner on May 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
cantact.go
103 lines (86 loc) · 2.19 KB
/
cantact.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright 2016 Eric Evenchick. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file
/*
Package cantact implements an interface to the CANtact device, to provide
to Controller Area Network (CAN) buses.
*/
package cantact
import (
"fmt"
"github.com/tarm/serial"
)
// Frame is a single CAN frame.
type Frame struct {
ID int
Dlc int
Data []byte
}
// Device is a reference to a hardware CANtact device connected to this
// computer.
type Device struct {
port *serial.Port
}
// NewDevice creates a new device.
func NewDevice(portName string) (Device, error) {
c := &serial.Config{Name: portName, Baud: 115200}
s, err := serial.OpenPort(c)
if err != nil {
return Device{}, err
}
return Device{port: s}, nil
}
// SetBitrate sets the bitrate of the device.
func (d *Device) SetBitrate(rate int) error {
str := fmt.Sprintf("S%d\r", rate)
_, err := d.port.Write([]byte(str))
return err
}
// Open opens the connection to the CAN bus, enabling reception and transmission
// of CAN frames.
func (d *Device) Open() error {
_, err := d.port.Write([]byte("O\r"))
d.port.Flush()
return err
}
// Close closes the connection to the CAN bus, disabling reception and
// transmission of CAN frames.
func (d *Device) Close() error {
_, err := d.port.Write([]byte("C\r"))
return err
}
// WriteFrame writes a single Frame to the CAN bus.
func (d *Device) WriteFrame(f Frame) error {
str := fmt.Sprintf("t%03X%d", f.ID, f.Dlc)
for i := 0; i < f.Dlc; i++ {
str = fmt.Sprintf("%s%02X", str, f.Data[i])
}
str = str + "\r"
_, err := d.port.Write([]byte(str))
return err
}
// ReadFrame reads a single Frame from the CAN bus, blocks until a frame is
// received.
func (d *Device) ReadFrame() (Frame, error) {
char := make([]byte, 1)
buf := []byte{}
var err error
for {
_, err = d.port.Read(char)
buf = append(buf, char[0])
if char[0] == byte('\r') {
break
}
}
if err != nil {
return Frame{}, err
}
f := Frame{}
var dataString string
fmt.Sscanf(string(buf), "t%3X%1d%s", &f.ID, &f.Dlc, &dataString)
f.Data = make([]byte, 8)
for i := 0; i < f.Dlc; i++ {
fmt.Sscanf(dataString[i*2:i*2+2], "%2X", &f.Data[i])
}
return f, nil
}