Skip to content

How to catch tcp transport errors #74

@boatbodger

Description

@boatbodger

I am writing a client which needs to recover from temporary inability to connect to the modbus server the bare bones of what I'm trying to do is as follows

// Variables into which the data read from the MODBUS is put, available for forwarding to any web consumer
var meterVolts
const U16_METER_V = 33128		//Register Volts at meter in tenths of a Volt
//****************************************************************
//
//       MODBUS Handler etc (functions followed by some inline code)
//
//****************************************************************

const modbus = require("modbus-stream");
const util = require('util')

function getValuesPromise(connection,req){
	return new Promise ((resolve, reject) => {
		if (connection == null)
			reject('Connection found to be closed')
		connection.readInputRegisters(req,(err,res) => {
			if (err)
				reject(err)
			else 
				resolve(res.response.data)
		})
	})
}

async function getInverterInfo(connection){

	connection.transport.on("error", function (err){
			console.log("transport error",err)
			//raise reconnect request event
			return
	})
	connection.transport.on("close", function(err){
		console.log("transport close",err )
		return
	})

	//Meter voltage as a way to test manipulation of a U16 result
	meterVolts =  await getValuesPromise(connection,{address:U16_METER_V, quantity: 1, extra: { unitId: 1}}).catch(err => {console.log(err)})

	setTimeout(() => {getInverterInfo(connection)},10000)	//Run again after ten seconds
}


	modbus.tcp.connect(8899,"192.168.100.242",{debug: null}, (err, connection)=> {
		if (err != null){
			console.log('could not connect')
			console.log(err)
		};

		getInverterInfo(connection)	//This kicks a repeat timer.

	});
`

However, I'm finding that if I reset the server during the 'wait' time, instead of cleanly catching either a "close" or an "error" event, I see the following in my console:

Error: GatewayTargetDeviceFailedToRespond
    at exports.error (/home/solar/node_modules/modbus-pdu/lib/Exception.js:24:13)
    at Timeout._onTimeout (/home/solar/node_modules/modbus-stream/lib/transport/transport.js:93:33)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  code: 11
}

Can anyone help me understand what I'm doing wrong?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions