#!/usr/bin/perl
use 5.010;

# ./write_rom.pl "directory" "modbus-address" - write banks to the device

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


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 -o700 -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 -o700 -s2 $port -a$addr -t0x05 -r$reg 1`;
	sleep (2);
	print "Writing from rom_$j.ir... ";

	open(buff,"./$dir/rom_$j.ir");

	my (@buff)=split('\s', <buff>);

	foreach $k (2000, 2121, 2242, 2363) {

		$data="@buff[$k-2000..$k-2000+120]";
		`modbus_client --debug -mrtu -b$spd -pnone -s2 $port -a$addr -t0x10 -r$k -c121 $data`;

	}

	$k=2484;
	$data="@buff[$k-2000..$k-2000+22]";
	`modbus_client --debug -mrtu -b$spd -pnone -s2 $port -a$addr -t0x10 -r$k -c23 $data`;

	close(buff);

	print "Finishing... ";
	`modbus_client --debug -mrtu -b$spd -pnone -o700 -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();
