var mc1_oper = {
	cmd:0,
	comm_port:"",
	comm_baud:"",
	comm_parity:-1,
	comm_stopbit:-1,
	mos_switch:0,
	file_crc : 0,
	heart_beat_sw:1,
	mc_high_voltage:85,
	mc_middle_voltage:50,
	mc_firmware_file:"",
	mc_boot_crcaddr_beg:0x1000,
	mc_boot_crcaddr_end:0x3C00,
	mc_boot_readaddr_beg:0x3C00,
	mc_boot_readlen:8,
	mc_boot_earseaddr_beg:0x1000,
	mc_boot_earseaddr_end:0x3C00,
	mc_boot_writeaddr:0x3C00,
	mc_boot_writevalue:"",
	mc_iic_setaddr:0x1000,
	mc_iic_read_len:8,
	mc_iic_writedata:"",
	mc_iic_mtp_v:0x14,
	mc_iic_mtp_ear_cfg:0x04,
	
}
var mc_1_qthandle = null;
var mc_1_excuedcmd = -1;
var mc_1_excued_rtv = -1;
function MC_1_Start_Comm()
{
	if( typeof(mc_1_qthandle) != "undefined"  && mc_1_qthandle != null )
	{
		mc_1_qthandle.SearchCommport();
	}
}
function MC_1_Open_CommPort(main_serial)
{
	
	mc1_oper.comm_port =main_serial.comm_port;
	mc1_oper.comm_baud =main_serial.comm_baud;
	mc1_oper.comm_parity =main_serial.comm_parity;
	mc1_oper.comm_stopbit = main_serial.comm_stopbit;
	console.log(mc1_oper);
	Main_Close_CommPort_Select();
	mc1_oper.cmd = 0xFF;
	var json_str = JSON.stringify(mc1_oper);
	if( typeof(mc_1_qthandle) != "undefined"  && mc_1_qthandle != null )
	{
		mc_1_qthandle.ExcueCmd(json_str);
	}
}

function mc1_cmd(cmd_v)
{
	mc1_oper.cmd = cmd_v;
	switch(cmd_v)
	{
		case 4: mc1_oper.mos_switch = 1;break;
		case 5: mc1_oper.mos_switch = 0;break;
		case 25:mc1_oper.heart_beat_sw ^= 0x01;break;
		default : break;
	}
	mc1_oper.mc_boot_crcaddr_beg =  parseInt($("#mc_boot_crcaddr_beg").val(), 16); ;
	mc1_oper.mc_boot_crcaddr_end = parseInt($("#mc_boot_crcaddr_end").val(),16);
	mc1_oper.mc_boot_readaddr_beg = parseInt($("#mc_boot_readaddr_beg").val(),16);
	mc1_oper.mc_boot_readlen =      parseInt($("#mc_boot_readlen").val(),10);
	mc1_oper.mc_boot_earseaddr_beg = parseInt($("#mc_boot_earseaddr_beg").val(),16);
	mc1_oper.mc_boot_earseaddr_end = parseInt($("#mc_boot_earseaddr_end").val(),16);
	mc1_oper.mc_boot_writeaddr =  parseInt($("#mc_boot_writeaddr").val(),16);
	mc1_oper.mc_boot_writevalue = $("#mc_boot_writevalue").val();
	mc1_oper.mc_firmware_file =  $("#mc_firmware_file").val();
	mc1_oper.mc_iic_read_len = parseInt($("#mc_iic_read_len").val(),10);
	mc1_oper.mc_iic_setaddr = parseInt($("#mc_iic_setaddr").val(),16);
	mc1_oper.mc_iic_writedata = $("#mc_iic_writedata").val();
	mc1_oper.mc_high_voltage =  parseInt($("#mc_high_voltage").val(),10);
	mc1_oper.mc_middle_voltage = parseInt($("#mc_middle_voltage").val(),10);
	mc1_oper.mc_iic_mtp_v = parseInt($("#mc_iic_mtp_v").val(),16);
	mc1_oper.mc_iic_mtp_ear_cfg =  parseInt($("#mc_iic_mtp_ear_cfg").val(),16);
	var json_str = JSON.stringify(mc1_oper);
	if( typeof(mc_1_qthandle) != "undefined"  && mc_1_qthandle != null )
	{
		mc_1_qthandle.ExcueCmd(json_str);
	}
}

function MC_ShowDef()
{
	$("#mc_boot_crcaddr_beg").val(Int2HexStr(mc1_oper.mc_boot_crcaddr_beg,"",0));
	$("#mc_boot_crcaddr_end").val(Int2HexStr(mc1_oper.mc_boot_crcaddr_end,"",0));
	$("#mc_boot_readaddr_beg").val(Int2HexStr(mc1_oper.mc_boot_readaddr_beg,"",0));
	$("#mc_boot_readlen").val(mc1_oper.mc_boot_readlen);
	$("#mc_boot_earseaddr_beg").val(Int2HexStr(mc1_oper.mc_boot_earseaddr_beg,"",0));
	$("#mc_boot_earseaddr_end").val(Int2HexStr(mc1_oper.mc_boot_earseaddr_end,"",0))
	$("#mc_boot_writeaddr").val(Int2HexStr(mc1_oper.mc_boot_writeaddr,"",0));
	$("#mc_boot_writevalue").val(mc1_oper.mc_boot_writevalue);
	$("#mc_firmware_file").val(mc1_oper.mc_firmware_file);
	$("#mc_iic_read_len").val(mc1_oper.mc_iic_read_len);
	$("#mc_iic_setaddr").val(Int2HexStr(mc1_oper.mc_iic_setaddr,"",0));
	$("#mc_iic_writedata").val(mc1_oper.mc_iic_writedata);
	$("#mc_high_voltage").val(mc1_oper.mc_high_voltage);
	$("#mc_middle_voltage").val(mc1_oper.mc_middle_voltage);
	$("#mc_iic_mtp_v").val(Int2HexStr(mc1_oper.mc_iic_mtp_v,"",0));
	$("#mc_iic_mtp_ear_cfg").val(Int2HexStr(mc1_oper.mc_iic_mtp_ear_cfg,"",0));
}

function MC_1ShowFirmWare(file)
{
	$("#mc_firmware_file").val(file);
	ShowCommMes("选择文件： "+file,MesgType.MESG_TYPE_INFO);
}
function MC_1Init()
{

	MC_ShowDef();

	if(typeof(qchannel) != "undefined" &&  qchannel != null )
	{
			if(typeof(mc_1_qthandle) != "undefined" &&  mc_1_qthandle != null )
			{
				console.log("MC_1Inited  OK ---");
			}else{
				mc_1_qthandle = qchannel.objects.mc1_qthandle;
				if((typeof(mc_1_qthandle) != "undefined") && (mc_1_qthandle != null) )
				{
					console.log("MC_1Init  OK ---");
					mc_1_qthandle.ShowCommMes.connect(function(mesg,type){
						ShowCommMes(mesg,type);
						
					});
					mc_1_qthandle.ShowCommport.connect(function(jsoninfo){
						Main_ShowCommport(jsoninfo);
					});
					
					mc_1_qthandle.ShowFirmWare.connect(function(jsoninfo){
						MC_1ShowFirmWare(jsoninfo);
					});
					mc_1_qthandle.Comm_Recive.connect(function(jsoninfo){
						MC_1_Comm_Recive(jsoninfo);
					});
					mc_1_qthandle.IICDownLoadFirmware.connect(function(file_size){
						MC_1_IICDownLoadFirmware(file_size);
					});
				
					 mc_1_qthandle.VBUSDownLoadFirmware.connect(function(file_size,crc){
						MC_1_VBUSDownLoadFirmware(file_size,crc);
					});		
				}
				
			} 
	}
}
//同步非阻塞延时
async function MC_1WaitCmdExcu( cmd,  time_out)
{
    if(time_out == 0)
        return 0;
    time_out = parseInt ( (time_out+19)/20);
    mc_1_excued_rtv = 0;
    while(time_out > 0)
    {
        if(mc_1_excuedcmd == cmd)
        {
            break;
        }
        await  TransSleep(20);
        time_out--;
    }
    if(mc_1_excued_rtv != 0)
    {
    	 ShowCommMes("命令错误退出",MesgType.MESG_TYPE_ERROR);
    	 return 2;
    }
    if(time_out > 0 )
    {
        return 0;
    }  
   else
    {
       ShowCommMes("通信超时",MesgType.MESG_TYPE_ERROR);
       return  1;

    }
}


var mc1_heartbeat_head = Str2Bytes("HBT");
function MC1_HeartBeat(frame_buf)
{
	var bus_volate = frame_buf[5] + (frame_buf[6] << 8);
	bus_volate = bus_volate / 10;
	bus_volate = bus_volate.toFixed(1);
	var bus_current = frame_buf[7] + (frame_buf[8] << 8)+(frame_buf[9] << 16)+(frame_buf[10] << 24);
	bus_current = bus_current/1000;
	bus_current = bus_current.toFixed(2);
	var bus_mvolate = frame_buf[11] + (frame_buf[12] << 8);
	bus_mvolate = bus_mvolate / 10;
	bus_mvolate = bus_mvolate.toFixed(1);
	var mes = "高电平电压 "+bus_volate+"V 中电平"+bus_mvolate+"V 总线电流  "+bus_current+"mA"
	ShowCommMes(mes,MesgType.MESG_TYPE_INFO);
}
function MC_1_Comm_Recive(json_str)
{
	var frame = JSON.parse(json_str);
	var frame_str = "Rx: "+ Bytes2Str(frame);
	ShowCommMes(frame_str,MesgType.MESG_TYPE_INFO);
	mc_1_excued_rtv = 0;
	mc_1_excuedcmd  = frame[4];
	//心跳包拦截
	if(frame[0] == mc1_heartbeat_head[0] &&frame[1] == mc1_heartbeat_head[1]&&frame[1] == mc1_heartbeat_head[1] )
	{
		MC1_HeartBeat(frame);
		return;
	}
	if(frame[2] == 0x42)
	{
		if(frame[6] != 0)
		{
			ShowCommMes("获取执行结果失败",MesgType.MESG_TYPE_ERROR);
			mc_1_excued_rtv = 1;
			BTErrorCount(1);
			return;
		}
		if(frame.length > 7)
		{
			if(frame[9] != 0)
			{
				ShowCommMes("命令执行失败",MesgType.MESG_TYPE_ERROR);
				mc_1_excued_rtv = 1;
				BTErrorCount(1);
				return;
			}
			if( 0 != MC_1_CRC8(frame,7,frame.length - 7))
			{
				ShowCommMes("数据校验失败",MesgType.MESG_TYPE_ERROR);
				mc_1_excued_rtv = 1;
				BTErrorCount(1);
				return;
			}
		}
		
		BTInfoCount(1);
		switch(frame[4])
		{
			case 1: ShowCommMes("全擦除执行成功",MesgType.MESG_TYPE_OK);break;
			case 2:	ShowCommMes("跳转执行成功",MesgType.MESG_TYPE_OK);break;
			case 4:	ShowCommMes("充电命令执行成功",MesgType.MESG_TYPE_OK);break;
			case 5:	ShowCommMes("放电命令执行成功",MesgType.MESG_TYPE_OK);break;
			case 8: ShowCommMes("CRC值: "+Bytes2Str(frame.slice(10,frame.length-1)),MesgType.MESG_TYPE_OK);break; 
			case 9: ShowCommMes("读取数据: "+Bytes2Str(frame.slice(10,frame.length-1)),MesgType.MESG_TYPE_OK);break; 
			case 10: ShowCommMes("擦除指定空间执行成功 ",MesgType.MESG_TYPE_OK);break; 
			case 11: ShowCommMes("写数据成功 ",MesgType.MESG_TYPE_OK);break;
			
		}
		
	}else if((frame[2] == 0x49)  && (frame.length > 8))
	{
		if(frame[8] != 0)
		{
			ShowCommMes("命令执行超时",MesgType.MESG_TYPE_ERROR);
			mc_1_excued_rtv = 1;
			return;
		}
		BTInfoCount(1);
		switch(frame[4])
		{
			case 12: ShowCommMes("MTP使能执行成功",MesgType.MESG_TYPE_OK);break;
			case 13: ShowCommMes("片擦执行成功",MesgType.MESG_TYPE_OK);break;
			case 14: ShowCommMes("块擦命令执行成功",MesgType.MESG_TYPE_OK);break;
			case 15: ShowCommMes("页擦命令执行成功",MesgType.MESG_TYPE_OK);break;
		}
		
	}else{
		ShowCommMes("错误命令",MesgType.MESG_TYPE_ERROR);
	}
}

async function MC_1_IICDownLoadFirmware(file_size)
{
	ShowCommMes("开始升级",MesgType.MESG_TYPE_INFO);
	if(file_size < 1)
	{
		return   ;
	}
	var count = 0;
	var begaddr = parseInt($("#mc_iic_setaddr").val(),16);
	var write_len = 0;
	var rtv = 0;
	while(count < file_size)
	{
		/*************设置MTP操作地址**********************/
		mc1_oper.cmd = 18;
		mc1_oper.mc_iic_setaddr = begaddr + count;
		var json_str = JSON.stringify(mc1_oper);
		if( typeof(mc_1_qthandle) != "undefined"  && mc_1_qthandle != null )
		{
			mc_1_qthandle.ExcueCmd(json_str);
		}
		mc_1_excuedcmd = -1;
		rtv = await  MC_1WaitCmdExcu(mc1_oper.cmd,1000);
		if(0 != rtv)
		{
			return;
		}
		ShowCommMes("设置操作地址: "+mc1_oper.mc_iic_setaddr.toString(16),MesgType.MESG_TYPE_INFO);
		if((count+192) < file_size)
		{
			write_len = 192;
		}else{
			write_len = file_size - count;
		}
		/************写缓存区中的固件数据******************/

		if( typeof(mc_1_qthandle) != "undefined"  && mc_1_qthandle != null )
		{
			mc_1_qthandle.IICDownLoadFirmwareFrame(20,count,write_len);
		}
		mc_1_excuedcmd = -1;
		rtv = await  MC_1WaitCmdExcu(20,1000);
		if(0 != rtv)
		{
			return;
		}
		count += write_len;
	}
}

async function MC_1_VBUSDownLoadFirmware(file_size,crc)
{
	
	if(file_size < 1)
	{
		return   ;
	}
	mc1_oper.file_crc = crc;
	var count = 0;
	var begaddr = parseInt($("#mc_boot_writeaddr").val(),16);
	var write_len = 0;
	var rtv = 0;
	var mes = "开始升级,文件大小 "+file_size;
	mes += "起始地址 "+ begaddr;
	ShowCommMes(mes,MesgType.MESG_TYPE_INFO);
	while(count < file_size)
	{
		if((count+192) < file_size)
		{
			write_len = 192;
		}else{
			write_len = file_size - count;
		}
		ShowCommMes("地址: "+begaddr.toString(16)+" 写入长度 "+ write_len,MesgType.MESG_TYPE_INFO);
		if( typeof(mc_1_qthandle) != "undefined"  && mc_1_qthandle != null )
		{
			mc_1_qthandle.VBUSDownLoadFirmwareFrame(11, begaddr, count,  write_len);
		}
		mc_1_excuedcmd = -1;
		rtv = await  MC_1WaitCmdExcu(11,1000);
		if(0 != rtv )
		{
			return;
		}
		count += write_len;
		begaddr+= write_len;
	}
	
}

function MC_1_CRC8(buf,offset,len)
{
	var crc = 0;
	var count = 0;
	while(count < len)
	{
		crc ^= (buf[offset++] & 0xFF);
		count++;
		crc &= 0xFF;
	}
	return crc;
}
