#!/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();
$cl->set_debug();



print "\nFirst 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 "\n\nNow 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 "\n\nGreat, we're ready to calibrate!\n";
	print "Press enter when you're ready to continue>\n";

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

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

	print "\n\nnow I'm going to try each pwm setting, and record the voltage\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_d2};
		

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

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

			$rxvolts = $rvolts * 1000;

		
			if($dvolts != $last_dvolts) {

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

	}


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

	print "Solving for C/B/M: ";

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

	print "Done\n";

	$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 VOLTS B: $best_b C: $best_c M: $best_m E: $best_error MC: $max_count\n";
	close(LOG);
	

	while($cl->write_eeprom_int_verify(0x1FD0,$best_m)) {}
	while($cl->write_eeprom_int_verify(0x1FD2,$best_c)) {}
	while($cl->write_eeprom_int_verify(0x1FD4,$best_b)) {}

	print "Okay! Voltage calibrated!\n";
		

	$cl->force_on_charger(0,0);





