Skip to content

Commit

Permalink
First tests for device.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
robmosca committed Dec 11, 2023
1 parent 6a055df commit 3102bb4
Show file tree
Hide file tree
Showing 5 changed files with 254 additions and 84 deletions.
12 changes: 0 additions & 12 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,6 @@
],
"outFiles": ["${workspaceFolder}/out/**/*.js"],
"preLaunchTask": "${defaultBuildTask}"
},
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"args": [
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": ["${workspaceFolder}/out/test/**/*.js"],
"preLaunchTask": "${defaultBuildTask}"
}
]
}
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@
"@types/mocha": "^10.0.6",
"@types/node": "^18.19.3",
"@types/serialport": "^8.0.1",
"@types/sinon": "^17.0.2",
"@types/sinon-chai": "^3.2.12",
"@types/vscode": "^1.53.0",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
Expand All @@ -125,6 +127,8 @@
"glob": "^10.3.10",
"mocha": "^10.2.0",
"prettier": "^3.1.0",
"sinon": "^17.0.1",
"sinon-chai": "^3.7.0",
"typescript": "^5.3.3"
},
"dependencies": {
Expand Down
119 changes: 119 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

83 changes: 11 additions & 72 deletions src/device.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { SerialPort } from 'serialport';
import { SerialPort, SerialPortMock } from 'serialport';
import { EventEmitter } from 'events';
import { APIRequest } from './api';
import { encodeBase64 } from './utils';

export type SlotType = 'all' | 'empty' | 'full';
const _testing: {
SerialPortType: typeof SerialPort | typeof SerialPortMock;
} = {
SerialPortType: SerialPort,
};

const PROMPT = '\r\n>>> ';
export type SlotType = 'all' | 'empty' | 'full';

export enum DeviceMode {
REPL,
Expand Down Expand Up @@ -49,7 +53,7 @@ class Device extends EventEmitter {
ttyDevice: string;
name: string;
firmwareVersion: string;
serialPort: SerialPort | undefined;
serialPort: SerialPort | SerialPortMock | undefined;
devMode: DeviceMode;
storageStatus: StorageStatus | undefined;

Expand All @@ -69,73 +73,6 @@ class Device extends EventEmitter {
}
}

private async obtainPrompt() {
return new Promise<void>((resolve) => {
this.assertConnected();
const dataHandler = (data: Buffer) => {
if (data.toString().endsWith(PROMPT)) {
this.serialPort?.removeListener('data', dataHandler);
this.devMode = DeviceMode.REPL;
resolve();
}
};
this.serialPort?.on('data', dataHandler);
this.serialPort?.write('\x03');
});
}

private async execPythonCmd(cmd: string): Promise<string> {
const removePrefix = (str: string, prefix: string) =>
str.startsWith(prefix) ? str.substring(prefix.length) : str;
const removeSuffix = (str: string, prefix: string) =>
str.endsWith(prefix) ? str.substring(0, str.length - prefix.length) : str;

if (this.devMode !== DeviceMode.REPL) {
await this.obtainPrompt();
}

return new Promise((resolve, reject) => {
this.assertConnected();

let output = '';

const processData = (data: Buffer) => {
const stringData = data.toString();
if (stringData.endsWith(PROMPT)) {
this.serialPort?.removeListener('data', processData);
output += removeSuffix(stringData, PROMPT);
output = removePrefix(output, cmd);
output = removePrefix(output, '... \r\n');
if (output.toLowerCase().trim().startsWith('traceback')) {
reject(new Error(output));
} else {
resolve(output);
}
} else {
output += stringData;
}
};

this.serialPort?.on('data', processData);
this.serialPort?.write(Buffer.from(`${cmd}\r\n`));
this.serialPort?.flush();
});
}

// TODO: Disabling retrieval of name for the moment as this would require
// a soft restart to go back to API mode
// async retrieveName() {
// try {
// const response = await this.execPythonCmd(
// "with open('local_name.txt') as f: print(f.read())\r\n",
// );
// this.name = response;
// } catch (err) {
// this.name = 'LEGO Hub';
// }
// this.emit('change');
// }

private executeSlotSpecificCommand(cmd: string, slotId: number) {
this.assertConnected();
checkSlotId(slotId);
Expand Down Expand Up @@ -231,7 +168,7 @@ class Device extends EventEmitter {

connect() {
return new Promise<void>((resolve, reject) => {
this.serialPort = new SerialPort(
this.serialPort = new _testing.SerialPortType(
{
path: this.ttyDevice,
baudRate: 115200,
Expand Down Expand Up @@ -342,3 +279,5 @@ export function addDeviceOnChangeCallbak(callback: () => void) {
export function removeDeviceAllListeners() {
device?.removeAllListeners();
}

export { _testing };
Loading

0 comments on commit 3102bb4

Please sign in to comment.