2
0
mirror of https://github.com/ad1217/PrinterStatus synced 2024-11-21 15:03:48 -05:00

Don't break when printers are not accessible during server startup

This commit is contained in:
Adam Goldsmith 2021-10-28 01:06:42 -04:00
parent 8c18460995
commit 51d3cbf41e

View File

@ -69,6 +69,7 @@ class PrinterStatus {
webcamURL?: URL; webcamURL?: URL;
name?: string; name?: string;
session_key?: string;
websocket?: WebSocket; websocket?: WebSocket;
lastStatus?: messages.ExtendedMessage; lastStatus?: messages.ExtendedMessage;
@ -78,15 +79,17 @@ class PrinterStatus {
this.address = address; this.address = address;
this.apikey = apikey; this.apikey = apikey;
try { // async init
this.init(); // async init this.connect_websocket().catch((e) => {
} catch (e) { console.error('Failed to initialize "${this.slug}"');
throw 'Failed to Init' + e; throw e;
} });
} }
async init() { async connect_websocket() {
// TODO: error handling (try/catch) // initial setup
if (!this.session_key) {
try {
const settings = await this.api_get('settings'); const settings = await this.api_get('settings');
this.webcamURL = new URL(settings.webcam.streamUrl, this.address); this.webcamURL = new URL(settings.webcam.streamUrl, this.address);
this.name = settings.appearance.name; this.name = settings.appearance.name;
@ -95,17 +98,23 @@ class PrinterStatus {
const login: octoprint.LoginResponse = await this.api_post('login', { const login: octoprint.LoginResponse = await this.api_post('login', {
passive: 'true', passive: 'true',
}); });
this.session_key = login.name + ':' + login.session;
this.connect_websocket(login.name + ':' + login.session); } catch {
console.log(
`Failed to connect to "${this.slug}" attempting reconnection in 5 seconds`
);
setTimeout(() => this.connect_websocket(), 5000);
return;
}
} }
connect_websocket(authToken: string): void {
const url = new URL('/sockjs/websocket', this.address); const url = new URL('/sockjs/websocket', this.address);
url.protocol = 'ws'; url.protocol = 'ws';
this.websocket = new WebSocket(url.toString()); this.websocket = new WebSocket(url.toString());
this.websocket this.websocket
.on('open', () => { .on('open', () => {
this.websocket!.send(JSON.stringify({ auth: authToken })); console.log(`Connected to "${this.slug}"`);
this.websocket!.send(JSON.stringify({ auth: this.session_key }));
}) })
.on('message', (data: WebSocket.Data) => { .on('message', (data: WebSocket.Data) => {
const event: octoprint.Message = JSON.parse(data as string); const event: octoprint.Message = JSON.parse(data as string);
@ -122,8 +131,10 @@ class PrinterStatus {
} }
}) })
.on('close', () => { .on('close', () => {
console.log('Lost connection to ' + this.slug + ' reconnecting...'); console.log(
setTimeout(() => this.connect_websocket(authToken), 5000); `Lost connection to "${this.slug}" attempting reconnection in 5 seconds`
);
setTimeout(() => this.connect_websocket(), 5000);
}); });
} }