This repository has been archived by the owner on Oct 27, 2022. It is now read-only.
/
port.go
98 lines (77 loc) · 1.67 KB
/
port.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
package main
import (
"github.com/tarm/serial"
"log"
"sync"
"time"
)
// Port represents the serial inteface with the connected device
type Port struct {
port *serial.Port
readMux sync.Mutex
writeMux sync.Mutex
}
// Write in the serial port
func (port *Port) Write(data []byte) int {
var n int
var err error
port.writeMux.Lock()
defer port.writeMux.Unlock()
if port.port != nil {
n, err = port.port.Write(data)
if err != nil {
log.Printf("Could not to write on port: %v", err)
n = -1
}
} else {
log.Println("Was tried to write in a nil port")
n = -1
}
return n
}
// Read from the serial port
func (port *Port) Read(data []byte) (int, error) {
port.readMux.Lock()
defer port.readMux.Unlock()
var err error
var n int
if port.port != nil {
n, err = port.port.Read(data)
if err != nil {
log.Printf("Was not possible to read from serial port: %v", err)
}
} else {
log.Println("Was tried te read from a nil port")
}
return n, err
}
// Open a new serial port
func (port *Port) Open(portName string) error {
port.readMux.Lock()
port.writeMux.Lock()
defer port.readMux.Unlock()
defer port.writeMux.Unlock()
var err error
configuration := &serial.Config{
Name: portName,
Baud: baudRate,
ReadTimeout: time.Second,
}
port.port, err = serial.OpenPort(configuration)
if err != nil {
log.Printf("Was not possible to open the serial port: %v", err)
}
return err
}
// IsOpen return true if the port is open
func (port *Port) IsOpen() bool {
return port.port != nil
}
// Flush to clean the buffer
func (port *Port) Flush() {
port.port.Flush()
}
// Close the serial port
func (port *Port) Close() {
port.port.Close()
}