-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
245 lines (201 loc) · 4.74 KB
/
main.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
package main
import (
"bufio"
"bytes"
"context"
"flag"
"fmt"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
var mu sync.Mutex
type cmd struct {
execCommand func(name string, args ...string) *exec.Cmd
execCommandContext func(ctx context.Context, name string, args ...string) *exec.Cmd
executable string
sudo string
MAC string
Quiet bool
wg sync.WaitGroup
}
func newCmd() *cmd {
return &cmd{
execCommand: exec.Command,
execCommandContext: exec.CommandContext,
executable: "bluetoothctl",
sudo: "xfsudo",
}
}
func main() {
command := newCmd()
flag.Usage = func() {
fmt.Println(`This program parse first argument by characters:
"r": restart bluetooth daemon
"+": connect to the MAC
"-": disconnect from the MAC
"c": remove device and connect cleanly`)
}
flag.StringVar(&command.MAC, "mac", "5C:FB:7C:77:23:E2", "Address of bluetooth device")
flag.BoolVar(&command.Quiet, "q", false, "Do not verbose output")
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
return
}
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(3*time.Minute))
defer cancel()
go func() {
gracefullShutdown()
cancel()
command.wg.Wait()
}()
for _, elem := range flag.Args()[0] {
switch elem {
case '+':
must(command.On())
must(command.Connect())
case '-':
must(command.Disconnect())
must(command.Off())
case 'r':
must(command.Restart())
case 's':
must(command.Scan(ctx, 3*time.Second))
time.Sleep(10*time.Second)
case 'c':
must(command.On())
must(command.Remove())
must(command.Scan(ctx, 3*time.Second))
must(command.Pair(ctx, time.Second))
must(command.Connect())
default:
log.Printf("No such command: %v", elem)
}
}
}
func gracefullShutdown() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
<-sig
fmt.Println("Caught interrupt signal, stopping all processes")
}
func must(info string, err error) (ok bool) {
msg := new(strings.Builder)
msg.WriteString(info)
msg.WriteString("...\t: ")
mu.Lock()
if err != nil {
log.SetLevel(log.ErrorLevel)
msg.WriteString(err.Error())
ok = false
} else {
log.SetLevel(log.InfoLevel)
msg.WriteString("SUCCESS")
ok = true
}
mu.Unlock()
log.Print(msg.String())
return
}
func (c *cmd) execHere(command string, args ...string) *exec.Cmd {
res := c.execCommand(command, args...)
if !c.Quiet {
res.Stdout = os.Stdout
res.Stderr = os.Stderr
}
return res
}
func (c *cmd) Scan(ctx context.Context, active time.Duration) (info string, err error) {
c.wg.Add(1)
go func() {
c.scan(ctx, active)
c.wg.Done()
}()
return "Scan avaliable devices", nil
}
func (c *cmd) scan(ctx context.Context, active time.Duration) {
for {
select {
case <-ctx.Done():
return
default:
if c.scanByInterval(active) {
if !c.Quiet {
log.Info("Device found")
}
return
}
}
}
}
func (c *cmd) scanByInterval(active time.Duration) bool {
var (
ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(active))
cmd = c.execCommandContext(ctx, c.executable, "scan", "on")
waitFor = fmt.Sprintf(`[NEW] Device %s`, c.MAC)
)
defer cancel()
// ошибка будет всегда, т.к. я убиваю нахер процесс
out, _ := cmd.Output()
if !c.Quiet {
_, err := os.Stdout.Write(out)
if err != nil {
log.Warn(err)
}
}
s := bufio.NewScanner(bytes.NewReader(out))
for s.Scan() {
if strings.HasPrefix(s.Text(), waitFor) {
return true
}
}
return false
}
func (c *cmd) Pair(ctx context.Context, sleep time.Duration) (info string, err error) {
info = "Pair with specified device"
loop:
for {
select {
case <-ctx.Done():
return
default:
err = c.execHere(c.executable, "pair", c.MAC).Run()
must(info, err)
if err == nil {
break loop
} else {
time.Sleep(sleep)
}
}
}
return
}
func (c *cmd) Connect() (info string, err error) {
return "Connect to specified device",
c.execHere(c.executable, "connect", c.MAC).Run()
}
func (c *cmd) Disconnect() (info string, err error) {
return "Disconnect specified device",
c.execHere(c.executable, "disconnect").Run()
}
func (c *cmd) On() (info string, err error) {
return "Power on bluetooth adapter",
c.execHere(c.executable, "power", "on").Run()
}
func (c *cmd) Off() (info string, err error) {
return "Power off bluetooth adapter",
c.execHere(c.executable, "power", "off").Run()
}
func (c *cmd) Restart() (info string, err error) {
return "Restart bluetooth service",
c.execHere(c.sudo, "systemctl", "restart", "bluetooth").Run()
}
func (c *cmd) Remove() (info string, err error) {
return "Remove specified device",
c.execHere(c.executable, "remove", c.MAC).Run()
}