Skip to content
This repository has been archived by the owner on Dec 23, 2021. It is now read-only.

Commit

Permalink
Add new command to deploy to the device (#27)
Browse files Browse the repository at this point in the history
PBI: 29761
Task: 29765, 29769

* add new command to deploy to the device

* keep destination name the same as source

* refactor directory finding method and address comments

* update comment reference

* Rewrite the device finding code without influence of mu

* change string interpolation to a more compatible version

* remove use if platform module

* Update code to work on Unix devices

* Break when we find the first matching device
  • Loading branch information
LukeSlev authored Jul 4, 2019
1 parent 2400dfc commit 902557f
Show file tree
Hide file tree
Showing 7 changed files with 162 additions and 21 deletions.
4 changes: 3 additions & 1 deletion locales/en/out/constants.i18n.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"error.stderr": "[ERROR] {0} \n",
"error.unexpectedMessage": "Webview sent an unexpected message",
"info.deployOutput": "\n[INFO] Deploying code to the simulator...\n",
"info.deployDevice": "\n[INFO] Deploying code to the device...\n",
"info.deploySimulator": "\n[INFO] Deploying code to the simulator...\n",
"info.deploySuccess": "\n[INFO] Code successfully deployed\n",
"info.extensionActivated": "Congratulations, your extension Adafruit_Simulator is now active!",
"info.runningCode": "Running user code",
"info.welcomeOutputTab": "Welcome to the Adafruit Simulator output tab !\n\n",
Expand Down
4 changes: 3 additions & 1 deletion locales/en/package.i18n.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"pacificaExtension.commands.label": "Adafruit",
"pacificaExtension.commands.openSimulator": "Open Simulator",
"pacificaExtension.commands.runSimulator": "Run Simulator"
"pacificaExtension.commands.runSimulator": "Run Simulator",
"pacificaExtension.commands.newProject": "New Project",
"pacificaExtension.commands.runDevice": "Deploy to Device"
}
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"activationEvents": [
"onCommand:pacifica.openSimulator",
"onCommand:pacifica.runSimulator",
"onCommand:pacifica.newProject"
"onCommand:pacifica.newProject",
"onCommand:pacifica.runDevice"
],
"main": "./out/extension.js",
"contributes": {
Expand All @@ -44,6 +45,11 @@
"command": "pacifica.newProject",
"title": "%pacificaExtension.commands.newProject%",
"category": "%pacificaExtension.commands.label%"
},
{
"command": "pacifica.runDevice",
"title": "%pacificaExtension.commands.runDevice%",
"category": "%pacificaExtension.commands.label%"
}
]
},
Expand Down
3 changes: 2 additions & 1 deletion package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
"pacificaExtension.commands.label": "Adafruit",
"pacificaExtension.commands.openSimulator": "Open Simulator",
"pacificaExtension.commands.runSimulator": "Run Simulator",
"pacificaExtension.commands.newProject": "New Project"
"pacificaExtension.commands.newProject": "New Project",
"pacificaExtension.commands.runDevice": "Deploy to Device"
}
13 changes: 11 additions & 2 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,19 @@ export const CONSTANTS = {
)
},
INFO: {
DEPLOY_OUTPUT: localize(
"info.deployOutput",
COMPLETED_MESSAGE: "Completed",
DEPLOY_DEVICE: localize(
"info.deployDevice",
"\n[INFO] Deploying code to the device...\n"
),
DEPLOY_SIMULATOR: localize(
"info.deploySimulator",
"\n[INFO] Deploying code to the simulator...\n"
),
DEPLOY_SUCCESS: localize(
"info.deploySuccess",
"\n[INFO] Code successfully deployed\n"
),
EXTENSION_ACTIVATED: localize(
"info.extensionActivated",
"Congratulations, your extension Adafruit_Simulator is now active!"
Expand Down
64 changes: 64 additions & 0 deletions src/device.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from subprocess import check_output
import string
import os
import sys
if sys.platform == "win32":
# pylint: disable=import-error
import win32api


class Adafruit:
def __init__(self):
self.connected = False
self.error_message = None

def find_device_directory(self):
"""
Check if the Circuit Playground Express is available/plugged in
"""
found_directory = None

if sys.platform.startswith("linux") or sys.platform.startswith("darwin"):
# Mac or Linux
mounted = check_output('mount').decode('utf-8').split('\n')
for mount in mounted:
drive_path = mount.split()[2] if mount else ""
if drive_path.endswith("CIRCUITPY"):
found_directory = drive_path
break
elif sys.platform == "win32":
# Windows
for drive_letter in string.ascii_uppercase:
drive_path = "{}:{}".format(drive_letter, os.sep)
if (os.path.exists(drive_path)):
drive_name = win32api.GetVolumeInformation(drive_path)[0]
if drive_name == "CIRCUITPY":
found_directory = drive_path
break
else:
raise NotImplementedError(
'The OS "{}" not supported.'.format(sys.platform))

if not found_directory:
self.connected = False
self.error_message = ("No Circuit Playground Express detected",
"Could not find drive with name 'CIRCUITPYTHON'. Detected OS: {}".format(sys.platform))
else:
self.connected = True
self.error_message = None
return found_directory


if __name__ == "__main__":
import shutil

cpx = Adafruit()
device_directory = cpx.find_device_directory()
if cpx.error_message:
print("{}:\t{}".format(
cpx.error_message[0], cpx.error_message[1]), file=sys.stderr, flush=True)
if cpx.connected:
dest_path = os.path.join(
device_directory, sys.argv[1].rsplit(os.sep, 1)[-1])
shutil.copyfile(sys.argv[1], dest_path)
print("Completed", end="", flush=True)
87 changes: 72 additions & 15 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ export function activate(context: vscode.ExtensionContext) {
// Add our library path to settings.json for autocomplete functionality
updatePythonExtraPaths();

// Opening the output panel
if (outChannel === undefined) {
outChannel = vscode.window.createOutputChannel(CONSTANTS.NAME);
logToOutputChannel(outChannel, CONSTANTS.INFO.WELCOME_OUTPUT_TAB, true);
}

// Open Simulator on the webview
let openSimulator = vscode.commands.registerCommand(
"pacifica.openSimulator",
Expand Down Expand Up @@ -62,13 +68,15 @@ export function activate(context: vscode.ExtensionContext) {
const filePath = __dirname + path.sep + fileName;
const file = fs.readFileSync(filePath, "utf8");

vscode.workspace.openTextDocument({content: file, language: "en"})
.then((template: vscode.TextDocument) => {
vscode.window.showTextDocument(template, 1, false);
}), (error: any) => {
console.error(`Failed to open a new text document: ${error}`);
}
}
vscode.workspace
.openTextDocument({ content: file, language: "en" })
.then((template: vscode.TextDocument) => {
vscode.window.showTextDocument(template, 1, false);
}),
(error: any) => {
console.error(`Failed to open a new text document: ${error}`);
};
}
);

// Send message to the webview
Expand Down Expand Up @@ -104,13 +112,7 @@ export function activate(context: vscode.ExtensionContext) {
childProcess.kill();
}

// Opening the output panel
if (outChannel === undefined) {
outChannel = vscode.window.createOutputChannel(CONSTANTS.NAME);
logToOutputChannel(outChannel, CONSTANTS.INFO.WELCOME_OUTPUT_TAB, true);
}

logToOutputChannel(outChannel, CONSTANTS.INFO.DEPLOY_OUTPUT);
logToOutputChannel(outChannel, CONSTANTS.INFO.DEPLOY_SIMULATOR);

childProcess = cp.spawn("python", [
scriptPath.fsPath,
Expand Down Expand Up @@ -203,7 +205,62 @@ export function activate(context: vscode.ExtensionContext) {
}
);

context.subscriptions.push(openSimulator, runSimulator, newProject);
// Send message to the webview
let runDevice = vscode.commands.registerCommand("pacifica.runDevice", () => {
console.info("Sending code to device");

logToOutputChannel(outChannel, CONSTANTS.INFO.DEPLOY_DEVICE);

const activeTextEditor: vscode.TextEditor | undefined =
vscode.window.activeTextEditor;
let currentFileAbsPath: string = "";

if (activeTextEditor) {
currentFileAbsPath = activeTextEditor.document.fileName;
}

// Get the Python script path (And the special URI to use with the webview)
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, "out", "device.py")
);
const scriptPath = onDiskPath.with({ scheme: "vscode-resource" });

const deviceProcess = cp.spawn("python", [
scriptPath.fsPath,
currentFileAbsPath
]);

let dataFromTheProcess = "";

// Data received from Python process
deviceProcess.stdout.on("data", data => {
dataFromTheProcess = data.toString();
if (dataFromTheProcess === CONSTANTS.INFO.COMPLETED_MESSAGE) {
logToOutputChannel(outChannel, CONSTANTS.INFO.DEPLOY_SUCCESS);
}
console.log(`Device output = ${dataFromTheProcess}`);
});

// Std error output
deviceProcess.stderr.on("data", data => {
console.error(
`Error from the Python device process through stderr: ${data}`
);
logToOutputChannel(outChannel, `[ERROR] ${data} \n`, true);
});

// When the process is done
deviceProcess.on("end", (code: number) => {
console.info(`Command execution exited with code: ${code}`);
});
});

context.subscriptions.push(
openSimulator,
runSimulator,
runDevice,
newProject
);
}

const updatePythonExtraPaths = () => {
Expand Down

0 comments on commit 902557f

Please sign in to comment.