#!/usr/bin/perl
use 5.010;

# ./get_rom.pl "directory" "modbus-address" - read banks from the device

$dir=$ARGV[0];
$qnt=$ARGV[1] - 1;
$port=$ARGV[2];
$spd=$ARGV[3];
$addr=$ARGV[4];


`mkdir $dir`;

print "Stopping wb-mqtt-serial...\n";
`systemctl stop wb-mqtt-serial`;

print "Closing command editing (just in case)...\n";
foreach $i (0..$qnt) {

	$reg=5200 + $i;
	`modbus_client --debug -mrtu -b$spd -pnone  -o1200 -s2 $port -a$addr -t0x05 -r$reg 0`;
	sleep(2);

}


foreach $i (0..$qnt) {

	$reg=5200 + $i;
	$j=$i+1;
	print "Command $j. Starting... ";
	`modbus_client --debug -mrtu -b$spd -pnone -o1200 -s2 $port -a$addr -t0x05 -r$reg 1`;
	sleep (2);
	print "Writing to rom_$j.ir... ";

	my $command="";
	foreach $k (2000, 2125, 2250, 2375) {
		$commandpart = qq (echo `modbus_client --debug -mrtu -b$spd -pnone -s2 $port -a$addr -t0x03 -r$k -c125 | grep Data | sed -e 's/Data://' -e 's/s//g'`);
		$command.=`$commandpart`;

	}
	$commandend = qq (echo `modbus_client --debug -mrtu -b$spd -pnone -s2 $port -a$addr -t0x03 -r2500 -c9 | grep Data | sed -e 's/Data://' -e 's/s//g'`);
	$command.=`$commandend`;

	$command=~s/\n/ /g;
	@command=split(' ',$command);
	@deccommand = map hex, @command;
	my $result = join(' ',@deccommand);

	open($file, ">", "./$dir/rom_$j.ir");
	print $file $result;
	close $file;

	print "Finishing... ";
	`modbus_client --debug -mrtu -b$spd -pnone -o1200 -s2 $port -a$addr -t0x05 -r$reg 0`;
	sleep (2);
	print "Done.\n";
}

print "Starting wb-mqtt-serial...\n";
`systemctl start wb-mqtt-serial`;

exit();
