This repository was archived by the owner on Oct 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy patharduino.ts
315 lines (280 loc) · 12.1 KB
/
arduino.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
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
/*--------------------------------------------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------------------------------------------------------*/
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as vscode from "vscode";
import * as constants from "../common/constants";
import * as util from "../common/util";
import * as Logger from "../logger/logger";
import * as settings from "./settings";
import { DeviceContext, IDeviceContext } from "../deviceContext";
import { BoardManager } from "./boardManager";
import { arduinoChannel } from "../common/outputChannel";
/**
* Represent an Arduino application based on the official Arduino IDE.
*/
export class ArduinoApp {
private _preferences: Map<string, string>;
private _boardManager: BoardManager;
/**
* @param {IArduinoSettings} ArduinoSetting object.
*/
constructor(private _settings: settings.IArduinoSettings) {
}
/**
* Need refresh Arduino IDE's setting when starting up.
* @param {boolean} force - Whether force initialzie the arduino
*/
public async initialize(force: boolean = false) {
if (force || !util.fileExistsSync(path.join(this._settings.packagePath, "package_index.json"))) {
try {
// Use the dummy package to initialize the Arduino IDE
await this.installBoard("dummy", "", "", true);
} catch (ex) {
}
}
}
/**
* Initialize the arduino library.
* @param {boolean} force - Whether force refresh library index file
*/
public async initializeLibrary(force: boolean = false) {
if (force || !util.fileExistsSync(path.join(this._settings.packagePath, "library_index.json"))) {
try {
// Use the dummy library to initialize the Arduino IDE
await this.installLibrary("dummy", "", true);
} catch (ex) {
}
}
}
/**
* Set the Arduino preferences value.
* @param {string} key - The preference key
* @param {string} value - The preference value
*/
public async setPref(key, value) {
try {
await util.spawn(this._settings.commandPath,
null,
["--pref", `${key}=${value}`]);
} catch (ex) {
}
}
public async upload() {
let dc = DeviceContext.getIntance();
const boardDescriptor = this.getBoardDescriptorString(dc);
if (!boardDescriptor) {
return;
}
arduinoChannel.show();
arduinoChannel.start(`Upload sketch - ${dc.sketch}`);
await vscode.commands.executeCommand("arduino.closeSerialMonitor", dc.port);
const appPath = path.join(vscode.workspace.rootPath, dc.sketch);
const args = ["--upload", "--board", boardDescriptor, "--port", dc.port, appPath];
if (this._settings.logLevel === "verbose") {
args.push("--verbose");
}
await util.spawn(this._settings.commandPath, arduinoChannel.channel, args).then((result) => {
arduinoChannel.end(`Uploaded the sketch: ${dc.sketch}${os.EOL}`);
}, (reason) => {
arduinoChannel.error(`Exit with code=${reason.code}${os.EOL}`);
});
}
public async verify() {
let dc = DeviceContext.getIntance();
const boardDescriptor = this.getBoardDescriptorString(dc);
if (!boardDescriptor) {
return;
}
arduinoChannel.start(`Verify sketch - ${dc.sketch}`);
const appPath = path.join(vscode.workspace.rootPath, dc.sketch);
const args = ["--verify", "--board", boardDescriptor, "--port", dc.port, appPath];
if (this._settings.logLevel === "verbose") {
args.push("--verbose");
}
arduinoChannel.show();
await util.spawn(this._settings.commandPath, arduinoChannel.channel, args).then((result) => {
arduinoChannel.end(`Finished verify sketch - ${dc.sketch}${os.EOL}`);
}, (reason) => {
arduinoChannel.error(`Exit with code=${reason.code}${os.EOL}`);
});
}
public addLibPath(libraryPath: string) {
let libPaths;
if (libraryPath) {
libPaths = [libraryPath];
} else {
libPaths = this.getDefaultPackageLibPaths();
}
const configFilePath = path.join(vscode.workspace.rootPath, constants.CPP_CONFIG_FILE);
let deviceContext = null;
if (!util.fileExistsSync(configFilePath)) {
util.mkdirRecursivelySync(path.dirname(configFilePath));
deviceContext = {};
} else {
deviceContext = util.tryParseJSON(fs.readFileSync(configFilePath, "utf8"));
}
if (!deviceContext) {
Logger.notifyAndThrowUserError("arduinoFileError", new Error(constants.messages.ARDUINO_FILE_ERROR));
}
deviceContext.configurations = deviceContext.configurations || [];
let configSection = null;
deviceContext.configurations.forEach((section) => {
if (section.name === util.getCppConfigPlatform()) {
configSection = section;
configSection.browse = configSection.browse || {};
configSection.browse.limitSymbolsToIncludedHeaders = false;
}
});
if (!configSection) {
configSection = {
name: util.getCppConfigPlatform(),
includePath: [],
browse: { limitSymbolsToIncludedHeaders: false },
};
deviceContext.configurations.push(configSection);
}
libPaths.forEach((childLibPath) => {
childLibPath = path.resolve(path.normalize(childLibPath));
if (configSection.includePath && configSection.includePath.length) {
for (let existingPath of configSection.includePath) {
if (childLibPath === path.resolve(path.normalize(existingPath))) {
return;
}
}
} else {
configSection.includePath = [];
}
configSection.includePath.push(childLibPath);
});
fs.writeFileSync(configFilePath, JSON.stringify(deviceContext, null, 4));
}
/**
* Install arduino board package based on package name and platform hardware architecture.
*/
public async installBoard(packageName: string, arch: string = "", version: string = "", showOutput: boolean = true) {
arduinoChannel.show();
const updatingIndex = packageName === "dummy" && !arch && !version;
if (updatingIndex) {
arduinoChannel.start(`Update package index files...`);
} else {
arduinoChannel.start(`Install package - ${packageName}...`);
}
try {
await util.spawn(this._settings.commandPath,
showOutput ? arduinoChannel.channel : null,
["--install-boards", `${packageName}${arch && ":" + arch}${version && ":" + version}`]);
if (updatingIndex) {
arduinoChannel.end("Updated package index files.");
} else {
arduinoChannel.end(`Installed board package - ${packageName}${os.EOL}`);
}
} catch (error) {
// If a platform with the same version is already installed, nothing is installed and program exits with exit code 1
if (error.code === 1) {
if (updatingIndex) {
arduinoChannel.end("Updated package index files.");
} else {
arduinoChannel.end(`Installed board package - ${packageName}${os.EOL}`);
}
} else {
arduinoChannel.error(`Exit with code=${error.code}${os.EOL}`);
}
}
}
public uninstallBoard(boardName: string, packagePath: string) {
arduinoChannel.start(`Uninstall board package - ${boardName}...`);
util.rmdirRecursivelySync(packagePath);
arduinoChannel.end(`Uninstalled board package - ${boardName}${os.EOL}`);
}
public async installLibrary(libName: string, version: string = "", showOutput: boolean = true) {
arduinoChannel.show();
const updatingIndex = (libName === "dummy" && !version);
if (updatingIndex) {
arduinoChannel.start("Update library index files...");
} else {
arduinoChannel.start(`Install library - ${libName}`);
}
try {
await util.spawn(this._settings.commandPath,
showOutput ? arduinoChannel.channel : null,
["--install-library", `${libName}${version && ":" + version}`]);
if (updatingIndex) {
arduinoChannel.end("Updated library index files.");
} else {
arduinoChannel.end(`Installed library - ${libName}${os.EOL}`);
}
} catch (error) {
// If a library with the same version is already installed, nothing is installed and program exits with exit code 1
if (error.code === 1) {
if (updatingIndex) {
arduinoChannel.end("Updated library index files.");
} else {
arduinoChannel.end(`Installed library - ${libName}${os.EOL}`);
}
} else {
arduinoChannel.error(`Exit with code=${error.code}${os.EOL}`);
}
}
}
public uninstallLibrary(libName: string, libPath: string) {
arduinoChannel.start(`Remove library - ${libName}`);
util.rmdirRecursivelySync(libPath);
arduinoChannel.end(`Removed library - ${libName}${os.EOL}`);
}
public getDefaultPackageLibPaths(): string[] {
let result = [];
let boardDescriptor = this._boardManager.currentBoard;
if (!boardDescriptor) {
return result;
}
let toolsPath = boardDescriptor.platform.rootBoardPath;
if (util.directoryExistsSync(path.join(toolsPath, "cores"))) {
let coreLibs = fs.readdirSync(path.join(toolsPath, "cores"));
if (coreLibs && coreLibs.length > 0) {
coreLibs.forEach((coreLib) => {
result.push(path.normalize(path.join(toolsPath, "cores", coreLib)));
});
}
}
return result;
}
public get preferences() {
if (!this._preferences) {
this.loadPreferences();
}
return this._preferences;
}
public get boardManager() {
return this._boardManager;
}
public set boardManager(value: BoardManager) {
this._boardManager = value;
}
private loadPreferences() {
this._preferences = new Map<string, string>();
const lineRegex = /(\S+)=(\S+)/;
const rawText = fs.readFileSync(path.join(this._settings.packagePath, "preferences.txt"), "utf8");
const lines = rawText.split("\n");
lines.forEach((line) => {
if (line) {
let match = lineRegex.exec(line);
if (match && match.length > 2) {
this._preferences.set(match[1], match[2]);
}
}
});
}
private getBoardDescriptorString(deviceContext: IDeviceContext): string {
let boardDescriptor = this.boardManager.currentBoard;
if (!boardDescriptor) {
Logger.notifyUserError("getBoardDescriptorError", new Error(constants.messages.NO_BOARD_SELECTED));
return;
}
let boardString = `${boardDescriptor.platform.package.name}:${boardDescriptor.platform.architecture}:${boardDescriptor.board}`;
return boardString;
}
}