forked from arduino/arduino-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmonitor.go
385 lines (355 loc) · 11.8 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
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
383
384
385
// This file is part of arduino-cli.
//
// Copyright 2020 ARDUINO SA (http://www.arduino.cc/)
//
// This software is released under the GNU General Public License version 3,
// which covers the main part of arduino-cli.
// The terms of this license can be found at:
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// You can be released from the requirements of the above licenses by purchasing
// a commercial license. Buying such a license is mandatory if you want to
// modify or otherwise use the software for commercial activities involving the
// Arduino software without disclosing the source code of your own applications.
// To purchase a commercial license, send an email to [email protected].
package monitor
import (
"bytes"
"cmp"
"context"
"errors"
"io"
"os"
"slices"
"sort"
"strings"
"time"
"github.com/arduino/arduino-cli/commands"
"github.com/arduino/arduino-cli/internal/cli/arguments"
"github.com/arduino/arduino-cli/internal/cli/feedback"
"github.com/arduino/arduino-cli/internal/cli/feedback/result"
"github.com/arduino/arduino-cli/internal/cli/feedback/table"
"github.com/arduino/arduino-cli/internal/cli/instance"
"github.com/arduino/arduino-cli/internal/i18n"
rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1"
"github.com/arduino/go-properties-orderedmap"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"go.bug.st/cleanup"
)
// NewCommand created a new `monitor` command
func NewCommand(srv rpc.ArduinoCoreServiceServer) *cobra.Command {
var (
portArgs arguments.Port
fqbnArg arguments.Fqbn
profileArg arguments.Profile
raw bool
describe bool
configs []string
quiet bool
timestamp bool
)
monitorCommand := &cobra.Command{
Use: "monitor",
Short: i18n.Tr("Open a communication port with a board."),
Long: i18n.Tr("Open a communication port with a board."),
Example: "" +
" " + os.Args[0] + " monitor -p /dev/ttyACM0\n" +
" " + os.Args[0] + " monitor -p /dev/ttyACM0 -b arduino:avr:uno\n" +
" " + os.Args[0] + " monitor -p /dev/ttyACM0 --config 115200\n" +
" " + os.Args[0] + " monitor -p /dev/ttyACM0 --describe",
Run: func(cmd *cobra.Command, args []string) {
sketchPath := ""
if len(args) > 0 {
sketchPath = args[0]
}
runMonitorCmd(cmd.Context(), srv, &portArgs, &fqbnArg, &profileArg, sketchPath, configs, describe, timestamp, quiet, raw)
},
}
portArgs.AddToCommand(monitorCommand, srv)
profileArg.AddToCommand(monitorCommand, srv)
monitorCommand.Flags().BoolVar(&raw, "raw", false, i18n.Tr("Set terminal in raw mode (unbuffered)."))
monitorCommand.Flags().BoolVar(&describe, "describe", false, i18n.Tr("Show all the settings of the communication port."))
monitorCommand.Flags().StringSliceVarP(&configs, "config", "c", []string{}, i18n.Tr("Configure communication port settings. The format is <ID>=<value>[,<ID>=<value>]..."))
monitorCommand.Flags().BoolVarP(&quiet, "quiet", "q", false, i18n.Tr("Run in silent mode, show only monitor input and output."))
monitorCommand.Flags().BoolVar(×tamp, "timestamp", false, i18n.Tr("Timestamp each incoming line."))
fqbnArg.AddToCommand(monitorCommand, srv)
return monitorCommand
}
func runMonitorCmd(
ctx context.Context, srv rpc.ArduinoCoreServiceServer,
portArgs *arguments.Port, fqbnArg *arguments.Fqbn, profileArg *arguments.Profile, sketchPathArg string,
configs []string, describe, timestamp, quiet, raw bool,
) {
logrus.Info("Executing `arduino-cli monitor`")
if !feedback.HasConsole() {
quiet = true
}
// Flags takes maximum precedence over sketch.yaml
// If {--port --fqbn --profile} are set we ignore the profile.
// If both {--port --profile} are set we read the fqbn in the following order: profile -> default_fqbn -> discovery
// If only --port is set we read the fqbn in the following order: default_fqbn -> discovery
// If only --fqbn is set we read the port in the following order: default_port
sketchPath := arguments.InitSketchPath(sketchPathArg)
resp, err := srv.LoadSketch(ctx, &rpc.LoadSketchRequest{SketchPath: sketchPath.String()})
if err != nil && !portArgs.IsPortFlagSet() {
feedback.Fatal(
i18n.Tr("Error getting default port from `sketch.yaml`. Check if you're in the correct sketch folder or provide the --port flag: %s", err),
feedback.ErrGeneric,
)
}
sketch := resp.GetSketch()
var inst *rpc.Instance
var profile *rpc.SketchProfile
if fqbnArg.String() == "" {
if profileArg.Get() == "" {
inst, profile = instance.CreateAndInitWithProfile(ctx, srv, sketch.GetDefaultProfile().GetName(), sketchPath)
} else {
inst, profile = instance.CreateAndInitWithProfile(ctx, srv, profileArg.Get(), sketchPath)
}
}
if inst == nil {
inst = instance.CreateAndInit(ctx, srv)
}
// Priority on how to retrieve the fqbn
// 1. from flag
// 2. from profile
// 3. from default_fqbn specified in the sketch.yaml
// 4. try to detect from the port
var fqbn string
switch {
case fqbnArg.String() != "":
fqbn = fqbnArg.String()
case profile.GetFqbn() != "":
fqbn = profile.GetFqbn()
case sketch.GetDefaultFqbn() != "":
fqbn = sketch.GetDefaultFqbn()
default:
fqbn, _, _ = portArgs.DetectFQBN(ctx, inst, srv)
}
var defaultPort, defaultProtocol string
if sketch != nil {
defaultPort, defaultProtocol = sketch.GetDefaultPort(), sketch.GetDefaultProtocol()
}
portAddress, portProtocol, err := portArgs.GetPortAddressAndProtocol(ctx, inst, srv, defaultPort, defaultProtocol)
if err != nil {
feedback.FatalError(err, feedback.ErrGeneric)
}
defaultSettings, err := srv.EnumerateMonitorPortSettings(ctx, &rpc.EnumerateMonitorPortSettingsRequest{
Instance: inst,
PortProtocol: portProtocol,
Fqbn: fqbn,
})
if err != nil {
feedback.Fatal(i18n.Tr("Error getting port settings details: %s", err), feedback.ErrGeneric)
}
if describe {
settings := make([]*result.MonitorPortSettingDescriptor, len(defaultSettings.GetSettings()))
for i, v := range defaultSettings.GetSettings() {
settings[i] = result.NewMonitorPortSettingDescriptor(v)
}
feedback.PrintResult(&detailsResult{Settings: settings})
return
}
// This utility finds the settings descriptor from key/value or only from key.
// It fails fatal if the key or value are invalid.
searchSettingDescriptor := func(k, v string) *rpc.MonitorPortSettingDescriptor {
for _, s := range defaultSettings.GetSettings() {
if k == "" {
if contains(s.GetEnumValues(), v) {
return s
}
} else {
if strings.EqualFold(s.GetSettingId(), k) {
if !contains(s.GetEnumValues(), v) {
feedback.Fatal(i18n.Tr("invalid port configuration value for %s: %s", k, v), feedback.ErrBadArgument)
}
return s
}
}
}
feedback.Fatal(i18n.Tr("invalid port configuration: %s=%s", k, v), feedback.ErrBadArgument)
return nil
}
// Build configuration by layering
layeredPortConfig := properties.NewMap()
setConfig := func(k, v string) {
settingDesc := searchSettingDescriptor(k, v)
layeredPortConfig.Set(settingDesc.GetSettingId(), v)
}
// Layer 1: apply configuration from sketch profile...
profileConfig := profile.GetPortConfig()
if profileConfig == nil {
// ...or from sketch default...
profileConfig = sketch.GetDefaultPortConfig()
}
for _, setting := range profileConfig.GetSettings() {
setConfig(setting.SettingId, setting.Value)
}
// Layer 2: apply configuration from command line...
for _, config := range configs {
if split := strings.SplitN(config, "=", 2); len(split) == 2 {
setConfig(split[0], split[1])
} else {
setConfig("", config)
}
}
ttyIn, ttyOut, err := feedback.InteractiveStreams()
if err != nil {
feedback.FatalError(err, feedback.ErrGeneric)
}
if timestamp {
ttyOut = newTimeStampWriter(ttyOut)
}
ctx, cancel := cleanup.InterruptableContext(ctx)
if raw {
if feedback.IsInteractive() {
if err := feedback.SetRawModeStdin(); err != nil {
feedback.Warning(i18n.Tr("Error setting raw mode: %s", err.Error()))
}
defer feedback.RestoreModeStdin()
}
// In RAW mode CTRL-C is not converted into an Interrupt by
// the terminal, we must intercept ASCII 3 (CTRL-C) on our own...
ctrlCDetector := &charDetectorWriter{
callback: cancel,
detectedChar: 3, // CTRL-C
}
ttyIn = io.TeeReader(ttyIn, ctrlCDetector)
}
var portConfiguration []*rpc.MonitorPortSetting
for k, v := range layeredPortConfig.AsMap() {
portConfiguration = append(portConfiguration, &rpc.MonitorPortSetting{
SettingId: k,
Value: v,
})
}
monitorServer, portProxy := commands.MonitorServerToReadWriteCloser(ctx, &rpc.MonitorPortOpenRequest{
Instance: inst,
Port: &rpc.Port{Address: portAddress, Protocol: portProtocol},
Fqbn: fqbn,
PortConfiguration: &rpc.MonitorPortConfiguration{
Settings: portConfiguration,
},
})
go func() {
if !quiet {
if layeredPortConfig.Size() == 0 {
if fqbn != "" {
feedback.Print(i18n.Tr("Using default monitor configuration for board: %s", fqbn))
} else if portProtocol == "serial" {
feedback.Print(i18n.Tr("Using generic monitor configuration.\nWARNING: Your board may require different settings to work!\n"))
}
}
feedback.Print(i18n.Tr("Monitor port settings:"))
slices.SortFunc(defaultSettings.GetSettings(), func(a, b *rpc.MonitorPortSettingDescriptor) int {
return cmp.Compare(a.GetSettingId(), b.GetSettingId())
})
for _, defaultSetting := range defaultSettings.GetSettings() {
k := defaultSetting.GetSettingId()
v, ok := layeredPortConfig.GetOk(k)
if !ok {
v = defaultSetting.GetValue()
}
feedback.Printf(" %s=%s", k, v)
}
feedback.Print("")
feedback.Print(i18n.Tr("Connecting to %s. Press CTRL-C to exit.", portAddress))
}
if err := srv.Monitor(monitorServer); err != nil {
feedback.FatalError(err, feedback.ErrGeneric)
}
portProxy.Close()
cancel()
}()
go func() {
_, err := io.Copy(ttyOut, portProxy)
if err != nil && !errors.Is(err, io.EOF) {
if !quiet {
feedback.Print(i18n.Tr("Port closed: %v", err))
}
}
cancel()
}()
go func() {
_, err := io.Copy(portProxy, ttyIn)
if err != nil && !errors.Is(err, io.EOF) {
if !quiet {
feedback.Print(i18n.Tr("Port closed: %v", err))
}
}
cancel()
}()
// Wait for port closed
<-ctx.Done()
}
type charDetectorWriter struct {
callback func()
detectedChar byte
}
func (cd *charDetectorWriter) Write(buf []byte) (int, error) {
if bytes.IndexByte(buf, cd.detectedChar) != -1 {
cd.callback()
}
return len(buf), nil
}
type detailsResult struct {
Settings []*result.MonitorPortSettingDescriptor `json:"settings"`
}
func (r *detailsResult) Data() interface{} {
return r
}
func (r *detailsResult) String() string {
if len(r.Settings) == 0 {
return ""
}
t := table.New()
t.SetHeader(i18n.Tr("ID"), i18n.Tr("Setting"), i18n.Tr("Default"), i18n.Tr("Values"))
green := color.New(color.FgGreen)
sort.Slice(r.Settings, func(i, j int) bool {
return r.Settings[i].Label < r.Settings[j].Label
})
for _, setting := range r.Settings {
values := strings.Join(setting.EnumValues, ", ")
t.AddRow(setting.SettingId, setting.Label, table.NewCell(setting.Value, green), values)
}
return t.Render()
}
func contains(s []string, searchterm string) bool {
for _, item := range s {
if strings.EqualFold(item, searchterm) {
return true
}
}
return false
}
type timeStampWriter struct {
writer io.Writer
sendTimeStampNext bool
}
func newTimeStampWriter(writer io.Writer) *timeStampWriter {
return &timeStampWriter{
writer: writer,
sendTimeStampNext: true,
}
}
func (t *timeStampWriter) Write(p []byte) (int, error) {
written := 0
for _, b := range p {
if t.sendTimeStampNext {
_, err := t.writer.Write([]byte(time.Now().Format("[2006-01-02 15:04:05] ")))
if err != nil {
return written, err
}
t.sendTimeStampNext = false
}
n, err := t.writer.Write([]byte{b})
written += n
if err != nil {
return written, err
}
t.sendTimeStampNext = b == '\n'
}
return written, nil
}