import usb2canfd;
import thread.command;
import win.timer;
//初始化CAN句柄对象
CANHw = usb2canfd.USB2CANHW();
CANHw.LoadDll();

DiagReqID = 0x732;//0x18dadff1; 
DiagRespID = 0x7B2;//0x18daf1df; 
DiagGloableID = 0x7DF;//0x18DB33F1;
stopflag = 0;

write2Etest = function(did){
	select(did) {
		case 0xF010 {
			var data = {1,2,3,4, 0,0,0,0, 0,0,0,0, 0,0,0,0,};
			FuncReq2E(did,data);
		}
		case 0xF101 {
			var data = {1,2,3,4, 0,0,0,0, };
			FuncReq2E(did,data);
		}
	}
}

//注册一个消息钩子函数
FuncLoopMsg = function(msg){
	select(msg.message) {
		case 100 {//刷新硬件
			FuncFreshHw();
		}
		case 101 {//连接硬件
			//console.log("msg.wParam = " + msg.wParam);
			//console.log("msg.lParam = " + msg.lParam);
			FuncConnect(msg.wParam,msg.lParam);
		}
		case 102 {//开始boot
			FuncStartBoot();
		}
		case 103 {//停止boot
			FuncStopBoot();
		}
		case 104 {//打开s19文件

			FuncDisplay("打开烧写文件");
			var ret = FuncOpenS19File(1);
			if(ret != null){
				thread.command.$ShowPath(ret);
				var crc32 = FuncGetFlashCRC(1);
				FuncDisplay("CRC = " ++ string.format("%X",crc32));
			}
			
			
		}
		case 105 {//停止boot
			thread.stop(0);
		}
		case 106 {//导出
			exportbootflag();
		}
		case 110 {//readDID
			FuncReadDID(msg.wParam);
		}
		case 111 {
			FuncReq10(msg.wParam,msg.lParam);
		}
		case 112 {
			FuncReq28(msg.wParam);
		}
		case 113 {
			FuncReq85(msg.wParam);
		}
		case 114 {
			FuncReq27(msg.wParam);
		}
		case 115 {
			write2Etest(msg.wParam)
		}
		case 120 {
			win.quitMessage()
		}
		case 121 {
			SetDiagID(msg.wParam,msg.lParam);
		}
		else {

		}
	}
}

SetDiagID = function(reqid,respid){
	DiagReqID = reqid;//0x18dadff1; 
	DiagRespID = respid;//0x18daf1df; 
	var idstr = string.format("req=0x%x,resp=0x%x",DiagReqID,DiagRespID);
	FuncDisplay(idstr);
}



var delay_const = 100000;
DelayTest = function(){
	import time.performance;
	var tk = time.performance.tick();
	for(i=1;1000000;1)
	{
	}
	var tk2 = time.performance.tick();
	tk2 = tk2 - tk;
	delay_const = math.ceil(1000000*(1/tk2));
	FuncDisplay(delay_const);
	//console.log(delay_const);
}



FuncFreshHw = function(){
	var hwnum = CANHw.FlashHw();
	if(hwnum == 0){
		//mainForm.cbbDev.text = "未找到硬件"
	}
	else {
		FuncDisplay("找到硬件")
	}
}

FuncConnect = function(dev,chn){
	var canfd = (chn&0x80)==0x80?true:false;
	var ret = CANHw.OpenDevice(dev,chn&0x7f,canfd);
	if(ret == 0){
		FuncDisplay("连接成功");
		thread.command.$Connected();
	}
	else {
		FuncDisplay("连接失败");
	}
}

FuncDisplay = function(str){
	thread.command.$Display(str);//"线程" +
}


loadcodex("\user\Diag10code.aardio");
loadcodex("\user\Diag11code.aardio");
loadcodex("\user\Diag22code.aardio");
loadcodex("\user\Diag27code.aardio");
loadcodex("\user\Diag2Ecode.aardio");
loadcodex("\user\Diag28code.aardio");
loadcodex("\user\Diag31code.aardio");
loadcodex("\user\Diag34code.aardio");
loadcodex("\user\Diag36code.aardio");
loadcodex("\user\Diag37code.aardio");
loadcodex("\user\Diag7Fcode.aardio");
loadcodex("\user\Diag85code.aardio");

loadcodex("\user\DiagBootcode.aardio");
loadcodex("\user\S19Decode.aardio");


RespState = 0;

FuncDiagPro = function(diagmsg){

	select(diagmsg.sid) {
		case 0x50 {
			FuncDiag10Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x62 {
			FuncDiag22Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x67 {
			FuncDiag27Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x74 {
			FuncDiag34Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x71 {
			FuncDiag31Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x76 {
			FuncDiag36Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x68 {
			FuncDiag28Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0xC5 {
			FuncDiag85Pro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x7F {
			FuncDiag7FPro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		case 0x6E {
			FuncDiag2EPro(table.slice(diagmsg.data,1,diagmsg.len))
		}
		else {
		}
	}
	RespState = diagmsg.sid;
}







FuncStartBoot = function(){
	FuncInitBootState();
	boottimer.enable();
	
	FuncDisplay("开始刷写");
	stopflag = 0;
}

var delay = function(w){
	var delay_time = w*delay_const;
	for(i=1;delay_time;1)
	{
	}

}

var PackNext = 0x21;
var Packdata = {};
var PackID = 0;
var FuncSendPackage = function(){
	while(#Packdata > 0)
	{
		//sleep(1);
		delay(1);
		var data = {PackNext,0xCC,0xCC,0xCC,0xCC,0xCC,0xCC,0xCC};
		var max = #Packdata > 7 ? 7 : #Packdata;
		for(i=1;max;1){
			data[i+1] = table.remove(Packdata);
		}
		//sleep(0.3);
		CANHw.SendMsg(PackID,data);
		
		PackNext += 1;
		if(PackNext > 0x2f){
			PackNext = 0x20;
		}
	}
	
}
FuncPushPackage = function(ID,data){
	PackNext = 0x21;
	Packdata = data;
	PackID = ID;
}



boottimer = win.timer(,10);
boottimer.onTimer = function(){
	if(CANHw.isConnected() == false){
		boottimer.disable();
		return; 
	}
	FuncBootSeq();
}


timer1 = win.timer(,1);
diagresp = {}
timer1.onTimer = function(){	
	if(CANHw.isConnected() == false){
		return; 
	}
	ret = CANHw.GetMsg();
	
	for(i=1;#ret;1){
		//console.log("id = " + tostring(ret[i].id))
		if(ret[i].id & 0x7FFFFFFF ==  DiagRespID){
			if(ret[i].data[1] == 0x10){//首帧
				var data = {0x30,0x00,0x14,0x00,0,0,0,0};
				CANHw.SendMsg(DiagReqID,data);
				diagresp["sid"] = ret[i].data[3];
				diagresp["len"] = ret[i].data[2]-1;
				diagresp["data"] = {};
				diagresp["next"] = 0x21;
				table.append(diagresp["data"],table.slice(ret[i].data,4));
			}
			elseif(ret[i].data[1] <= 0x07){//单帧
				//console.dumpJson()
				diagresp["sid"] = ret[i].data[2];
				diagresp["len"] = ret[i].data[1]-1;
				diagresp["data"] = table.slice(ret[i].data,3);
				FuncDiagPro(diagresp);
			}
			elseif(ret[i].data[1] >= 0x21 && ret[i].data[1] <= 0x2f){
				if(ret[i].data[1] == diagresp["next"]){//多帧
					diagresp["next"] += 1;
					if(diagresp["next"] >= 0x2F){
						diagresp["next"] = 0x20;
					}
					table.append(diagresp["data"],table.slice(ret[i].data,2));
					if(#diagresp["data"] >= diagresp["len"]){
						FuncDiagPro(diagresp);
					}
				}
			}
			elseif(ret[i].data[1] == 0x30){//
				FuncSendPackage();
			}	
		}
		else {
			//console.varDump(ret[i].id);
			//显示报文
		}
		
	}
	
}

timer1.enable();
FuncDisplay("正在运行");


DelayTest();

