Merge pull request #1 from Pablo2048/development

Better disconnect handling
This commit is contained in:
2024-10-09 14:06:56 +02:00
committed by GitHub

View File

@@ -37,16 +37,25 @@ class ModbusRTUMaster {
} }
async disconnect() { async disconnect() {
console.log('Disconnect requested');
try {
if (this.reader) { if (this.reader) {
await this.reader.cancel();
await this.reader.releaseLock(); await this.reader.releaseLock();
this.reader = null;
} }
if (this.writer) { if (this.writer) {
await this.writer.releaseLock(); await this.writer.releaseLock();
this.writer = null;
} }
if (this.port) { if (this.port) {
await this.port.close(); await this.port.close();
this.port = null;
console.log('Serial port closed'); console.log('Serial port closed');
} }
} catch (error) {
console.error('Error during disconnect:', error);
}
} }
async readHoldingRegisters(slaveId, startAddress, quantity) { async readHoldingRegisters(slaveId, startAddress, quantity) {
@@ -161,10 +170,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; ?
} }
} }