Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

Commit

Permalink
Hotfix/s7 wrong connection crash (#38)
Browse files Browse the repository at this point in the history
Fix S7 driver crashing app when failing to connect to host.
- Using `once` allows to use inbuilt S7 lib reconnect function. 
- Remove `emit("error") as kills app on minor connection failure.

Also tidy log descriptions.

Issue #37
  • Loading branch information
grigals authored Nov 29, 2023
2 parents a7316b0 + b74cb65 commit 4487eed
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions lib/devices/S7.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,18 +44,18 @@ export class S7Connection extends DeviceConnection {
// Pass on disconnect event to parent
this.#s7Conn.on('disconnect', () => {
this.emit('close');
log(`☠️ Southbound S7 disconnected from ${this.#s7Conn._connOptsTcp.host}:${this.#s7Conn._connOptsTcp.port}`);
});

// Notify when connection is ready
this.#s7Conn.on('connect', () => {
log(`S7 connected to ${this.#s7Conn._connOptsTcp.host}:${this.#s7Conn._connOptsTcp.port}`)
log(`🔌 Southbound S7 connected to ${this.#s7Conn._connOptsTcp.host}:${this.#s7Conn._connOptsTcp.port}`)
this.emit("open");
});

// Pass on errors to parent
this.#s7Conn.on('error', (e: Error) => {
this.emit('error');
log("S7 Error: " + e);
log(`⚠️ Southbound S7 Error for ${this.#s7Conn._connOptsTcp.host}:${this.#s7Conn._connOptsTcp.port}: ` + e);
})
}

Expand All @@ -77,9 +77,6 @@ export class S7Connection extends DeviceConnection {
* Open the connection to the PLC
*/
async open() {
if (!this.#s7Conn.isConnected) {
this.#s7Conn.connect()
}
}

/**
Expand All @@ -90,8 +87,16 @@ export class S7Connection extends DeviceConnection {
async readMetrics(metrics: Metrics, payloadFormat?: string,) {
const changedMetrics: sparkplugMetric[] = [];
// Tell S7 to update metric values
let newVals = await this.#itemGroup.readAllItems(); // name: value
this.emit('data', newVals, false);

try {
let newVals = await this.#itemGroup.readAllItems(); // name: value
log(JSON.stringify(newVals));
this.emit('data', newVals, false);
} catch (error) {
// When a read fails, the connection is closed and the error is emitted
// This is a workaround so that the app does not crash
log(`⚠️ Southbound S7 read error for ${this.#s7Conn._connOptsTcp.host}:${this.#s7Conn._connOptsTcp.port}: ` + error);
}
}

/**
Expand Down

0 comments on commit 4487eed

Please sign in to comment.