Better disconnect and connection timeout handling

This commit is contained in:
2024-10-05 15:24:07 +02:00
parent 1d93632f6d
commit 6272dbf38a

View File

@@ -37,15 +37,23 @@ class ModbusRTUMaster {
} }
async disconnect() { async disconnect() {
if (this.reader) { console.log('Disconnect requested');
await this.reader.releaseLock(); try {
} if (this.reader) {
if (this.writer) { await this.reader.releaseLock();
await this.writer.releaseLock(); this.reader = null;
} }
if (this.port) { if (this.writer) {
await this.port.close(); await this.writer.releaseLock();
console.log('Serial port closed'); this.writer = null;
}
if (this.port) {
await this.port.close();
this.port = null;
console.log('Serial port closed');
}
} catch (error) {
console.error('Error during disconnect:', error);
} }
} }
@@ -161,10 +169,16 @@ class ModbusRTUMaster {
} }
} catch (error) { } catch (error) {
console.error('Error receiving response:', error.message); console.error('Error receiving response:', error.message);
if (this.reader) {
await this.reader.cancel();
await this.reader.releaseLock();
this.reader = null;
this.reader = this.port.readable.getReader();
}
if (error.message.includes('Device has been lost')) { if (error.message.includes('Device has been lost')) {
await this.handleDeviceLost(); await this.handleDeviceLost();
} }
return { error: error.message }; return { error: error.message }; // TODO: or throw error; ?
} }
} }