-
-
Notifications
You must be signed in to change notification settings - Fork 437
/
Copy pathboard-discovery.ts
197 lines (179 loc) · 6.13 KB
/
board-discovery.ts
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
import { injectable, inject, postConstruct, named } from 'inversify';
import { ClientDuplexStream } from '@grpc/grpc-js';
import { ILogger } from '@theia/core/lib/common/logger';
import { deepClone } from '@theia/core/lib/common/objects';
import { CoreClientAware, CoreClientProvider } from './core-client-provider';
import {
BoardListWatchRequest,
BoardListWatchResponse,
} from './cli-protocol/cc/arduino/cli/commands/v1/board_pb';
import {
Board,
Port,
NotificationServiceServer,
AvailablePorts,
AttachedBoardsChangeEvent,
} from '../common/protocol';
/**
* Singleton service for tracking the available ports and board and broadcasting the
* changes to all connected frontend instances. \
* Unlike other services, this is not connection scoped.
*/
@injectable()
export class BoardDiscovery extends CoreClientAware {
@inject(ILogger)
@named('discovery')
protected discoveryLogger: ILogger;
@inject(NotificationServiceServer)
protected readonly notificationService: NotificationServiceServer;
// Used to know if the board watch process is already running to avoid
// starting it multiple times
private watching: boolean;
protected boardWatchDuplex:
| ClientDuplexStream<BoardListWatchRequest, BoardListWatchResponse>
| undefined;
/**
* Keys are the `address` of the ports. \
* The `protocol` is ignored because the board detach event does not carry the protocol information,
* just the address.
* ```json
* {
* "type": "remove",
* "address": "/dev/cu.usbmodem14101"
* }
* ```
*/
protected _state: AvailablePorts = {};
get state(): AvailablePorts {
return this._state;
}
@postConstruct()
protected async init(): Promise<void> {
await this.coreClientProvider.initialized;
const coreClient = await this.coreClient();
this.startBoardListWatch(coreClient);
}
stopBoardListWatch(coreClient: CoreClientProvider.Client): Promise<void> {
return new Promise((resolve, reject) => {
if (!this.boardWatchDuplex) {
return resolve();
}
const { instance } = coreClient;
const req = new BoardListWatchRequest();
req.setInstance(instance);
try {
this.boardWatchDuplex.write(req.setInterrupt(true), resolve);
} catch (e) {
this.discoveryLogger.error(e);
resolve();
}
});
}
startBoardListWatch(coreClient: CoreClientProvider.Client): void {
if (this.watching) {
// We want to avoid starting the board list watch process multiple
// times to meet unforseen consequences
return;
}
this.watching = true;
const { client, instance } = coreClient;
const req = new BoardListWatchRequest();
req.setInstance(instance);
this.boardWatchDuplex = client.boardListWatch();
this.boardWatchDuplex.on('end', () => {
this.watching = false;
console.info('board watch ended');
});
this.boardWatchDuplex.on('close', () => {
this.watching = false;
console.info('board watch ended');
});
this.boardWatchDuplex.on('data', (resp: BoardListWatchResponse) => {
if (resp.getEventType() === 'quit') {
this.watching = false;
console.info('board watch ended');
return;
}
const detectedPort = resp.getPort();
if (detectedPort) {
let eventType: 'add' | 'remove' | 'unknown' = 'unknown';
if (resp.getEventType() === 'add') {
eventType = 'add';
} else if (resp.getEventType() === 'remove') {
eventType = 'remove';
} else {
eventType = 'unknown';
}
if (eventType === 'unknown') {
throw new Error(`Unexpected event type: '${resp.getEventType()}'`);
}
const oldState = deepClone(this._state);
const newState = deepClone(this._state);
const address = (detectedPort as any).getPort().getAddress();
const protocol = (detectedPort as any).getPort().getProtocol();
const label = (detectedPort as any).getPort().getLabel();
const port = { address, protocol, label };
const boards: Board[] = [];
for (const item of detectedPort.getMatchingBoardsList()) {
boards.push({
fqbn: item.getFqbn(),
name: item.getName() || 'unknown',
port,
});
}
if (eventType === 'add') {
if (newState[port.address]) {
const [, knownBoards] = newState[port.address];
console.warn(
`Port '${
port.address
}' was already available. Known boards before override: ${JSON.stringify(
knownBoards
)}`
);
}
newState[port.address] = [port, boards];
} else if (eventType === 'remove') {
if (!newState[port.address]) {
console.warn(`Port '${port.address}' was not available. Skipping`);
return;
}
delete newState[port.address];
}
const oldAvailablePorts = this.getAvailablePorts(oldState);
const oldAttachedBoards = this.getAttachedBoards(oldState);
const newAvailablePorts = this.getAvailablePorts(newState);
const newAttachedBoards = this.getAttachedBoards(newState);
const event: AttachedBoardsChangeEvent = {
oldState: {
ports: oldAvailablePorts,
boards: oldAttachedBoards,
},
newState: {
ports: newAvailablePorts,
boards: newAttachedBoards,
},
};
this._state = newState;
this.notificationService.notifyAttachedBoardsChanged(event);
}
});
this.boardWatchDuplex.write(req);
}
getAttachedBoards(state: AvailablePorts = this.state): Board[] {
const attachedBoards: Board[] = [];
for (const address of Object.keys(state)) {
const [, boards] = state[address];
attachedBoards.push(...boards);
}
return attachedBoards;
}
getAvailablePorts(state: AvailablePorts = this.state): Port[] {
const availablePorts: Port[] = [];
for (const address of Object.keys(state)) {
const [port] = state[address];
availablePorts.push(port);
}
return availablePorts;
}
}