Skip to content

Commit 3399a67

Browse files
committed
move trace to trace object
1 parent 966690b commit 3399a67

File tree

7 files changed

+81
-56
lines changed

7 files changed

+81
-56
lines changed

examples/typescript/src/index.ts

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ const alertDiv = document.getElementById("alertDiv");
2323
// This is a frontend example of Esptool-JS using local bundle file
2424
// To optimize use a CDN hosted version like
2525
// https://unpkg.com/esptool-js/bundle.js
26-
import { ESPLoader, FlashOptions, LoaderOptions, WebSerialTransport, SerialOptions } from "../../../lib";
26+
import { ESPLoader, FlashOptions, LoaderOptions, WebSerialTransport, SerialOptions, ITrace } from "../../../lib";
2727

2828
declare let Terminal; // Terminal is imported in HTML script
2929
declare let CryptoJS; // CryptoJS is imported in HTML script
@@ -79,10 +79,35 @@ const espLoaderTerminal = {
7979
},
8080
};
8181

82+
class TraceObject implements ITrace {
83+
traceBuffer: string;
84+
private lastTraceTime = Date.now();
85+
86+
trace(message: string) {
87+
const delta = Date.now() - this.lastTraceTime;
88+
const prefix = `TRACE ${delta.toFixed(3)}`;
89+
const traceMessage = `${prefix} ${message}`;
90+
console.log(traceMessage);
91+
this.traceBuffer += traceMessage + "\n";
92+
}
93+
94+
async returnTrace() {
95+
try {
96+
await navigator.clipboard.writeText(this.traceBuffer);
97+
console.log("Text copied to clipboard!");
98+
} catch (err) {
99+
console.error("Failed to copy text:", err);
100+
}
101+
return this.traceBuffer;
102+
}
103+
}
104+
105+
const traceObj = new TraceObject();
106+
82107
connectButton.onclick = async () => {
83108
if (device === null) {
84109
device = await navigator.serial.requestPort({});
85-
transport = new WebSerialTransport(device, true);
110+
transport = new WebSerialTransport(device, traceObj);
86111
}
87112

88113
const serialOptions = { baudRate: parseInt(baudrates.value) } as SerialOptions;
@@ -118,8 +143,8 @@ connectButton.onclick = async () => {
118143
};
119144

120145
traceButton.onclick = async () => {
121-
if (transport) {
122-
transport.returnTrace();
146+
if (traceObj) {
147+
traceObj.returnTrace();
123148
}
124149
};
125150

@@ -233,7 +258,7 @@ let isConsoleClosed = false;
233258
consoleStartButton.onclick = async () => {
234259
if (device === null) {
235260
device = await navigator.serial.requestPort({});
236-
transport = new WebSerialTransport(device, true);
261+
transport = new WebSerialTransport(device, traceObj);
237262
}
238263
lblConsoleFor.style.display = "block";
239264
lblConsoleBaudrate.style.display = "none";
@@ -248,7 +273,7 @@ consoleStartButton.onclick = async () => {
248273
isConsoleClosed = false;
249274

250275
while (true && !isConsoleClosed) {
251-
const val = await transport.rawRead();
276+
const val = await transport.read();
252277
if (typeof val !== "undefined") {
253278
term.write(val);
254279
} else {

src/esploader.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { classicReset, customReset, hardReset, usbJTAGSerialReset } from "./rese
77
import { hexConvert } from "./utils/hex";
88
import { appendArray, bstrToUi8, byteArrayToInt, intToByteArray, shortToBytearray, ui8ToBstr } from "./utils/convert";
99
import { Slip } from "./utils/slip";
10+
import { ITrace } from "./utils/ITrace";
1011

1112
/**
1213
* Options for flashing a device with firmware.
@@ -134,6 +135,12 @@ export interface LoaderOptions {
134135
* @type {ResetFunctions}
135136
*/
136137
resetFunctions?: ResetFunctions;
138+
139+
/**
140+
* The Trace object to log all communication output.
141+
* @type {ITrace}
142+
*/
143+
tracer?: ITrace;
137144
}
138145

139146
/**
@@ -287,6 +294,7 @@ export class ESPLoader {
287294
private debugLogging = false;
288295
private resetFunctions: ResetFunctions;
289296
private slip: Slip;
297+
private tracer?: ITrace;
290298

291299
/**
292300
* Create a new ESPLoader to perform serial communication
@@ -329,6 +337,9 @@ export class ESPLoader {
329337
if (typeof options.debugLogging !== "undefined") {
330338
this.debugLogging = options.debugLogging;
331339
}
340+
if (options.tracer) {
341+
this.tracer = options.tracer;
342+
}
332343
this.slip = new Slip(this.transport);
333344

334345
this.info("esptool.js");
@@ -440,8 +451,8 @@ export class ESPLoader {
440451
timeout: number = 3000,
441452
): Promise<[number, Uint8Array]> {
442453
if (op != null) {
443-
if (this.transport.tracing) {
444-
this.transport.trace(
454+
if (this.tracer) {
455+
this.tracer.trace(
445456
`command op:0x${op.toString(16).padStart(2, "0")} data len=${data.length} wait_response=${
446457
waitResponse ? 1 : 0
447458
} timeout=${(timeout / 1000).toFixed(3)} data=${hexConvert(data)}`,

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@ export { ROM } from "./targets/rom";
1111
export { ISerialTransport, ISerialOptions } from "./transport/ISerialTransport";
1212
export { SerialOptions, WebSerialTransport } from "./transport/WebSerialTransport";
1313
export { Slip, SlipReaderOutput } from "./utils/slip";
14+
export { ITrace } from "./utils/ITrace";

src/transport/ISerialTransport.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ export interface ISerialOptions {
1616
* @interface ISerialTransport
1717
*/
1818
export interface ISerialTransport {
19-
tracing: boolean;
2019
leftOver: Uint8Array;
2120

2221
/**
@@ -31,12 +30,6 @@ export interface ISerialTransport {
3130
*/
3231
getPID(): number | undefined;
3332

34-
/**
35-
* Format received or sent data for tracing output.
36-
* @param {string} message Message to format as trace line.
37-
*/
38-
trace(message: string): void;
39-
4033
/**
4134
* Write binary data to device.
4235
* @param {Uint8Array} data 8 bit unsigned data array to write to device.

src/transport/WebSerialTransport.ts

Lines changed: 8 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import { ISerialTransport, ISerialOptions } from "./ISerialTransport";
44
import { hexConvert } from "../utils/hex";
55
import { appendArray } from "../utils/convert";
6+
import { ITrace } from "../utils/ITrace";
67

78
/**
89
* Options for device serialPort.
@@ -51,11 +52,9 @@ export interface SerialOptions extends ISerialOptions {
5152
*/
5253
export class WebSerialTransport implements ISerialTransport {
5354
public leftOver = new Uint8Array(0);
54-
private traceLog = "";
55-
private lastTraceTime = Date.now();
5655
private reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
5756

58-
constructor(public device: SerialPort, public tracing = false) {}
57+
constructor(public device: SerialPort, private tracer?: ITrace) {}
5958

6059
/**
6160
* Request the serial device vendor ID and Product ID as string.
@@ -76,40 +75,16 @@ export class WebSerialTransport implements ISerialTransport {
7675
return this.device.getInfo().usbProductId;
7776
}
7877

79-
/**
80-
* Format received or sent data for tracing output.
81-
* @param {string} message Message to format as trace line.
82-
*/
83-
trace(message: string) {
84-
const delta = Date.now() - this.lastTraceTime;
85-
const prefix = `TRACE ${delta.toFixed(3)}`;
86-
const traceMessage = `${prefix} ${message}`;
87-
console.log(traceMessage);
88-
this.traceLog += traceMessage + "\n";
89-
}
90-
91-
/**
92-
* Return the whole trace output to the user clipboard.
93-
*/
94-
async returnTrace() {
95-
try {
96-
await navigator.clipboard.writeText(this.traceLog);
97-
console.log("Text copied to clipboard!");
98-
} catch (err) {
99-
console.error("Failed to copy text:", err);
100-
}
101-
}
102-
10378
/**
10479
* Write binary data to device using the WebSerial device writable stream.
10580
* @param {Uint8Array} outData 8 bit unsigned data array to write to device.
10681
*/
10782
async write(outData: Uint8Array) {
10883
if (this.device.writable) {
10984
const writer = this.device.writable.getWriter();
110-
if (this.tracing) {
111-
console.log("Write bytes");
112-
this.trace(`Write ${outData.length} bytes: ${hexConvert(outData)}`);
85+
if (this.tracer) {
86+
this.tracer.trace("Write bytes");
87+
this.tracer.trace(`Write ${outData.length} bytes: ${hexConvert(outData)}`);
11388
}
11489
await writer.write(outData);
11590
writer.releaseLock();
@@ -152,9 +127,9 @@ export class WebSerialTransport implements ISerialTransport {
152127
this.leftOver = packet;
153128
throw new Error("Timeout");
154129
}
155-
if (this.tracing) {
156-
console.log("Raw Read bytes");
157-
this.trace(`Read ${value.length} bytes: ${hexConvert(value)}`);
130+
if (this.tracer) {
131+
this.tracer.trace("Raw Read bytes");
132+
this.tracer.trace(`Read ${value.length} bytes: ${hexConvert(value)}`);
158133
}
159134
const p = appendArray(packet, value);
160135
packet = p;

src/utils/ITrace.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export interface ITrace {
2+
/**
3+
* Buffer with all trace messages.
4+
* @type {string}
5+
*/
6+
traceBuffer: string;
7+
8+
/**
9+
* Send message for tracing output.
10+
* @param {string} message Message to format as trace line.
11+
*/
12+
trace(message: string): void;
13+
14+
/**
15+
* Method to return content of tracing buffer.
16+
*/
17+
returnTrace(): Promise<string>;
18+
}

src/utils/slip.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { ISerialTransport } from "../transport/ISerialTransport";
2+
import { ITrace } from "./ITrace";
23
import { hexConvert } from "./hex";
34

45
/**
@@ -22,10 +23,11 @@ export interface SlipReaderOutput {
2223
/**
2324
* Class to handle SLIP read and write serial methods.
2425
* @param {ISerialTransport} transport Transport object with raw read and write serial methods
25-
* @param {boolean} enableSlipRead Enable or disable read SLIP data formatting.
26+
* @param {boolean} enableSlipRead Enable or disable read SLIP data formatting.
27+
* @param {ITrace} trace Object that log or trace all serial messages.
2628
*/
2729
export class Slip {
28-
constructor(private transport: ISerialTransport, public enableSlipRead: boolean = false) {}
30+
constructor(private transport: ISerialTransport, public enableSlipRead: boolean = false, private tracer?: ITrace) {}
2931

3032
/**
3133
* Format data packet using the Serial Line Internet Protocol (SLIP).
@@ -119,17 +121,17 @@ export class Slip {
119121
}
120122
packet = await this.transport.read(timeout, minData, packet);
121123

122-
if (this.transport.tracing) {
123-
this.transport.trace("Read SLIP bytes");
124-
this.transport.trace(`Read ${packet.length} bytes: ${hexConvert(packet)}`);
124+
if (this.tracer) {
125+
this.tracer.trace("Read SLIP bytes");
126+
this.tracer.trace(`Read ${packet.length} bytes: ${hexConvert(packet)}`);
125127
}
126128

127129
if (this.enableSlipRead) {
128130
const slipReaderResult = this.decode(packet);
129131
this.transport.leftOver = slipReaderResult.newLeftOver;
130-
if (this.transport.tracing) {
131-
this.transport.trace("Slip reader results");
132-
this.transport.trace(`Read ${slipReaderResult.packet.length} bytes: ${hexConvert(slipReaderResult.packet)}`);
132+
if (this.tracer) {
133+
this.tracer.trace("Slip reader results");
134+
this.tracer.trace(`Read ${slipReaderResult.packet.length} bytes: ${hexConvert(slipReaderResult.packet)}`);
133135
}
134136
return slipReaderResult.packet;
135137
}

0 commit comments

Comments
 (0)