-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.go
105 lines (86 loc) · 1.6 KB
/
monitor.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
package main
// taken from: https://github.com/tinygo-org/tinygo/blob/release/monitor.go
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/mattn/go-tty"
"go.bug.st/serial"
)
func Monitor(port string, baud int) error {
if baud < 1 {
baud = 115200
}
fmt.Printf("connecting %s %d\n", port, baud)
wait := 300
var err error
var p serial.Port
for i := 0; i <= wait; i++ {
p, err = serial.Open(port, &serial.Mode{BaudRate: baud})
if err != nil {
if i < wait {
time.Sleep(10 * time.Millisecond)
continue
}
return err
}
break
}
defer p.Close()
tty, err := tty.Open()
if err != nil {
return err
}
defer tty.Close()
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGQUIT)
defer signal.Stop(sig)
go func() {
for {
sig := <-sig
switch sig {
case os.Interrupt:
p.Write([]byte{0x1b, 0x03}) // send ctrl+c to tty
case syscall.SIGQUIT:
p.Write([]byte{0x1b, 0x1c}) // send ctrl+\ to tty
}
}
}()
fmt.Printf("%s connected, use ctrl+] to exit\n", port)
errCh := make(chan error, 1)
go func() {
buf := make([]byte, 100*1024)
for {
n, err := p.Read(buf)
if err != nil {
errCh <- fmt.Errorf("read error: %w", err)
return
}
if n == 0 {
continue
}
fmt.Printf("%v", string(buf[:n]))
}
}()
go func() {
for {
r, err := tty.ReadRune()
if err != nil {
errCh <- err
return
}
if r == 0 {
continue
}
if r == 29 { // ctrl+]
fmt.Println("ctrl+] received, exiting...")
tty.Close()
os.Exit(0)
}
p.Write([]byte(string(r)))
}
}()
return <-errCh
}