Skip to content

add unit tests for monitor utils #522

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions arduino-ide-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@
"download": "^7.1.0",
"grpc_tools_node_protoc_ts": "^4.1.0",
"mocha": "^7.0.0",
"mockdate": "^3.0.5",
"moment": "^2.24.0",
"protoc": "^1.0.4",
"shelljs": "^0.8.3",
Expand Down
237 changes: 117 additions & 120 deletions arduino-ide-extension/src/browser/monitor/monitor-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,129 +71,15 @@ export class MonitorConnection {

@postConstruct()
protected init(): void {
this.monitorServiceClient.onMessage(async (port) => {
const w = new WebSocket(`ws://localhost:${port}`);
w.onmessage = (res) => {
const messages = JSON.parse(res.data);
this.onReadEmitter.fire({ messages });
};
});

// let i = 0;
// this.monitorServiceClient.onMessage(async (msg) => {
// // msg received
// i++;
// if (i % 1000 === 0) {
// // console.log(msg);
// }
// });

this.monitorServiceClient.onError(async (error) => {
let shouldReconnect = false;
if (this.state) {
const { code, config } = error;
const { board, port } = config;
const options = { timeout: 3000 };
switch (code) {
case MonitorError.ErrorCodes.CLIENT_CANCEL: {
console.debug(
`Connection was canceled by client: ${MonitorConnection.State.toString(
this.state
)}.`
);
break;
}
case MonitorError.ErrorCodes.DEVICE_BUSY: {
this.messageService.warn(
`Connection failed. Serial port is busy: ${Port.toString(port)}.`,
options
);
shouldReconnect = this.autoConnect;
this.monitorErrors.push(error);
break;
}
case MonitorError.ErrorCodes.DEVICE_NOT_CONFIGURED: {
this.messageService.info(
`Disconnected ${Board.toString(board, {
useFqbn: false,
})} from ${Port.toString(port)}.`,
options
);
break;
}
case undefined: {
this.messageService.error(
`Unexpected error. Reconnecting ${Board.toString(
board
)} on port ${Port.toString(port)}.`,
options
);
console.error(JSON.stringify(error));
shouldReconnect = this.connected && this.autoConnect;
break;
}
}
const oldState = this.state;
this.state = undefined;
this.onConnectionChangedEmitter.fire(this.state);
if (shouldReconnect) {
if (this.monitorErrors.length >= 10) {
this.messageService.warn(
`Failed to reconnect ${Board.toString(board, {
useFqbn: false,
})} to the the serial-monitor after 10 consecutive attempts. The ${Port.toString(
port
)} serial port is busy. after 10 consecutive attempts.`
);
this.monitorErrors.length = 0;
} else {
const attempts = this.monitorErrors.length || 1;
if (this.reconnectTimeout !== undefined) {
// Clear the previous timer.
window.clearTimeout(this.reconnectTimeout);
}
const timeout = attempts * 1000;
this.messageService.warn(
`Reconnecting ${Board.toString(board, {
useFqbn: false,
})} to ${Port.toString(port)} in ${attempts} seconds...`,
{ timeout }
);
this.reconnectTimeout = window.setTimeout(
() => this.connect(oldState.config),
timeout
);
}
}
}
});
this.monitorServiceClient.onMessage(this.handleMessage.bind(this));
this.monitorServiceClient.onError(this.handleError.bind(this));
this.boardsServiceProvider.onBoardsConfigChanged(
this.handleBoardConfigChange.bind(this)
);
this.notificationCenter.onAttachedBoardsChanged((event) => {
if (this.autoConnect && this.connected) {
const { boardsConfig } = this.boardsServiceProvider;
if (
this.boardsServiceProvider.canUploadTo(boardsConfig, {
silent: false,
})
) {
const { attached } = AttachedBoardsChangeEvent.diff(event);
if (
attached.boards.some(
(board) =>
!!board.port && BoardsConfig.Config.sameAs(boardsConfig, board)
)
) {
const { selectedBoard: board, selectedPort: port } = boardsConfig;
const { baudRate } = this.monitorModel;
this.disconnect().then(() =>
this.connect({ board, port, baudRate })
);
}
}
}
});
this.notificationCenter.onAttachedBoardsChanged(
this.handleAttachedBoardsChanged.bind(this)
);

// Handles the `baudRate` changes by reconnecting if required.
this.monitorModel.onChange(({ property }) => {
if (property === 'baudRate' && this.autoConnect && this.connected) {
Expand All @@ -203,6 +89,14 @@ export class MonitorConnection {
});
}

async handleMessage(port: string): Promise<void> {
const w = new WebSocket(`ws://localhost:${port}`);
w.onmessage = (res) => {
const messages = JSON.parse(res.data);
this.onReadEmitter.fire({ messages });
};
}

get connected(): boolean {
return !!this.state;
}
Expand Down Expand Up @@ -234,6 +128,109 @@ export class MonitorConnection {
}
}

handleError(error: MonitorError): void {
let shouldReconnect = false;
if (this.state) {
const { code, config } = error;
const { board, port } = config;
const options = { timeout: 3000 };
switch (code) {
case MonitorError.ErrorCodes.CLIENT_CANCEL: {
console.debug(
`Connection was canceled by client: ${MonitorConnection.State.toString(
this.state
)}.`
);
break;
}
case MonitorError.ErrorCodes.DEVICE_BUSY: {
this.messageService.warn(
`Connection failed. Serial port is busy: ${Port.toString(port)}.`,
options
);
shouldReconnect = this.autoConnect;
this.monitorErrors.push(error);
break;
}
case MonitorError.ErrorCodes.DEVICE_NOT_CONFIGURED: {
this.messageService.info(
`Disconnected ${Board.toString(board, {
useFqbn: false,
})} from ${Port.toString(port)}.`,
options
);
break;
}
case undefined: {
this.messageService.error(
`Unexpected error. Reconnecting ${Board.toString(
board
)} on port ${Port.toString(port)}.`,
options
);
console.error(JSON.stringify(error));
shouldReconnect = this.connected && this.autoConnect;
break;
}
}
const oldState = this.state;
this.state = undefined;
this.onConnectionChangedEmitter.fire(this.state);
if (shouldReconnect) {
if (this.monitorErrors.length >= 10) {
this.messageService.warn(
`Failed to reconnect ${Board.toString(board, {
useFqbn: false,
})} to the the serial-monitor after 10 consecutive attempts. The ${Port.toString(
port
)} serial port is busy. after 10 consecutive attempts.`
);
this.monitorErrors.length = 0;
} else {
const attempts = this.monitorErrors.length || 1;
if (this.reconnectTimeout !== undefined) {
// Clear the previous timer.
window.clearTimeout(this.reconnectTimeout);
}
const timeout = attempts * 1000;
this.messageService.warn(
`Reconnecting ${Board.toString(board, {
useFqbn: false,
})} to ${Port.toString(port)} in ${attempts} seconds...`,
{ timeout }
);
this.reconnectTimeout = window.setTimeout(
() => this.connect(oldState.config),
timeout
);
}
}
}
}

handleAttachedBoardsChanged(event: AttachedBoardsChangeEvent): void {
if (this.autoConnect && this.connected) {
const { boardsConfig } = this.boardsServiceProvider;
if (
this.boardsServiceProvider.canUploadTo(boardsConfig, {
silent: false,
})
) {
const { attached } = AttachedBoardsChangeEvent.diff(event);
if (
attached.boards.some(
(board) =>
!!board.port && BoardsConfig.Config.sameAs(boardsConfig, board)
)
) {
const { selectedBoard: board, selectedPort: port } = boardsConfig;
const { baudRate } = this.monitorModel;
this.disconnect().then(() => this.connect({ board, port, baudRate }));
}
}
}
}

async connect(config: MonitorConfig): Promise<Status> {
if (this.connected) {
const disconnectStatus = await this.disconnect();
Expand Down
14 changes: 8 additions & 6 deletions arduino-ide-extension/src/browser/monitor/monitor-utils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { Line, SerialMonitorOutput } from './serial-monitor-send-output';

export function messageToLines(
export function messagesToLines(
messages: string[],
prevLines: Line[],
prevLines: Line[] = [],
charCount = 0,
separator = '\n'
): [Line[], number] {
const linesToAdd: Line[] = prevLines.length
? [prevLines[prevLines.length - 1]]
: [{ message: '', lineLen: 0 }];
let charCount = 0;

for (const message of messages) {
const messageLen = message.length;
Expand Down Expand Up @@ -38,11 +38,12 @@ export function messageToLines(

export function truncateLines(
lines: Line[],
charCount: number
charCount: number,
maxCharacters: number = SerialMonitorOutput.MAX_CHARACTERS
): [Line[], number] {
let charsToDelete = charCount - SerialMonitorOutput.MAX_CHARACTERS;
let charsToDelete = charCount - maxCharacters;
let lineIndex = 0;
while (charsToDelete > 0) {
while (charsToDelete > 0 || lineIndex > 0) {
const firstLineLength = lines[lineIndex]?.lineLen;

if (charsToDelete >= firstLineLength) {
Expand All @@ -55,6 +56,7 @@ export function truncateLines(

// delete all previous lines
lines.splice(0, lineIndex);
lineIndex = 0;

const newFirstLine = lines[0]?.message?.substring(charsToDelete);
const deletedCharsCount = firstLineLength - newFirstLine.length;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import AutoSizer from 'react-virtualized-auto-sizer';
import { MonitorModel } from './monitor-model';
import { MonitorConnection } from './monitor-connection';
import dateFormat = require('dateformat');
import { messageToLines, truncateLines } from './monitor-utils';
import { messagesToLines, truncateLines } from './monitor-utils';

export type Line = { message: string; timestamp?: Date; lineLen: number };

Expand Down Expand Up @@ -66,14 +66,12 @@ export class SerialMonitorOutput extends React.Component<
this.scrollToBottom();
this.toDisposeBeforeUnmount.pushAll([
this.props.monitorConnection.onRead(({ messages }) => {
const [newLines, charsToAddCount] = messageToLines(
const [newLines, totalCharCount] = messagesToLines(
messages,
this.state.lines
);
const [lines, charCount] = truncateLines(
newLines,
this.state.charCount + charsToAddCount
this.state.lines,
this.state.charCount
);
const [lines, charCount] = truncateLines(newLines, totalCharCount);

this.setState({
lines,
Expand Down
Loading