Skip to content
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

Use the telnet output to know when the debug protocol port is open #179

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions src/adapters/DebugProtocolAdapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,10 @@ describe('DebugProtocolAdapter', function() {
* Handles the initial connection and the "stop at first byte code" flow
*/
async function initialize() {
sinon.stub(adapter, 'processTelnetOutput').callsFake(async () => {});

await adapter.connect();
await adapter['connectSocketDebugger']();
client = adapter['socketDebugger'];
client['options'].shutdownTimeout = 100;
client['options'].exitChannelTimeout = 100;
Expand Down
49 changes: 38 additions & 11 deletions src/adapters/DebugProtocolAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ export class DebugProtocolAdapter {
});
}

private connectionDeferred = defer<void>();

public deferredConnectionPromise(): Promise<void> {
Christian-Holbrook marked this conversation as resolved.
Show resolved Hide resolved
return this.connectionDeferred.promise;
}

private logger = logger.createLogger(`[padapter]`);

/**
Expand Down Expand Up @@ -210,6 +216,9 @@ export class DebugProtocolAdapter {
* Connect to the telnet session. This should be called before the channel is launched.
*/
public async connect() {
//Start processing telnet output to look for compile errors or the debugger prompt
await this.processTelnetOutput();

let deferred = defer();
this.socketDebugger = new DebugProtocolClient(this.options);
try {
Expand Down Expand Up @@ -292,15 +301,6 @@ export class DebugProtocolAdapter {
this.emit('breakpoints-verified', event);
});

this.connected = await this.socketDebugger.connect();

this.logger.log(`Closing telnet connection used for compile errors`);
if (this.compileClient) {
this.compileClient.removeAllListeners();
this.compileClient.destroy();
this.compileClient = undefined;
}

this.socketDebugger.on('compile-error', (update) => {
let diagnostics: BSDebugDiagnostic[] = [];
diagnostics.push({
Expand All @@ -313,7 +313,19 @@ export class DebugProtocolAdapter {
this.emit('diagnostics', diagnostics);
});

this.socketDebugger.on('control-connected', () => {
this.connectionDeferred.resolve();

this.logger.log(`Closing telnet connection used for compile errors`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not close this. The compileClient (telnet connection) should stay alive for the lifetime of the debug session (i.e. until someone clicks "stop")

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a small step to start using the telnet logs to trigger the control port connection.

I'm starting the work to keep the debug session open once the control port closes.

if (this.compileClient) {
this.compileClient.removeAllListeners();
this.compileClient.destroy();
this.compileClient = undefined;
}
});

this.logger.log(`Connected to device`, { host: this.options.host, connected: this.connected });
this.connected = true;
this.emit('connected', this.connected);

//the adapter is connected and running smoothly. resolve the promise
Expand All @@ -337,8 +349,7 @@ export class DebugProtocolAdapter {
public get supportsCompileErrorReporting() {
return semver.satisfies(this.deviceInfo.brightscriptDebuggerVersion, '>=3.1.0');
}

public async watchCompileOutput() {
public async processTelnetOutput() {
let deferred = defer();
try {
this.compileClient = new Socket();
Expand Down Expand Up @@ -376,6 +387,9 @@ export class DebugProtocolAdapter {
lastPartialLine = '';
}
// Emit the completed io string.
this.processUnhandedOutputForDebugPrompt(responseText.trim()).catch((e) => {
console.log(`Error processing telnet output for debug prompt`);
});
this.compileErrorProcessor.processUnhandledLines(responseText.trim());
this.emit('unhandled-console-output', responseText.trim());
}
Expand All @@ -389,6 +403,19 @@ export class DebugProtocolAdapter {
return deferred.promise;
}

private async processUnhandedOutputForDebugPrompt(responseText: string) {
let lines = responseText.split(/\r?\n/g);
for (const line of lines) {
if (/Waiting for debugger on \d+\.\d+\.\d+\.\d+:8081/g.exec(line)) {
await this.connectSocketDebugger();
}
}
}

private async connectSocketDebugger() {
await this.socketDebugger.connect();
}

/**
* Send command to step over
*/
Expand Down
7 changes: 7 additions & 0 deletions src/adapters/TelnetAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ export class TelnetAdapter {
});
}

private connectionDeferred = defer<void>();

public deferredConnectionPromise(): Promise<void> {
return this.connectionDeferred.promise;
}

public logger = logger.createLogger(`[tadapter]`);
/**
* Indicates whether the adapter has successfully established a connection with the device
Expand Down Expand Up @@ -239,6 +245,7 @@ export class TelnetAdapter {
client.connect(this.options.brightScriptConsolePort, this.options.host, () => {
this.logger.log(`Telnet connection established to ${this.options.host}:${this.options.brightScriptConsolePort}`);
this.connected = true;
this.connectionDeferred.resolve();
this.emit('connected', this.connected);
});

Expand Down
5 changes: 3 additions & 2 deletions src/debugProtocol/client/DebugProtocolClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ export class DebugProtocolClient {
public on<T = AllThreadsStoppedUpdate | ThreadAttachedUpdate>(eventName: 'runtime-error' | 'suspend', handler: (data: T) => void);
public on(eventName: 'io-output', handler: (output: string) => void);
public on(eventName: 'protocol-version', handler: (data: ProtocolVersionDetails) => void);
public on(eventName: 'control-connected', handler: () => void);
public on(eventName: 'handshake-verified', handler: (data: HandshakeResponse) => void);
// public on(eventname: 'rendezvous', handler: (output: RendezvousHistory) => void);
// public on(eventName: 'runtime-error', handler: (error: BrightScriptRuntimeError) => void);
Expand All @@ -201,7 +202,7 @@ export class DebugProtocolClient {
private emit(eventName: 'data', update: Buffer);
private emit(eventName: 'breakpoints-verified', event: BreakpointsVerifiedEvent);
private emit(eventName: 'suspend' | 'runtime-error', data: AllThreadsStoppedUpdate | ThreadAttachedUpdate);
private emit(eventName: 'app-exit' | 'cannot-continue' | 'close' | 'handshake-verified' | 'io-output' | 'protocol-version' | 'start', data?);
private emit(eventName: 'app-exit' | 'cannot-continue' | 'close' | 'handshake-verified' | 'io-output' | 'protocol-version' | 'control-connected' | 'start', data?);
private async emit(eventName: string, data?) {
//emit these events on next tick, otherwise they will be processed immediately which could cause issues
await util.sleep(0);
Expand Down Expand Up @@ -253,6 +254,7 @@ export class DebugProtocolClient {
client: this,
server: connection
});
await this.emit('control-connected');
return connection;
}

Expand Down Expand Up @@ -611,7 +613,6 @@ export class DebugProtocolClient {
return simulatedResponse;
}
}
console.log('Bronley');
//prop in the middle is missing, tried reading a prop on it
// ex: variablePathEntries = ["there", "thereButSetToInvalid", "definitelyNotThere"]
throw new Error(`Cannot read '${variablePathEntries[invalidPathIndex + 1]}'${parentVarType ? ` on type '${parentVarTypeText}'` : ''}`);
Expand Down
21 changes: 4 additions & 17 deletions src/debugSession/BrightScriptDebugSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,7 @@ export class BrightScriptDebugSession extends BaseDebugSession {
await this.initRendezvousTracking();

this.createRokuAdapter(this.rendezvousTracker);
if (!this.enableDebugProtocol) {
//connect to the roku debug via telnet
if (!this.rokuAdapter.connected) {
await this.connectRokuAdapter();
}
} else {
await (this.rokuAdapter as DebugProtocolAdapter).watchCompileOutput();
}
await this.connectRokuAdapter();

await this.runAutomaticSceneGraphCommands(this.launchConfiguration.autoRunSgDebugCommands);

Expand Down Expand Up @@ -336,7 +329,7 @@ export class BrightScriptDebugSession extends BaseDebugSession {
}
});

await this.connectAndPublish();
await this.publish();

this.sendEvent(new ChannelPublishedEvent(
this.launchConfiguration
Expand Down Expand Up @@ -461,13 +454,7 @@ export class BrightScriptDebugSession extends BaseDebugSession {
this.sendEvent(new DiagnosticsEvent(diagnostics));
}

private async connectAndPublish() {
let connectPromise: Promise<any>;
//connect to the roku debug via sockets
if (this.enableDebugProtocol) {
connectPromise = this.connectRokuAdapter().catch(e => this.logger.error(e));
}

private async publish() {
this.logger.log('Uploading zip');
const start = Date.now();
let packageIsPublished = false;
Expand Down Expand Up @@ -507,7 +494,7 @@ export class BrightScriptDebugSession extends BaseDebugSession {
//the channel has been deployed. Wait for the adapter to finish connecting.
//if it hasn't connected after 5 seconds, it probably will never connect.
await Promise.race([
connectPromise,
this.rokuAdapter.deferredConnectionPromise(),
util.sleep(10000)
]);
this.logger.log('Finished racing promises');
Expand Down