-
Notifications
You must be signed in to change notification settings - Fork 41
/
realdevice.go
382 lines (299 loc) · 6.84 KB
/
realdevice.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package elmobd
import (
"bytes"
"fmt"
"io"
"net"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/tarm/serial"
)
/*==============================================================================
* External
*/
// RealResult represents the raw text output of running a raw command,
// including information used in debugging to show what input caused what
// error, how long the command took, etc.
type RealResult struct {
input string
outputs []string
error error
writeTime time.Duration
readTime time.Duration
totalTime time.Duration
}
// Failed checks if the result is successful or not
func (res *RealResult) Failed() bool {
return res.error != nil
}
// GetError returns the results current error
func (res *RealResult) GetError() error {
return res.error
}
// GetOutputs returns the outputs of the result
func (res *RealResult) GetOutputs() []string {
return res.outputs
}
// FormatOverview formats a result as an overview of what command was run and
// how long it took.
func (res *RealResult) FormatOverview() string {
lines := []string{
"=======================================",
" Ran command \"%s\" in %s",
" Spent %s writing",
" Spent %s reading",
"=======================================",
}
return fmt.Sprintf(
strings.Join(lines, "\n"),
res.input,
res.totalTime,
res.writeTime,
res.readTime,
)
}
type Conn interface {
io.ReadWriteCloser
Flush() error
}
// RealDevice represent the low level serial connection.
type RealDevice struct {
mutex sync.Mutex
state deviceState
input string
outputs []string
conn Conn
}
// NewSerialDevice creates a new low-level ELM327 device manager by connecting to
// the device at given path.
//
// After a connection has been established the device is reset, and a minimum of
// 800 ms blocking wait will occur. This makes sure the device does not have
// any custom settings that could make this library handle the device
// incorrectly.
func NewSerialDevice(addr *url.URL) (*RealDevice, error) {
config := &serial.Config{
Name: addr.Path,
Baud: 38400,
ReadTimeout: time.Second * 5,
Size: 8,
Parity: serial.ParityNone,
StopBits: serial.Stop1,
}
q := addr.Query()
baudStr := q.Get("baudrate")
timeoutStr := q.Get("timeout")
if baudStr != "" {
if baud, err := strconv.Atoi(baudStr); err == nil {
config.Baud = baud
}
}
if timeoutStr != "" {
if to, err := time.ParseDuration(timeoutStr); err == nil {
config.ReadTimeout = to
}
}
port, err := serial.OpenPort(config)
if err != nil {
return nil, err
}
dev := &RealDevice{
state: deviceReady,
mutex: sync.Mutex{},
conn: port,
}
err = dev.Reset()
if err != nil {
return nil, err
}
return dev, nil
}
type netConn struct {
net.Conn
}
func (t *netConn) Flush() error {
return nil
}
func NewNetDevice(u *url.URL) (*RealDevice, error) {
var network = u.Scheme
var address string
switch network {
case "tcp", "tcp4", "tcp6":
address = u.Host
case "unix":
address = u.Opaque
}
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
dev := &RealDevice{
state: deviceReady,
mutex: sync.Mutex{},
conn: &netConn{conn},
}
err = dev.Reset()
if err != nil {
return nil, err
}
return dev, nil
}
// Reset restarts the device, resets all the settings to factory defaults and
// makes sure it actually is a ELM327 device we are talking to.
//
// In case this doesn't work, you should turn off/on the device.
func (dev *RealDevice) Reset() error {
var err error
dev.mutex.Lock()
dev.state = deviceBusy
err = dev.conn.Flush()
if err != nil {
goto out
}
_, err = dev.write("ATZ")
if err != nil {
goto out
}
err = dev.read()
if err != nil {
goto out
}
// Device can identified itself in first or second line
if !(strings.HasPrefix(dev.outputs[0], "ELM327") || (len(dev.outputs) > 1 && strings.HasPrefix(dev.outputs[1], "ELM327"))) {
output := dev.outputs[0]
if len(dev.outputs) > 1 {
output += " " + dev.outputs[1]
}
err = fmt.Errorf(
"Device did not identify itself as ELM327: %s",
output,
)
}
out:
if err != nil {
dev.conn.Flush()
dev.state = deviceError
} else {
dev.state = deviceReady
}
dev.mutex.Unlock()
return err
}
// RunCommand runs the given AT/OBD command by sending it to the device and
// waiting for the output. There are no restrictions on what commands you can
// run with this function, so be careful.
//
// WARNING: Do not turn off echoing, because the underlying write function
// relies on echo being on so that it can compare the input command and the
// echo from the device.
//
// For more information about AT/OBD commands, see:
// https://en.wikipedia.org/wiki/Hayes_command_set
// https://en.wikipedia.org/wiki/OBD-II_PIDs
func (dev *RealDevice) RunCommand(command string) RawResult {
var err error
var startTotal time.Time
var startRead time.Time
var startWrite time.Time
result := RealResult{
input: command,
writeTime: 0,
readTime: 0,
totalTime: 0,
}
startTotal = time.Now()
dev.mutex.Lock()
dev.state = deviceBusy
startWrite = time.Now()
_, err = dev.write(command)
if err != nil {
goto out
}
result.writeTime = time.Since(startWrite)
startRead = time.Now()
err = dev.read()
result.readTime = time.Since(startRead)
if err != nil {
goto out
}
out:
if err != nil {
dev.conn.Flush()
dev.state = deviceError
} else {
dev.state = deviceReady
}
dev.mutex.Unlock()
result.error = err
result.outputs = dev.outputs
result.totalTime = time.Since(startTotal)
return &result
}
/*==============================================================================
* Internal
*/
type deviceState int
const (
deviceReady deviceState = iota
deviceBusy
deviceError
)
func (dev *RealDevice) write(input string) (int, error) {
dev.input = ""
n, err := dev.conn.Write(
[]byte(input + "\r\n"),
)
if err == nil {
dev.input = input
}
return n, err
}
func (dev *RealDevice) read() error {
var buffer bytes.Buffer
ticker := time.NewTicker(10 * time.Millisecond)
for range ticker.C {
tmp := make([]byte, 128)
n, err := dev.conn.Read(tmp)
if err != nil {
dev.outputs = []string{}
return err
}
buffer.Write(tmp[:n])
if tmp[n-1] == byte('>') {
buffer.Truncate(buffer.Len() - 1)
ticker.Stop()
break
}
}
return dev.processResult(buffer)
}
func (dev *RealDevice) processResult(result bytes.Buffer) error {
parts := strings.Split(
string(result.Bytes()),
"\r",
)
if parts[0] != dev.input {
return fmt.Errorf(
"Write echo mismatch: %q not suffix of %q",
dev.input,
parts[0],
)
}
parts = parts[1:]
var trimmedParts []string
for p := range parts {
tmp := strings.Trim(parts[p], "\r ")
if tmp == "" {
continue
}
trimmedParts = append(trimmedParts, tmp)
}
if len(trimmedParts) < 1 {
return fmt.Errorf("No payload received")
}
dev.outputs = trimmedParts
return nil
}