-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathadapter.go
112 lines (99 loc) · 2.32 KB
/
adapter.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
108
109
110
111
112
package gocan
import (
"context"
"fmt"
"log"
"path/filepath"
"runtime"
"sort"
"strings"
)
func init() {
}
type Adapter interface {
Name() string
Open(context.Context) error
Close() error
Send() chan<- *CANFrame
Recv() <-chan *CANFrame
Err() <-chan error
//SetFilter([]uint32) error
}
type AdapterInfo struct {
Name string
Description string
RequiresSerialPort bool
Capabilities AdapterCapabilities
New func(*AdapterConfig) (Adapter, error)
}
type AdapterCapabilities struct {
HSCAN bool
SWCAN bool
KLine bool
}
type AdapterConfig struct {
Debug bool
Port string
PortBaudrate int
CANRate float64
CANFilter []uint32
UseExtendedID bool // only used for j2534 when setting upp frame filters
PrintVersion bool
OnMessage func(string)
MinimumFirmwareVersion string
}
var adapterMap = make(map[string]*AdapterInfo)
func NewAdapter(adapterName string, cfg *AdapterConfig) (Adapter, error) {
if cfg.OnMessage == nil {
cfg.OnMessage = func(msg string) {
_, file, no, ok := runtime.Caller(1)
if ok {
fmt.Printf("%s#%d %v\n", filepath.Base(file), no, msg)
} else {
log.Println(msg)
}
}
}
/*
if cfg.OnError == nil {
cfg.OnError = func(err error) {
_, file, no, ok := runtime.Caller(1)
if ok {
fmt.Printf("%s#%d %v\n", filepath.Base(file), no, err)
} else {
log.Println(err)
}
}
}
*/
if adapter, found := adapterMap[adapterName]; found {
return adapter.New(cfg)
}
return nil, fmt.Errorf("unknown adapter %q", adapterName)
}
func RegisterAdapter(adapter *AdapterInfo) error {
//log.Println("Registering adapter", adapter.Name)
if _, found := adapterMap[adapter.Name]; !found {
adapterMap[adapter.Name] = adapter
return nil
}
return fmt.Errorf("adapter %s already registered", adapter.Name)
}
func List() []string {
var out []string
for name := range adapterMap {
out = append(out, name)
}
sort.Slice(out, func(i, j int) bool { return strings.ToLower(out[i]) < strings.ToLower(out[j]) })
return out
}
func ListAdapters() []AdapterInfo {
var out []AdapterInfo
for _, adapter := range adapterMap {
out = append(out, *adapter)
}
return out
}
func GetAdapterMap() map[string]*AdapterInfo {
return adapterMap
}