#!/usr/bin/perl

use charger_lib;


$cl = charger_lib->new(0x0F);


$cl->set_unit(shift || 1);
$cl->set_baud(shift || 9600);
$cl->set_delay(0.05);
$cl->open_bus();


print "First I'm going to enable manual charger control\n";

while($cl->write_with_verify(0x1FF3,42)) {}
while($cl->write_with_verify(0x1FE8,0)) {}; # disable ALL errnos for cal

	print "Now I'm going to turn on the charger at a very low voltage\n";
	print "Please ensure that the charger is connected to a high voltage src\n";

	die "Couldn't reset charger" if($cl->force_on_charger($pwm,5000));

	print "Now I'd like you to disconnect the charger from the battery,\n";
	print "Carefully hook the RS232 voltmeter 20A jack up to the battery\n";
	print "Positive, and the -/COM jack up to the BatMod positive\n";
	print "Set the meter knob in the AMPS position\n";
	print "Press enter when you're ready to continue>\n";

	$junk = <>;
	
	$avg = $cl->read_eeprom(0x1FF4);

	$cl->write_eeprom(0x1FF4,2);

	print "now I'm going to try each pwm setting, and record the amperages\n";

	print "This will take about 5 minutes, please wait:";

	@x_array = ();
	@y_array = ();


	for($pwm = 0; $pwm<255; $pwm+=25) {
		sleep(1);
		$cl->force_on_charger($pwm,5000);

		sleep(5); # wait for the voltage to stablelize

		if($cl->show_inputs()) {
			#timeout occured
		} else {
	
			$last_dvolts = $dvolts;
			$dvolts = $cl->{read_d3};

		#	$realvolts = `./poll`;
			$realvolts = $cl->vm_read_data();

			($rvolts) = $realvolts =~ /\D*(\d*.\d*)\D*/;

			$rxvolts = ($rvolts * 1000);
				
			# might need to be reset for optimas?

		
			if($dvolts != $last_dvolts) {

				push(@x_array,$dvolts); 
				push(@y_array,$rxvolts);
				print "$dvolts -> $rxvolts\n";
			}
		}

	}


	$cl->write_eeprom(0x1FF4, $avg);
	
	$href = $cl->solve("x_array" => \@x_array,
			   "y_array" => \@y_array);

	$cl->print_mcb_error(%{$href});

	$best_c = $href->{best_c};
	$best_b = $href->{best_b};
	$best_m = $href->{best_m};
	$best_error = $href->{best_error};
	$max_count = $href->{max_count};
	
	print "B: $best_b C: $best_c M: $best_m error: $best_error \n";
	print "max count: $max_count\n";

	open(LOG,">>calresults.log");
	$ltime = localtime();
	print LOG "$ltime AMPS B: $best_b C: $best_c M: $best_m E: $best_error MC: $max_count\n";
	close(LOG);
	

	while($cl->write_eeprom_int(0x1FD6,$best_m)) {}
	while($cl->write_eeprom_int(0x1FD8,$best_c)) {}
	while($cl->write_eeprom_int(0x1FDA,$best_b)) {}

	print "Okay! Amperage calibrated!\n";
		

	$cl->force_on_charger(0,0);





