forked from arduino/arduino-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdiscovery.go
337 lines (308 loc) · 10.3 KB
/
discovery.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
// 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 discovery
import (
"encoding/json"
"io"
"sync"
"time"
"github.com/arduino/arduino-cli/cli/globals"
"github.com/arduino/arduino-cli/executils"
"github.com/arduino/go-properties-orderedmap"
"github.com/pkg/errors"
)
// PluggableDiscovery is a tool that detects communication ports to interact
// with the boards.
type PluggableDiscovery struct {
id string
process *executils.Process
outgoingCommandsPipe io.Writer
incomingMessagesChan <-chan *discoveryMessage
// All the following fields are guarded by statusMutex
statusMutex sync.Mutex
incomingMessagesError error
alive bool
eventsMode bool
eventChan chan<- *Event
cachedPorts map[string]*Port
}
type discoveryMessage struct {
EventType string `json:"eventType"`
Message string `json:"message"`
Error bool `json:"error"`
ProtocolVersion int `json:"protocolVersion"` // Used in HELLO command
Ports []*Port `json:"ports"` // Used in LIST command
Port *Port `json:"port"` // Used in add and remove events
}
// Port containts metadata about a port to connect to a board.
type Port struct {
Address string `json:"address"`
AddressLabel string `json:"label"`
Protocol string `json:"protocol"`
ProtocolLabel string `json:"protocolLabel"`
Properties *properties.Map `json:"properties"`
}
func (p *Port) String() string {
if p == nil {
return "none"
}
return p.Address
}
// Event is a pluggable discovery event
type Event struct {
Type string
Port *Port
}
// New create and connect to the given pluggable discovery
func New(id string, args ...string) (*PluggableDiscovery, error) {
proc, err := executils.NewProcess(args...)
if err != nil {
return nil, err
}
stdout, err := proc.StdoutPipe()
if err != nil {
return nil, err
}
stdin, err := proc.StdinPipe()
if err != nil {
return nil, err
}
if err := proc.Start(); err != nil {
return nil, err
}
messageChan := make(chan *discoveryMessage)
disc := &PluggableDiscovery{
id: id,
process: proc,
incomingMessagesChan: messageChan,
outgoingCommandsPipe: stdin,
alive: true,
}
go disc.jsonDecodeLoop(stdout, messageChan)
return disc, nil
}
// GetID returns the identifier for this discovery
func (disc *PluggableDiscovery) GetID() string {
return disc.id
}
func (disc *PluggableDiscovery) String() string {
return disc.id
}
func (disc *PluggableDiscovery) jsonDecodeLoop(in io.Reader, outChan chan<- *discoveryMessage) {
decoder := json.NewDecoder(in)
closeAndReportError := func(err error) {
disc.statusMutex.Lock()
disc.alive = false
disc.incomingMessagesError = err
disc.statusMutex.Unlock()
close(outChan)
}
for {
var msg discoveryMessage
if err := decoder.Decode(&msg); err != nil {
closeAndReportError(err)
return
}
if msg.EventType == "add" {
if msg.Port == nil {
closeAndReportError(errors.New("invalid 'add' message: missing port"))
return
}
disc.statusMutex.Lock()
disc.cachedPorts[msg.Port.Address+"|"+msg.Port.Protocol] = msg.Port
if disc.eventChan != nil {
disc.eventChan <- &Event{"add", msg.Port}
}
disc.statusMutex.Unlock()
} else if msg.EventType == "remove" {
if msg.Port == nil {
closeAndReportError(errors.New("invalid 'remove' message: missing port"))
return
}
disc.statusMutex.Lock()
delete(disc.cachedPorts, msg.Port.Address+"|"+msg.Port.Protocol)
if disc.eventChan != nil {
disc.eventChan <- &Event{"remove", msg.Port}
}
disc.statusMutex.Unlock()
} else {
outChan <- &msg
}
}
}
// IsAlive return true if the discovery process is running and so is able to receive commands
// and produce events.
func (disc *PluggableDiscovery) IsAlive() bool {
disc.statusMutex.Lock()
defer disc.statusMutex.Unlock()
return disc.alive
}
// IsEventMode return true if the discovery is in "events" mode
func (disc *PluggableDiscovery) IsEventMode() bool {
disc.statusMutex.Lock()
defer disc.statusMutex.Unlock()
return disc.eventsMode
}
func (disc *PluggableDiscovery) waitMessage(timeout time.Duration) (*discoveryMessage, error) {
select {
case msg := <-disc.incomingMessagesChan:
if msg == nil {
// channel has been closed
disc.statusMutex.Lock()
defer disc.statusMutex.Unlock()
return nil, disc.incomingMessagesError
}
return msg, nil
case <-time.After(timeout):
return nil, errors.New("timeout")
}
}
func (disc *PluggableDiscovery) sendCommand(command string) error {
data := []byte(command)
for {
n, err := disc.outgoingCommandsPipe.Write(data)
if err != nil {
return err
}
if n == len(data) {
return nil
}
data = data[n:]
}
}
// Hello sends the HELLO command to the discovery to agree on the pluggable discovery protocol. This
// must be the first command to run in the communication with the discovery.
func (disc *PluggableDiscovery) Hello() error {
if err := disc.sendCommand("HELLO 1 \"arduino-cli " + globals.VersionInfo.VersionString + "\"\n"); err != nil {
return err
}
if msg, err := disc.waitMessage(time.Second * 10); err != nil {
return err
} else if msg.EventType != "hello" {
return errors.Errorf("communication out of sync, expected 'hello', received '%s'", msg.EventType)
} else if msg.Message != "OK" || msg.Error {
return errors.Errorf("command failed: %s", msg.Message)
} else if msg.ProtocolVersion > 1 {
return errors.Errorf("protocol version not supported: requested 1, got %d", msg.ProtocolVersion)
}
return nil
}
// Start initializes and start the discovery internal subroutines. This command must be
// called before List or StartSync.
func (disc *PluggableDiscovery) Start() error {
if err := disc.sendCommand("START\n"); err != nil {
return err
}
if msg, err := disc.waitMessage(time.Second * 10); err != nil {
return err
} else if msg.EventType != "start" {
return errors.Errorf("communication out of sync, expected 'start', received '%s'", msg.EventType)
} else if msg.Message != "OK" || msg.Error {
return errors.Errorf("command failed: %s", msg.Message)
}
return nil
}
// Stop stops the discovery internal subroutines and possibly free the internally
// used resources. This command should be called if the client wants to pause the
// discovery for a while.
func (disc *PluggableDiscovery) Stop() error {
if err := disc.sendCommand("STOP\n"); err != nil {
return err
}
if msg, err := disc.waitMessage(time.Second * 10); err != nil {
return err
} else if msg.EventType != "stop" {
return errors.Errorf("communication out of sync, expected 'stop', received '%s'", msg.EventType)
} else if msg.Message != "OK" || msg.Error {
return errors.Errorf("command failed: %s", msg.Message)
}
return nil
}
// Quit terminates the discovery. No more commands can be accepted by the discovery.
func (disc *PluggableDiscovery) Quit() error {
if err := disc.sendCommand("QUIT\n"); err != nil {
return err
}
if msg, err := disc.waitMessage(time.Second * 10); err != nil {
return err
} else if msg.EventType != "quit" {
return errors.Errorf("communication out of sync, expected 'quit', received '%s'", msg.EventType)
} else if msg.Message != "OK" || msg.Error {
return errors.Errorf("command failed: %s", msg.Message)
}
return nil
}
// List executes an enumeration of the ports and returns a list of the available
// ports at the moment of the call.
func (disc *PluggableDiscovery) List() ([]*Port, error) {
if err := disc.sendCommand("LIST\n"); err != nil {
return nil, err
}
if msg, err := disc.waitMessage(time.Second * 10); err != nil {
return nil, err
} else if msg.EventType != "list" {
return nil, errors.Errorf("communication out of sync, expected 'list', received '%s'", msg.EventType)
} else if msg.Error {
return nil, errors.Errorf("command failed: %s", msg.Message)
} else {
return msg.Ports, nil
}
}
// EventChannel creates a channel used to receive events from the pluggable discovery.
// The event channel must be consumed as quickly as possible since it may block the
// discovery if it becomes full. The channel size is configurable.
func (disc *PluggableDiscovery) EventChannel(size int) <-chan *Event {
c := make(chan *Event, size)
disc.statusMutex.Lock()
defer disc.statusMutex.Unlock()
disc.eventChan = c
return c
}
// StartSync puts the discovery in "events" mode: the discovery will send "add"
// and "remove" events each time a new port is detected or removed respectively.
// After calling StartSync an initial burst of "add" events may be generated to
// report all the ports available at the moment of the start.
func (disc *PluggableDiscovery) StartSync() error {
disc.statusMutex.Lock()
defer disc.statusMutex.Unlock()
if disc.eventsMode {
return errors.New("already in events mode")
}
if err := disc.sendCommand("START_SYNC\n"); err != nil {
return err
}
if msg, err := disc.waitMessage(time.Second * 10); err != nil {
return err
} else if msg.EventType != "start_sync" {
return errors.Errorf("communication out of sync, expected 'start_sync', received '%s'", msg.EventType)
} else if msg.Message != "OK" || msg.Error {
return errors.Errorf("command failed: %s", msg.Message)
}
disc.eventsMode = true
disc.cachedPorts = map[string]*Port{}
return nil
}
// ListSync returns a list of the available ports. The list is a cache of all the
// add/remove events happened from the StartSync call and it will not consume any
// resource from the underliying discovery.
func (disc *PluggableDiscovery) ListSync() []*Port {
disc.statusMutex.Lock()
defer disc.statusMutex.Unlock()
res := []*Port{}
for _, port := range disc.cachedPorts {
res = append(res, port)
}
return res
}