writing modbus scan script

Hello im trying to write a simple script that will use modbus packet template to scan for adress range and get response from them, since my knowledge of jancy is so-so if you could point me in right direction or even a small example would be perfect. What i fail to understand is how to craft a packet using script to do so ( the loop part i understand )

Thank you very much and excuse me for being ignorant 🙂

If I understand correctly, you want to loop through all devices in an address range, and send a Modbus command to each one?

The sample below sends a ReadInputRegisters command; feel free to modify it accordingly.

import "../packets/ModbusRtu.jnc"

void main() {
	const int DeviceAddrFrom = 10;
	const int DeviceAddrTo = 20;
	const int ReadAddr = 30;

	for (int addr = DeviceAddrFrom; addr <= DeviceAddrTo; addr++) {
		ModbusRtuReadRequestPacket packet;
		packet.m_adu.m_deviceAddress = addr;
		packet.m_pdu.m_func = io.ModbusFunc.ReadInputRegisters;
		packet.m_pdu.m_address = ReadAddr;
		packet.m_pdu.m_count = 1;
		packet.updateChecksum();

		transmit(&packet, sizeof(packet));		
		sys.sleep(1000); // give the device some time to respond
	}	
}

@vladimir that is exactly what i wanted so i can check if i have devices online at all ( to be sure its not a cabling error ) i suppose i dont need the correct crc for this but if i do i guess ts just calling a function to recalculate crc on every loop instance. Thank you very much

@g0xran,

TBH, I think it's better to provide the correct checksum. Depending on the implementation, Modbus slaves may ignore commands with incorrect checksums and not respond to such packets at all.

In any case, the sample above fills in the checksum by calling ModbusRtuReadRequestPacket.updateChecksum(). The implementation is in scripts/packets/ModbusRtu.jnc in case you need it.

Also, I recommend attaching the Modbus Analyzer layer plugin when you work with Modbus devices -- this plugin will decode data streams and provide a human-readable representation of Modbus packets.

Sorry for super newbie question. I am able to send request for individual read & device address using the stock Modbus RTU script however I am running issues with running the script code provided as an example by @Vladimir above.

I have saved it as a new script and when I hit send in Transmit pane, it still sends the request for one read & device address and doesn't run the script.

UPDATE: I have figured out that there is separate tab for sending script messages next to settings 859bbd3d-e405-4fca-ae3e-b538d58cc005-image.png