2023-05-09 05:54:20 +00:00
|
|
|
//go:build linux
|
|
|
|
|
2023-04-15 05:01:36 +00:00
|
|
|
package socketcan
|
2023-04-14 20:42:16 +00:00
|
|
|
|
|
|
|
import (
|
2023-04-16 07:46:41 +00:00
|
|
|
"bytes"
|
|
|
|
"net"
|
2023-04-14 20:42:16 +00:00
|
|
|
"testing"
|
|
|
|
|
2024-02-28 07:07:28 +00:00
|
|
|
"github.com/kschamplin/gotelem/internal/can"
|
2023-04-14 20:42:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestCanSocket(t *testing.T) {
|
|
|
|
|
2023-04-16 07:46:41 +00:00
|
|
|
if _, err := net.InterfaceByName("vcan0"); err != nil {
|
|
|
|
t.Skipf("missing vcan0, skipping socket tests: %v", err)
|
|
|
|
}
|
|
|
|
|
2023-04-14 20:42:16 +00:00
|
|
|
t.Run("test construction and destruction", func(t *testing.T) {
|
|
|
|
sock, err := NewCanSocket("vcan0")
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("could not make socket: %v", err)
|
|
|
|
}
|
|
|
|
if sock.fd == 0 {
|
|
|
|
t.Errorf("socket was not made: expected non-zero, got %d", sock.fd)
|
|
|
|
}
|
|
|
|
if err := sock.Close(); err != nil {
|
|
|
|
t.Errorf("could not close socket")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("test name", func(t *testing.T) {
|
|
|
|
sock, _ := NewCanSocket("vcan0")
|
2023-04-16 07:46:41 +00:00
|
|
|
defer sock.Close()
|
2023-04-14 20:42:16 +00:00
|
|
|
|
|
|
|
if sock.Name() != "vcan0" {
|
|
|
|
t.Errorf("incorrect interface name: got %s, expected %s", sock.Name(), "vcan0")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2023-04-16 07:46:41 +00:00
|
|
|
t.Run("test sending can 2.0 packet", func(t *testing.T) {
|
|
|
|
sock, _ := NewCanSocket("vcan0")
|
|
|
|
defer sock.Close()
|
|
|
|
|
|
|
|
// make a packet.
|
2024-02-28 07:07:28 +00:00
|
|
|
testFrame := &can.Frame{
|
|
|
|
Id: can.CanID{Id: 0x123, Extended: false},
|
|
|
|
Kind: can.CanDataFrame,
|
2023-04-16 07:46:41 +00:00
|
|
|
Data: []byte{0, 1, 2, 3, 4, 5, 6, 7},
|
|
|
|
}
|
|
|
|
err := sock.Send(testFrame)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("test receiving a can 2.0 packet", func(t *testing.T) {
|
|
|
|
sock, _ := NewCanSocket("vcan0")
|
|
|
|
rsock, _ := NewCanSocket("vcan0")
|
|
|
|
defer sock.Close()
|
|
|
|
defer rsock.Close()
|
|
|
|
|
2024-02-28 07:07:28 +00:00
|
|
|
testFrame := &can.Frame{
|
|
|
|
Id: can.CanID{Id: 0x234, Extended: false},
|
|
|
|
Kind: can.CanDataFrame,
|
2023-04-16 07:46:41 +00:00
|
|
|
Data: []byte{0, 1, 2, 3, 4, 5, 6, 7},
|
|
|
|
}
|
|
|
|
_ = sock.Send(testFrame)
|
|
|
|
|
|
|
|
rpkt, err := rsock.Recv()
|
|
|
|
if err != nil {
|
|
|
|
t.Error(err)
|
|
|
|
}
|
|
|
|
if len(rpkt.Data) != 8 {
|
|
|
|
t.Errorf("length mismatch: got %d expected 8", len(rpkt.Data))
|
|
|
|
}
|
|
|
|
if !bytes.Equal(testFrame.Data, rpkt.Data) {
|
|
|
|
t.Error("data corrupted")
|
|
|
|
}
|
|
|
|
|
|
|
|
})
|
|
|
|
|
2023-05-09 15:25:29 +00:00
|
|
|
// TODO: test filtering.
|
2023-04-14 20:42:16 +00:00
|
|
|
}
|