-
Notifications
You must be signed in to change notification settings - Fork 6
/
serial.go
121 lines (102 loc) · 2.37 KB
/
serial.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
package serial
import (
"bufio"
"context"
"fmt"
"github.com/dascr/dascr-machine/service/config"
"github.com/dascr/dascr-machine/service/logger"
"github.com/tarm/serial"
)
// Serial holds the serial connection information
type Serial struct {
SerialConfig *serial.Config
Connection *serial.Port
Established bool
Quit chan int
Command chan string
Message chan string
}
// New will return an instantiated Serial object
func New(cmd chan string) *Serial {
machine := config.Config.Machine
return &Serial{
SerialConfig: &serial.Config{
Name: machine.Serial,
Baud: 9600,
},
Quit: make(chan int, 1),
Message: make(chan string),
Command: cmd,
}
}
// Start will start the serial loop
func (s *Serial) Start() error {
ctx, cancel := context.WithCancel(context.Background())
go s.read(ctx)
// Infinite read until chan Quit
for {
select {
case c := <-s.Message:
s.Command <- c
case <-s.Quit:
cancel()
return nil
}
}
}
// read will infinitly read on the serial interface
func (s *Serial) read(ctx context.Context) {
var err error
s.Established = false
// Connect via serial
s.Connection, err = serial.OpenPort(s.SerialConfig)
if err != nil {
logger.Errorf("cannot connect to serial: %+v", err)
config.Config.Machine.Error = err.Error()
return
}
s.Established = true
config.Config.Machine.Error = ""
s.Write("s,9")
// Write the Piezo Threshold time to set it at Arduino side
threshold := fmt.Sprintf("p,%+v", config.Config.Machine.Piezo)
s.Write(threshold)
// Write the debounce wobble time to set it at Arduino side
wobble := fmt.Sprintf("u,%+v", config.Config.Machine.Wobble)
s.Write(wobble)
scanner := bufio.NewScanner(s.Connection)
for {
select {
case <-ctx.Done():
close(s.Message)
close(s.Quit)
s.Connection.Close()
s.Established = false
return
default:
scanner.Scan()
cmd := scanner.Text()
if cmd != "" {
s.Message <- cmd
}
}
}
}
// Reload will terminate the serial loop
func (s *Serial) Reload() {
logger.Info("Stopping serial loop")
s.Quit <- 1
machine := config.Config.Machine
s.SerialConfig.Name = machine.Serial
s.Quit = make(chan int, 1)
s.Message = make(chan string)
go s.Start()
}
// Write will write to the serial connection
func (s *Serial) Write(input string) {
b := []byte("<" + input + ">")
_, err := s.Connection.Write(b)
if err != nil {
return
}
}