forked from tarm/can
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readwritecloser.go
107 lines (83 loc) · 2.04 KB
/
readwritecloser.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
104
105
106
107
package can
import (
"fmt"
"io"
"net"
"os"
"syscall"
)
// The Reader interface extends the `io.Reader` interface by method
// to read a frame.
type Reader interface {
io.Reader
ReadFrame(*Frame) error
}
// The Writer interface extends the `io.Writer` interface by method
// to write a frame.
type Writer interface {
io.Writer
WriteFrame(Frame) error
}
// The ReadWriteCloser interface combines the Reader and Writer and
// `io.Closer` interface.
type ReadWriteCloser interface {
Reader
Writer
io.Closer
}
// Socket protocols
const (
Raw uint8 = 1 // CAN_RAW
Bcm uint8 = 2 // CAN_BCM
TP16 uint8 = 3
TP20 uint8 = 4
MCNet uint8 = 5
ISOTp uint8 = 6
)
type readWriteCloser struct {
rwc io.ReadWriteCloser
}
// NewReadWriteCloserForInterface returns a ReadWriteCloser for a network interface.
func NewReadWriteCloserForInterface(i *net.Interface) (ReadWriteCloser, error) {
proto := Raw
s, err := syscall.Socket(AF_CAN, syscall.SOCK_RAW, int(proto) /* 0? */)
if err != nil {
return nil, err
}
addr := NewSockaddr(uint16(proto) /* can.AF_CAN? */, i.Index /* 0 for all interfaces? */)
if err := syscall.Bind(s, addr); err != nil {
return nil, err
}
f := os.NewFile(uintptr(s), fmt.Sprintf("fd %d", s))
return &readWriteCloser{f}, nil
}
// NewReadWriteCloser returns a ReadWriteCloser for an `io.ReadWriteCloser`.
func NewReadWriteCloser(rwc io.ReadWriteCloser) ReadWriteCloser {
return &readWriteCloser{rwc}
}
func (rwc *readWriteCloser) ReadFrame(frame *Frame) error {
b := make([]byte, 256) // TODO(brutella) optimize size
n, err := rwc.Read(b)
if err != nil {
return err
}
err = Unmarshal(b[:n], frame)
return err
}
func (rwc *readWriteCloser) WriteFrame(frame Frame) error {
b, err := Marshal(frame)
if err != nil {
return err
}
_, err = rwc.Write(b)
return err
}
func (rwc *readWriteCloser) Read(b []byte) (n int, err error) {
return rwc.rwc.Read(b)
}
func (rwc *readWriteCloser) Write(b []byte) (n int, err error) {
return rwc.rwc.Write(b)
}
func (rwc *readWriteCloser) Close() error {
return rwc.rwc.Close()
}