package pscs.connect;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.awt.Frame;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
//import java.util.TooManyListenersException;

import javax.swing.JOptionPane;
import javax.swing.JScrollBar;

import pscs.App;
import pscs._FrmPSCS;
import pscs.PairVC;
import pscs.PairVCS;
import pscs.PanLCD;
import pscs.func;
import pscs.bean.BeanConnectInfo;
import pscs.enums.EnmBeanConnectType;
import pscs.enums.EnmConnType;
import pscs.enums.EnmSerial;
import pscs.powerSupply.PowerSupply;
import pscs.publics.LOG;
import pscs.publics.RunETP;

/** ͨ RS232/RS485/TCP/UDP **/
public class ConnectRxtx implements SerialPortEventListener {
	private Object[][] dataMemory = null;
	private BeanConnectInfo connInfo;
	public PowerSupply ps = new PowerSupply();
	private SerialPort serialPort;
	private InputStream inputStream;
	private InputStream inputStreamTCP;
	private OutputStream outputStream;
	private OutputStream outputStreamTCP;
	private boolean use=false;
	private boolean ConnectOK = false;
	private boolean isExit = false;
	public boolean runCmdSetVCO;
	public boolean runCmdSetVC_old;
	public PairVC oldSettingVC;
	public boolean oldOutput;
	public boolean isSetUWL;
	public boolean isSaveFuncABC = false;
	public boolean isSaveProgram = false;
	public boolean isReadProgram;
	public boolean isSaveProgramToPS = false;	//sdp
	public boolean isSetRangeChannel = false;
	public boolean isSaveTransitTime = false;
	public boolean isSetABC_Select = false;
	public boolean isRunWFG = false;
	public boolean isChangeFuncABC = false;
	public int cycleI = 0, cycleE = 0;
	private int Sampling = 3;
	public String descI = "", descE = "", descM = "", descL = "";
	
	public boolean isRunITP;
	public boolean isCmdTest = false;
	public boolean isSetMemoryIdx = false;
	public boolean isReadM = false;
	public boolean isSaveM = false;
	public Boolean[] isChangeIpmRowArr = new Boolean[]{false,false,false,false,false,false,false,false,false,false};//[0-9(1-9)]  SDP2xxx ĸģĸ
	public boolean isRunerAutoAccess = true;
	public boolean runCmdGettSettingVolt = true;
	public boolean isFault = false;		//SDP2xxx
	private ArrayList<String> Portlist = new ArrayList<String>();
	private DatagramSocket clientUDP = null;
	private Socket clientTCP = null;
	public CmdIntf cmdSet = new CmdSetEmpty();	//command set
	
	private String remoteIP;
	private Integer remotePort;
	private String commData = "";
	
	public LOG logN = new LOG();
	private _FrmPSCS pscs = _FrmPSCS.getIt();
	private App app = App.getIt();
	
	public PanLCD lcd = null;
	
	public RunETP runETP = new RunETP(this);
	private int idxTmp = 99;
	//private CommPortIdentifier portId;
	public boolean isTableItpValidData = false;
	public boolean isTableEtpValidData = false;
	public boolean isRunningTableITP = false;
	public boolean isRunningTableETP = false;
	public boolean isRunningTableWFG = false;
	public boolean isChkOutputOff = false;
	
	public void initChangeRowArr() {
		for(int i=0; i<isChangeIpmRowArr.length; i++) isChangeIpmRowArr[i] = false;
	}
	
	public ConnectRxtx(BeanConnectInfo connInfo){
		this.connInfo = connInfo;
		setConnectionType();
		lcd = new PanLCD(this);
		new Thread(new Runnable() {
			public void run() { running(); }
		}).start();
	}
	
	public void _newComPortConnection(int idx){	//if model==null --> auto
		try {
			System.out.println("_newComPortConnection....connName:"+connInfo.getName());
			String strSerial = null;
			strSerial = _getSerialModel();
			if(strSerial==null || strSerial.length()==0){
				if(isCurrConn()){
					ps.setDisplay(null);//pscs.lcd.setData(null);
					ps.setDisplay(null);
					return;
				}
			}else{
				if(strSerial.startsWith("3")) strSerial = "HCS" + strSerial;
				String mod = strSerial.replace("OK", "");
				connInfo.setModel(mod);
				ps.setModel(mod);
			}
			if(connInfo==null) return;
//			System.out.println(idx+"--"+111);
			pscs.cpts.labStbUnits.setVisible(false);
//			System.out.println(idx+"--"+222);

			pscs.ps_setMachines(1);
//			System.out.println(idx+"--"+333);
		    ps.setMaxPower(10000);
//		    System.out.println(idx+"--"+444);
			if(strSerial.indexOf("OK")>0){
//				System.out.println(idx+"--"+555);


				if(connInfo.getSerial()==EnmSerial.HCS2){			//==================== [HCS OLD SERIES]
					cmdSet = new CmdSetHCS2xxx(this);
				    ps.setVoltFormatDisplay(10);//strModel
					if("3102/3104/3204".indexOf(ps.getModel())>=0){ // 20130407 cancel the 3304 to 0.0A
						ps.setCurrFormatDisplay(100);
					}else{ 
						ps.setCurrFormatDisplay(10);
					}
					ps.setVoltFormatSetting(10);
					ps.setCurrFormatSetting(10);
					//ps.setModel(cmdSet.getModel().replace("OK", ""));
					ps.setMax(cmdSet.getMax());
					ps.setSetting(cmdSet.getSetting());
					ps.setOutput(cmdSet.getOutputIsOn());
				}else if(connInfo.getSerial()==EnmSerial.HCS3){		//==================== [HCS NEW(MCU3.0) SERIES]
					cmdSet = new CmdSetHCS3xxx(this);
					ps.setVoltFormatDisplay(10);
					ps.setVoltFormatSetting(10);
					if(ps.getModel()!=null && "3102/3104/3204".indexOf(ps.getModel().replace("HCS", ""))>=0){ // 20130407 cancel the 3304 to 0.0A
						ps.setCurrFormatDisplay(100);
						ps.setCurrFormatSetting(100);
					}else{ 
						ps.setCurrFormatDisplay(10);
						ps.setCurrFormatSetting(10);
					}
					//ps.setModel(cmdSet.getModel().replace("OK", ""));	//HCS3400   ִкHCS-3400 Ҫ
					ps.setMax(cmdSet.getMax());
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					ps.setDataIPM(cmdSet.getPresetMemory());
					ps.setSetting(cmdSet.getSetting());
					ps.setOutput(cmdSet.getOutputIsOn());
				}else if(connInfo.getSerial()==EnmSerial.KPS){		//==================== [KPS] 
					pscs.panWFG.panTopRunCycle.setVisible(true);	//SSP9xxx 
					cmdSet = new CmdSetKpsNep(this);	//manson,sdp-3636,0,1.1.0OK
					ps.setVoltFormatDisplay(100);
					ps.setCurrFormatDisplay(100);
					ps.setVoltFormatSetting(100);
					ps.setCurrFormatSetting(100);
					ps.setMax(cmdSet.getMax());
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					ps.setSetting(cmdSet.getSetting());
					ps.setOutput(cmdSet.getOutputIsOn());
					ps.setDataITP(null);	//without ITP
					cmdSet.getProgram();	//ps.setDataIPM()
					ps.setDataIPM(cmdSet.getPresetMemory());
				}else if(connInfo.getSerial()==EnmSerial.NEP){		//==================== [NEP] 
					pscs.panWFG.panTopRunCycle.setVisible(true);	//SSP9xxx 
					cmdSet = new CmdSetKpsNep(this);	//manson,sdp-3636,0,1.1.0OK
					ps.setVoltFormatDisplay(100);
					ps.setCurrFormatDisplay(100);
					ps.setVoltFormatSetting(100);
					ps.setCurrFormatSetting(100);
					ps.setMax(cmdSet.getMax());
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					ps.setSetting(cmdSet.getSetting());
					ps.setOutput(cmdSet.getOutputIsOn());
					ps.setDataITP(null);	//without ITP
					cmdSet.getProgram();	//ps.setDataIPM()
					ps.setDataIPM(cmdSet.getPresetMemory());
				}else if(connInfo.getSerial()==EnmSerial.NTP){		//==================== [NTP] 
					cmdSet = new CmdSetNTP6xxx(this);
					ps.setVoltFormatDisplay(100);
					ps.setVoltFormatSetting(100);
					ps.setCurrFormatDisplay(1000);
					ps.setCurrFormatSetting(1000);
					//ps.setModel(cmdSet.getModel().replace("OK", ""));
					ps.setMax(cmdSet.getMax());
					ps.setUwl(cmdSet.getMax());	//NTP without OVP/OCP
					ps.setSetting(cmdSet.getSetting());
					ps.setOutput(cmdSet.getOutputIsOn());
				}else if(connInfo.getSerial()==EnmSerial.SDP2new){	//==================== [SDP2 NEW SERIES] 
					cmdSet = new CmdSetSDP2new(this); 
				    ps.setVoltFormatDisplay(100);//strModel
					ps.setCurrFormatDisplay(connInfo.getSerial()==EnmSerial.SDP2new?1000:100);
					ps.setVoltFormatSetting(10);
					ps.setCurrFormatSetting(100);
					//ps.setModel(strSerial.replace("OK", ""));	//SDP2603OK -> SDP2603
					ps.setMax(cmdSet.getMax());
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					ps.setSetting(cmdSet.getSetting());
					ps.setDataITP(getProgram());
					ps.setDataIPM(cmdSet.getPresetMemory());
					ps.setMemoryIdx(((CmdSetSDP2new)cmdSet).getMemoryIndex());
				}else if(connInfo.getSerial()==EnmSerial.SDP2old){	//==================== [SDP2 OLD SERIES] 
					cmdSet = new CmdSetSDP2old(this); 
				    ps.setVoltFormatDisplay(100);//strModel
					ps.setCurrFormatDisplay(connInfo.getSerial()==EnmSerial.SDP2old?1000:100);
					ps.setVoltFormatSetting(10);
					ps.setCurrFormatSetting(100);
					//ps.setModel(strSerial.replace("OK", ""));	//SDP2603OK -> SDP2603
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					//ps.setSetting(cmdSet.getSetting());
					ps.setDataITP(getProgram());
					ps.setDataIPM(cmdSet.getPresetMemory());
					ps.setOutput(cmdSet.getOutputIsOn());
					cmdSet.setKeyBoard(true);
				}else if(connInfo.getSerial()==EnmSerial.SDP3){		//==================== [NEW SDP SERIES] Port:?
					cmdSet = new CmdSetSDP3xxx(this);	//manson,sdp-3636,0,1.1.0OK
					ps.setVoltFormatDisplay(100);
					ps.setCurrFormatDisplay(100);
					ps.setVoltFormatSetting(100);
					ps.setCurrFormatSetting(100);
					ps.setMax(cmdSet.getMax());
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					ps.setSetting(cmdSet.getSetting());
					ps.setOutput(cmdSet.getOutputIsOn());
					ps.setDataIPM(cmdSet.getPresetMemory());
				}else if(connInfo.getSerial()==EnmSerial.SSP8080){	//==================== [SSP SERIES] SSP8080 /** is SSP8080 **/
					pscs.panWFG.panTopRunCycle.setVisible(false);	//SSP8080 û
					cmdSet = new CmdSetSSP8xxx(this);
					ps.setVoltFormatDisplay(100);
					ps.setCurrFormatDisplay(1000);
					ps.setVoltFormatSetting(100);
					ps.setCurrFormatSetting(1000);
					//ps.setModel(cmdSet.getModel().replace("OK", ""));
					
					String strAll = cmdSet.getAll(); 
					if(strAll.indexOf("OK")>=56){	//ssp8080 is 56
						//A/B/Cѡ
	//						int abc = func.getInt(strAll.substring(0, 1));
						int cha = func.getInt(strAll.substring(1, 2));
						ps.setChannel(cha);
					
						if(ps.getChannel()==0){
							ps.setMax(new PairVC(16, 5));
						}else if(ps.getChannel()==1){
							ps.setMax(new PairVC(27, 3));
						}else{
							ps.setMax(new PairVC(36, 2.2f));
						}
					}
					
					ps.setSetting(cmdSet.getSetting());
					ps.setOutput(cmdSet.getOutputIsOn());
				}else if(connInfo.getSerial()==EnmSerial.SSP8XXX){	//==================== [SSP SERIES] SSP8xxx /** SSP8160/8162/8320/8322 **/
					pscs.panWFG.panTopRunCycle.setVisible(false);	//SSP8xxx û
					cmdSet = new CmdSetSSP8xxx(this);
					ps.setVoltFormatDisplay(100);
					ps.setCurrFormatDisplay(100);
					ps.setVoltFormatSetting(100);
					ps.setCurrFormatSetting(100);
					//ps.setModel(cmdSet.getModel().replace("OK", ""));
					ps.setMax(cmdSet.getMax());
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					ps.setSetting(cmdSet.getSetting());	//and set ABC-select
					ps.setOutput(cmdSet.getOutputIsOn());
				}else if(connInfo.getSerial()==EnmSerial.SSP9){	//==================== [SSP SERIES] SSP9xxx /** SSP9081 **/	
					pscs.panWFG.panTopRunCycle.setVisible(true);	//SSP9xxx 
					cmdSet = new CmdSetSSP9xxx(this);
					ps.setVoltFormatDisplay(100);
					ps.setCurrFormatDisplay(1000);
					ps.setVoltFormatSetting(100);
					ps.setCurrFormatSetting(1000);
					//ps.setModel(cmdSet.getModel().replace("OK", ""));
					String strAll = cmdSet.getAll();
					//SSP9080;V1.0;0;0;3640;5100;0;0;0;1502;5100;180;1000;330;1000;0;0;0;10;
					//100;1; 300;1; 100;1; 300;1; 100;1;  300;1; 100;1; 300;1; 100;1; 300;0; 100;1; OK //length=42
					//SSP9081; V1.0; 1;		0;	  3640; 5100; 1002; 0;    0;       1000;600; 180;1000; 330;1000; 0;0;     0;10;100;1;300;1;100;1;300;1;100;1;300;1;100;1;300;1;100;1;300;1;100;1;OK
					//model;    ver;  On/Off;	CCCV; GUVL; GUCL; OutV: OutC; Channel;           P1V;P1C;  P2V;P2C;  P3V;P3C;
	//					panWFG.setCpts();
					if(strAll.indexOf("OK")>20){	//Ƕ
						//A/B/Cѡ
						String[] arr = strAll.split(";");
	//						float v = 0, c = 0;
						if(arr.length>=41){
	//							int abc = func.getInt(strAll.substring(0, 1));
	//							pssetABCSelected(abc);
							int cha = func.getInt(strAll.substring(1, 2));
							ps.setChannel(cha);
	
						}
					}
					ps.setMax(cmdSet.getMax());
					ps.setUwl(new PairVC(cmdSet.getVoltageUppeLimit(), cmdSet.getCurrentUppeLimit()));
					ps.setSetting(cmdSet.getSetting());
					ps.setDataIPM(cmdSet.getPresetMemory());
				}else {
					cmdSet = new CmdSetEmpty();
				}
				pscs.panMultiple.refreshCptsLabInfo();
				pscs.setCpts(this);
				pscs.setTitle(this);
				ConnectOK = true;
				pscs.setLeftTabIndexPageIO();
				initLogN();
				
				/* new connect refresh LCD */
				PairVCS vcs = cmdSet.getVoltageAndCurrentAndStatus();
				if(vcs!=null){
					ps.setDisplay(vcs);
					lcd.repaint();
					if(isCurrConn()) pscs.lcd.repaint();
				}
			}
			
			logN.startTime = (new Date()).getTime();
			logN.startDateTime = new Date();
			logN.index = 0;
			isRunerAutoAccess = true;
			
			pscs.cpts.labStbModel.setText(" " + pscs.lang.getString("Lang_Model") + ": " + (ps.getModel()==null ? " " : app.clientModelMap.get(ps.getModel()) + " "));
			isChangeFuncABC = false;
		}catch(NullPointerException e) {}
	}
	
	/**
	 * ȷõϵǷȷȷݲͬϵвòָͬ
	 * @return
	 */
	public String _getSerialModel(){ //190527 ȡͺе"-"
		String readStr = "";
		try {Thread.sleep(10);} catch (InterruptedException e) {}
		if(connInfo==null) return "";
		
		//SDP.old ר 3.1A/B ============================================
		if(app.isOldSDP) {	//ָǾSDP
			readStr = send("GMAX"+connInfo.getRs485Str());
			if(readStr.indexOf("OK")>0) {
				PairVC vc = new PairVC();
				vc.setVolt(func.getFloat(readStr.substring(0,3))/10);
				String c = readStr.substring(3,6);
				vc.setCurr(func.getFloat(c)/100);
				ps.setMax(vc);
				int v = func.getInt(readStr.replace("OK", ""));
				if(v<402502) { return "SDP2210OOK"; }else if(v==402502) { return "SDP2405OOK"; }else { return "SDP2603OOK"; }	//201999OK	//402502OK
			}
		}
		//SDP.old end ============================================
		//if(this.ps.getModel()!=null && this.ps.getModel().length()>0) System.out.println((12/0));;
		//System.out.println(this.ps.getModel());
		readStr = send("GMOD"+(connInfo.getBeanConnectType()==EnmBeanConnectType.RS485? connInfo.getRs485Str(): ""));
		if(readStr.indexOf("OK")<=0) readStr = send("GMOD"+connInfo.getRs485Str());
		if(readStr.indexOf("OK")>0){	//8160OK/SSP-9081OK
			if(readStr.startsWith("8"))	//SSP8xxx	=========== OK  
				return "SSP" + readStr;
			else if(readStr.startsWith("6"))	//KPS6xxx	=========== OK  
				return "KPS" + readStr;
			else if(readStr.startsWith("NTP5"))
				return "NTP" + readStr.substring(3);
			else if(readStr.startsWith("SDP"))
				return "SDP" + readStr.substring(3);
			else
				return readStr.replace("-", "");			//HCS3/SSP9081	======= OK
		}
		
		/** Rev 2.1.7 **/
		//send:*IDN?\r	 read:manson,kps-6200,1234,V1.0.0
		readStr = send("*IDN?");		//SDP3 ================ OK
		System.out.println(111);
		String[] para = readStr.toUpperCase().split(",");
		if(para.length>2){
			ps.setModel(para[1]);
			return para[1].replace("-", "")+"OK";
		}
		
		readStr = send("GCHA");			//SSP8080============== OK
		if(readStr.indexOf("OK")>0) return "SSP8080OK";
		readStr = send("GALL");		//SSP8XXX-9XXX=========
		if(readStr.indexOf("OK")>0) return readStr.replace("-", "");
		
		//Not SDP.old ============================================
		if(app.isOldSDP==false) {	//ָǾSDP
			readStr = send("GMAX"+connInfo.getRs485Str());
			if(readStr.indexOf("OK")>0) {
				PairVC vc = new PairVC();
				vc.setVolt(func.getFloat(readStr.substring(0,3))/10);
				String c = readStr.substring(3,6);
				vc.setCurr(func.getFloat(c)/100);
				ps.setMax(vc);
				int v = func.getInt(readStr.replace("OK", ""));
				if(v<402502) { return "SDP2210OOK"; }else if(v==402502) { return "SDP2405OOK"; }else { return "SDP2603OOK"; }	//201999OK	//402502OK
			}
		}
		//SDP.old end ============================================
		
		return readStr;
	}

	private Object[][] getProgram(){	//SDP only
		Object[][] data = new Object[20][3];
		String line = cmdSet.getProgram();
		if(line.indexOf("OK")>=200){
			int h,m;
			for(int r=0; r<data.length; r++){
				m=func.getInt(line.substring(r*10+6, r*10+8));
				h = m / 60;
				m = m % 60;
				data[r][0] = func.getFloat(line.substring(r*10, r*10+3))/10;
				data[r][1] = func.getFloat(line.substring(r*10+3, r*10+6))/100;
				data[r][2] = h+":"+func.getFormatStr(m, 2)+":"+line.substring(r*10+8, r*10+10);
			}
		}else{
			for(int r=0; r<data.length; r++){
				data[r][0] = 0f;
				data[r][1] = 0f;
				data[r][2] = "0:00:00";
			}
		}
		//pscs.setCptsITP(this);
		return data;
	}

	private void running() {
			PairVCS vcs = new PairVCS();
			int getdErrCount = 0;
			String strRead = "";
			int runIndex = 0;
			float v = 0, c = 0;
//			boolean isRunNew = false;
			int newIdx = 0;
			
			while (!isExit){
				if(!ps.isFactoryMode() && isRunerAutoAccess){
					if(connInfo.getBeanConnectType()==EnmBeanConnectType.RS485) this.setCommPort(null);
					if(ConnectOK==false){//runNewPort && 
						++newIdx;
						System.out.println(newIdx+"  "+System.currentTimeMillis() + " start-----");
						if(connInfo!=null && connInfo.getName()!=null) _newComPortConnection(newIdx);
						System.out.println(newIdx+"  "+System.currentTimeMillis() + " end  -----");
					}else if(isSetUWL){		/** Set UVL / UCL */
						// ======== if UwL < Setting.value then 
//						boolean implUandS = true;	//ǷҪϵ
						float fUvlV = func.getFloat(pscs.cpts.txtUVL.getText());
						float fUvlC = func.getFloat(pscs.cpts.txtUCL.getText());
//						if(implUandS){
							boolean changeSetting = false;
							if(ps.getSetting().getVolt()>fUvlV){	//if UVL < Setting.Volt then Setting.Volt = UVL
								strRead = cmdSet.setVoltage(fUvlV);
								if(strRead.indexOf("OK")>=0) ps.getSetting().setVolt(fUvlV);
								try { Thread.sleep(100); } catch (InterruptedException e) { }
								changeSetting = true;
							}
							if(ps.getSetting().getCurr()>fUvlC){	//if UCL < Setting.Curr then Setting.Curr = UCL
								strRead = cmdSet.setCurrent(fUvlC);
								if(strRead.indexOf("OK")>=0) ps.getSetting().setCurr(fUvlC);
								try { Thread.sleep(100); } catch (InterruptedException e) { }
								changeSetting = true;
							}
							if(changeSetting) {	//refresh setting
								if(ps.getModel().startsWith("SSP"))
									ps.setSetting(cmdSet.getSetting(ps.getABCSelected()));
								else
									ps.setSetting(cmdSet.getSetting());
								try { Thread.sleep(100); } catch (InterruptedException e) { }
								pscs.setCptsSetting(this);
							}
//						}
						// ======== end if UwL < Setting.value then 
						strRead = cmdSet.setVoltageUppeLimit(fUvlV);
						if(strRead.indexOf("OK")>=0) ps.getUwl().setVolt(fUvlV);
						try { Thread.sleep(100); } catch (InterruptedException e) { }
						strRead = cmdSet.setCurrentUppeLimit(fUvlC);
						if(strRead.indexOf("OK")>=0) ps.getUwl().setCurr(fUvlC);
						try { Thread.sleep(100); } catch (InterruptedException e) { }
						pscs.setCptsUwl(this);
						pscs.panWFG.setRunWFG_Enabled();
						ps.setOutput(cmdSet.getOutputIsOn());
						pscs.tableETP.repaint();  //refresh UVL and UCL
						isSetUWL = false;
						pscs.panMultiple.refreshCptsLabInfo(this);
						//pscs.panITP.refreshValidDataOfTable();
						
						func.checkValidDataOfTableITP(pscs);//.checkTableEtpData(pscs, pscs.panITP.tableITP);
						func.checkValidDataOfTableETP(pscs);//.checkTableEtpData(pscs, pscs.tableETP);
						
						//if(!pscs.getConnCurr().isRunETP) 
						pscs.refreshButsEnable();
						
						
						
					}else if(runCmdGettSettingVolt){		/** get Setting.Volt */
						ps.setSetting(cmdSet.getSetting());
						pscs.setCptsSetting(this);
						runCmdGettSettingVolt = false;
					}else if(runCmdSetVCO){  	/** Set Setting V/C/O */
						v = (float)pscs.cpts.sliSetV.getValue()/ps.getVoltFormatSetting();
						c = (float)pscs.cpts.sliSetC.getValue()/ps.getCurrFormatSetting(); 
						if(v*c>ps.getMaxPower()){
							String msg = pscs.lang.getString("Lang_Power_greater_than_%w_the_setting_is_invalid");
							msg = msg.replace("%", "" + (int)ps.getMaxPower());
							JOptionPane.showMessageDialog(new Frame(), msg, app.name, JOptionPane.ERROR_MESSAGE);
							ps.setSetting(ps.getSetting());
							pscs.setCptsSetting(this);
						}else{
							if(ps.getSerial()==EnmSerial.NEP) send("SYSTem:PRESet0");	//NEP is OK; KPS ?
							if(cmdSet.setVoltageCurrentOutput(v, c, pscs.cpts.rbtOn.isSelected()).indexOf("OK")>=0){
								ps.setOutput(pscs.cpts.rbtOn.isSelected());	//Output of LED ʾͬ
								ps.setSetting(new PairVC(v,c));		//Setting of LED ʾͬ
								pscs.setCptsSetting(this);
								if(ps.getModel().startsWith("8")){
									if(ps.getModel().endsWith("8080")){
										//set tableABC.voltage
									}else{					//SSP8xxx
										pscs.panWFG.rbutD.setSelected(true);	//select D
									}
								}
							}
						}
						runCmdSetVCO = false;
					}else if(runCmdSetVC_old){ 	/** Run is Stop to before.setting ... */
						if(oldOutput){
							strRead = cmdSet.setVoltageCurrentOutput(oldSettingVC.getVolt(), oldSettingVC.getCurr(),  oldOutput);
						}else{
							strRead = cmdSet.setVoltage(oldSettingVC.getVolt());
							strRead = cmdSet.setCurrent(oldSettingVC.getCurr());
							strRead = cmdSet.setOutput(false);
						}
						if(strRead.equals("OK")){
							ps.setOutput(oldOutput);
							ps.setSetting(oldSettingVC);
							pscs.setCptsSetting(this);
						}
						runCmdSetVC_old = false;
					}else if(isSaveFuncABC){	//SSP
						saveSetFuncABC();
						isSaveFuncABC = false;
					}else if(isSetRangeChannel){	//SSP 8080
						int cha = -1;
						if(pscs.panWFG.rbut16.isSelected()){
							cha = 0;
						}else if(pscs.panWFG.rbut27.isSelected()){
							cha = 1;
						}else if(pscs.panWFG.rbut36.isSelected()){
							cha = 2;
						} 
						if(cha>=0) {
							if(send("SCHA" + cha).indexOf("OK")>=0){ 
//								runNewPort = true;
								this.setConnectOK(false);
							}
						}
						pscs.cpts.sliSetV.revalidate();
						pscs.cpts.sliSetC.revalidate();
						pscs.cpts.sliSetV.repaint();
						pscs.cpts.sliSetC.repaint();
						isSetRangeChannel = false;
					}else if(isSaveTransitTime){	//SSP
						SaveSetTime();
						isSaveTransitTime = false;
					}else if(isSetABC_Select){	//SSP
						int i = -1;	//ԤѡABCֵ
						if(pscs.panWFG.rbutA.isSelected()){
							i = 0;
						}else if(pscs.panWFG.rbutB.isSelected()){
							i = 1;
						}else if(pscs.panWFG.rbutC.isSelected()){
							i = 2;
						}
						if(i>=0 && i<=2){
							if(ps.getModel().startsWith("SSP9")) i++;
							if(send("SABC" + i).indexOf("OK") >= 0) {
								pscs.pssetABCSelected(ps.getModel().startsWith("SSP9") ? i-1 : i);
								ps.setSetting(cmdSet.getSetting(i));
								pscs.setCptsSetting(this);
								isSetABC_Select = false;
							}
						}
					}else if(isRunWFG){		//SSP or KPS
						String lineStr = "";
						if(isRunningTableWFG){	// to stop
							if(connInfo.getModel().startsWith("KPS6")||connInfo.getModel().startsWith("NEP")){
								send("PROG:STOP");
							}else{
								lineStr = send("STOP");
								if(lineStr.indexOf("OK") < 0) lineStr = send("STOP");
							}
							isRunningTableWFG = false;
						}else{					//to run
							if(isChangeFuncABC) saveSetFuncABC();												// save tableFuncABC
							if(connInfo.getModel().startsWith("SSP9")){
								String[] arr = pscs.panWFG.cmbRunWfg.getSelectedItem().toString().split(" ");
								int port = func.getInt(arr[0]);
								if(send("SOUT1").indexOf("OK")>=0) ps.setOutput(true);	//set output to on
								lineStr = send("RUNP" + String.format("%02d",port));	// set port
								int cycle = func.getInt(pscs.panWFG.txtRunCycle.getText());
								lineStr = send("SWCN" + String.format("%03d",cycle));	// set cycle
								lineStr = send("RPOI"+String.format("%02d",port));//RUNW								// exe running
							}else if(connInfo.getModel().startsWith("KPS6")||connInfo.getModel().startsWith("NEP")){
								if(!ps.getOutput() && connInfo.getModel().startsWith("KPS6")){	//NEPϵMCUԶOutput On
									send("OUTP ON");
									func.sleep(400);
									ps.setOutput(send("OUTP?").startsWith("1"));
									if(!ps.getOutput()) send("OUTP ON");
								}
								func.sleep(100);
								int start = 1;//func.getInt(cpts.txtRunStartRow.getText());
								int end = func.getInt(pscs.panWFG.cmbRunWfg.getSelectedItem().toString().substring(0, 2).trim());
								int cycle = func.getInt(pscs.panWFG.txtRunCycle.getText());
								send("PROG:START "+start+","+end+","+cycle);
							}else{
								SaveSetTime();
								if(send("SOUT1").indexOf("OK")>=0) ps.setOutput(true);	//set output to on
								String runStr = pscs.panWFG.cmbRunWfg.getSelectedItem().toString().trim();	//A-B
								if(ps.getModel().startsWith("SSP9")){
									lineStr = send("SWCN" + String.format("%03d", func.getInt(pscs.panWFG.txtRunCycle.getText())));	//save run cycle
								}
								lineStr = send("RUNP" + (runStr.getBytes()[0]-65) + (runStr.getBytes()[2]-65));
								if(lineStr.indexOf("OK") < 0)
									lineStr = send("RUNP" + (runStr.getBytes()[0]-65) + (runStr.getBytes()[2]-65));//save running
							}
							isRunningTableWFG = true;
						}
						pscs.refreshButsEnable();	//runType 0:isRunWFG; 1:isRunITP; 2:isRunETP
						isRunWFG = false;
					}else if(isRunITP){		/** --- Run/Stop --ITP(ڲ)--------------------- */
						if(pscs.panITP.butIRun.getText().equals(pscs.lang.getString("Lang_Run"))){
							int start = func.getInt(pscs.cpts.txtRunStartRow.getText());
							int end = func.getInt(pscs.cpts.txtRunEndRow.getText());
							int cycle = func.getInt(pscs.cpts.txtCycleI.getText());
							if(ps.getModel().startsWith("SDP2")) {
								ps.setOutput(true);
								strRead = send("RUNP"+this.getConnInfo().getRs485Str()+func.getFormatStr(cycle, 4));
							}else {
								strRead = send("PROG:START "+start+","+end+","+cycle);
							}
							pscs.panITP.butIRun.setText(pscs.lang.getString("Lang_Stop"));
						    isRunningTableITP = true;
						}else{
							if(ps.getModel().startsWith("SDP2")) {
								ps.setOutput(false);
								send("STOP"+this.getConnInfo().getRs485Str());
							}else {
								send("PROG:STOP");
							}	
							pscs.panITP.butIRun.setText(pscs.lang.getString("Lang_Run"));
							isRunningTableITP = false;
						}
						isRunITP = false;
						idxTmp = 99; //ִGetPanl
					}else if(isRunningTableETP){		/** --- Run/Stop --ETP(ⲿ)--------------------- */
						long dt = (new Date()).getTime();
						if(runETP.runTime!=null && (runETP.runAllRowIndex==0 || dt>runETP.runTime[runETP.runAllRowIndex])){  // -1 is start status
							boolean o=false;
							int r = runETP.rowValid==0 ? 0 : runETP.runAllRowIndex % runETP.rowValid;
							if(runETP.runAllRowIndex == runETP.runTime.length-1){ //run is over to ...
								if(this.isChkOutputOff ){
									strRead = cmdSet.setOutput(false);	//Rev 2.1.7
									ps.setOutput(false);
								}
								for(int row=0; row<pscs.tableETP.getRowCount(); row++) pscs.tableETP.setValueAt(""+(row+1), row, 0);
							}else{ 			//is running ...
								if(runETP.runAllRowIndex==0 && ps.getSerial()==EnmSerial.NEP){	//״set PRE0(PRE1-3)Ч
									send("SYSTem:PRESet0");	//NEP is OK; KPS ?
								}
								v = func.getFloat(ps.getDataETP()[r][0]);//(pscs.tableETP.getValueAt(r, 1).toString()); 
								c = func.getFloat(ps.getDataETP()[r][1]);//(pscs.tableETP.getValueAt(r, 2).toString()); 
								o = (boolean) ps.getDataETP()[r][3];//(pscs.tableETP.getValueAt(r, pscs.tableETP.getColumnCount()-1).toString());
								//System.out.println(ps.getDataETP()[r][3].getClass() +"\t"+ ps.getDataETP()[r][3]);
								strRead = cmdSet.setVoltageCurrentOutput(v, c, o);
								if(!strRead.equals("OK")) {
									strRead = cmdSet.setVoltageCurrentOutput(v, c, o);
								}
								
								if(runETP.rowValid==0 || runETP.runAllRowIndex % runETP.rowValid==0) runETP.currRunCycleIndex++;
								if(runETP.runAllRowIndex<4 && ps.getModel().equals("SSP8080")) send("SABC3");	//Note:SSP8080 without 3
								if(!isRunningTableETP){ 
									pscs.cpts.labStbDesc.setText(""); 
								}else if(this.isCurrConn()){
									try{
										pscs.tableETP.changeSelection(runETP.runAllRowIndex%pscs.tableETP.getRowCount(), 0, false, true);	//쳣
									}catch(ClassCastException e){}
									pscs.tableETP.repaint();
									
									if(runETP.runCycleCount==0){
										pscs.cpts.labStbDesc.setText(" " + pscs.lang.getString("Lang_Running_Cycle") + ": " + runETP.currRunCycleIndex );
									}else{
										if(pscs.versionDevelog.equals("V2.1.6"))
											pscs.cpts.labStbDesc.setText(" " + pscs.lang.getString("Lang_Running_Cycle") + ": " + runETP.currRunCycleIndex + " / " + runETP.runCycleCount);//Rev 2.1.6
										else
											pscs.cpts.labStbDesc.setText(" " + pscs.lang.getString("Lang_Running_Cycle") + ": " + runETP.currRunCycleIndex + " / " + runETP.runCycleCount + " ("+pscs.lang.getString("Lang_Remain")+": " + runETP.getRemainTime()  + ")");//Rev 2.1.7
									}
								}
								if(strRead.equals("OK")){
									ps.setOutput(o);//Output of LED ʾͬ
									ps.setSetting(new PairVC(v,c));//Setting of LED ʾͬ
								}
							}
							runETP.runAllRowIndex++;
							pscs.tableETP.repaint();
							if(runETP.runAllRowIndex>=runETP.runTime.length){
								if (runETP.runCycleCount>0) runETP.toRunStop(false); else runETP.runStart(); //runFG1.runIndex = 0;
							}
						}
					}else if(isSaveProgram){	/** Save Program to PS */
						isRunningTableWFG = true;	//
						pscs.refreshButsEnable();
						String line = cmdSet.setProgram();
						if(line!=null && line.indexOf("OK")>=0) isSaveProgram = false;
						
						if(this.isCurrConn() && ps.getModel().startsWith("SDP2")) {	//SDP2xxxSaveProgramҪ5
							new Thread(new Runnable() {
								public void run() {
									long d = System.currentTimeMillis();
									while(System.currentTimeMillis()-d<5000) func.sleep(200);
									isRunningTableWFG = false;
									pscs.refreshButsEnable();
								}
							}).start();
						}else {
							isRunningTableWFG = false;
							pscs.refreshButsEnable();
						}
					}else if(isReadProgram){	/** Read Program from PS */
//						String line = cmdSet.getProgram();
//						if(line.indexOf("OK")>0) 
						ps.setDataITP(getProgram());
						pscs.setCptsITP(this);
						isReadProgram = false;
					}else if(isSetMemoryIdx){		/** Setting Memory */
						int setIndex = -1;
						Object[][] arr = new Object[pscs.tableIPM.getRowCount()][3];
						for(int r=0; r<pscs.tableIPM.getRowCount(); r++) {
							boolean isSelectRow = v==ps.getSetting().getVolt() && c==ps.getSetting().getCurr();
							v = func.getFloat(pscs.tableIPM_dtm.getValueAt(r, 1).toString());
							c = func.getFloat(pscs.tableIPM_dtm.getValueAt(r, 2).toString());
							arr[r][0] = isSelectRow;
							arr[r][1] = v;
							arr[r][2] = c;
							if((boolean)pscs.tableIPM.getValueAt(r, 0)) setIndex = r;
						}
						//String line = cmdSet.setPresetMemory(arr);
						cmdSet.setPresetMemory(arr);
						//if(line.indexOf("OK")>=0) {	//SDP2xxx setMemoryIndex ǰûҪMemory
							ps.setDataIPM(arr);
							if(connInfo.getModel().startsWith("KPS6")){
								send("SYSTem:PRESet" + (setIndex+1) +" "+ arr[setIndex][0]+"V,"+arr[setIndex][1]+"A");
								ps.setSetting(new PairVC((float)arr[setIndex][1], (float)arr[setIndex][2]));
								pscs.setCptsSetting(this);
							}else if(connInfo.getModel().startsWith("NEP")){
								send("SYSTem:PRESet" + (setIndex+1));
								ps.setSetting(new PairVC((float)arr[setIndex][1], (float)arr[setIndex][2]));
								pscs.setCptsSetting(this);
							}else {// if(line.endsWith("OK")){	//}else if(setIndex<3 && line.endsWith("OK")){
								if(connInfo.getModel().startsWith("SSP9")){
									send("SABC"+(setIndex+1));
									ps.setSetting(cmdSet.getSetting(setIndex+1));
									pscs.setCptsSetting(this);
								}else{
									String ret = "";
									if(ps.getSerial()==EnmSerial.HCS3)
										ret = cmdSet.setMemoryIndex(setIndex);
									else
										ret = cmdSet.setMemoryIndex(setIndex+1);
									if(ret!=null && ret.equals("OK") && setIndex>=0){
										//ps.setSetting(new PairVC((float)arr[setIndex][0], (float)arr[setIndex][1])); 
										ps.setSetting(new PairVC((float)arr[setIndex][1], (float)arr[setIndex][2])); 
										pscs.setCptsSetting(this);
									}else if(setIndex<0) {	//sdp2 set to setting
										ps.setSetting(cmdSet.getSetting());
									}
								}
							};
							isSetMemoryIdx = false;
						//}
					}else if(isReadM){		/** Run Memory */
						ps.setDataIPM(cmdSet.getPresetMemory());
						if(getConnInfo().getSerial()==EnmSerial.SDP2new) {
							ps.setMemoryIdx(((CmdSetSDP2new)cmdSet).getMemoryIndex());
						}else if(getConnInfo().getSerial()==EnmSerial.SDP2old) {
							ps.setMemoryIdx(((CmdSetSDP2old)cmdSet).getMemoryIndex());
						}
						pscs.setCptsIPM(this);
						isReadM = false;
						this.initChangeRowArr();
					}else if(isSaveM){		/** Save Memory */
						Object[][] arr = new Object[pscs.tableIPM.getRowCount()][3];
						for(int r=0; r<pscs.tableIPM.getRowCount(); r++) {
							boolean isSelectRow = v==ps.getSetting().getVolt() && c==ps.getSetting().getCurr();
							v = func.getFloat(pscs.tableIPM_dtm.getValueAt(r, 1).toString());
							c = func.getFloat(pscs.tableIPM_dtm.getValueAt(r, 2).toString());
							arr[r][0] = isSelectRow;
							arr[r][1] = v;
							arr[r][2] = c;
						}
						cmdSet.setPresetMemory(arr);
						initChangeRowArr();
						isSaveM = false;
						this.initChangeRowArr();
					}else if(ps.isSetOutput()){		/** Setting Output */
						if(ps.getOutput()){ 
							if(cmdSet.setOutput(false).indexOf("OK")>=0){ ps.setOutput(false); }
						}else{ 
							if(cmdSet.setOutput(true).indexOf("OK")>=0){ ps.setOutput(true); }
						}
						ps.setSetOutput(false);
						if(isCurrConn()) pscs.lcd.repaint();
					}
					
					if(isCmdTest){	/** do command test **/
						String cmd = pscs.panCmdTest.txtSend.getText().replace("\\r", "\r").replace("\\n", "\n");
						String cr = pscs.panCmdTest.chkCR.isSelected() ? "\r" : "";
						pscs.panCmdTest.txtRece.append("send: " + pscs.panCmdTest.txtSend.getText() + cr.replace("\r", "\\r") + "\n");
						pscs.panCmdTest.txtRece.append("read: " + send(cmd+cr) + "\n");
						func.sleep(100);
						JScrollBar jscrollBar = pscs.panCmdTest.scrPan.getVerticalScrollBar();
						if(jscrollBar!=null) jscrollBar.setValue(jscrollBar.getMaximum());
						isCmdTest = false;
					}
					
					if(runIndex>2){	//----------- GETD --------------5
						runIndex=1;
						if(!ConnectOK){
							ps.setDisplay(null);
						}else{
							vcs = cmdSet.getVoltageAndCurrentAndStatus();
							if(vcs!=null){
								ps.setDisplay(vcs);
								getdErrCount=0;
							}else{
								getdErrCount++; 
								if(getdErrCount>2){	//ûnε쳣
									ps.setDisplay(null); 
									if(getdErrCount>100000) getdErrCount=10;
								}
							}
						}
						lcd.repaint();
						if(isCurrConn()) pscs.lcd.repaint();
						
						//ڲʲôʱʼֹͣ
						//if(this.isCurrConn() && isRunITPing && ps.getModel().startsWith("SDP2")) {
						if(ps.getModel().startsWith("SDP2")) {
							if(idxTmp>8) {
								idxTmp = 0;
							    String line = cmdSet.getAll();	//3?;?6?661;?3?3?3?1;?3?3?3?10000000000003?6=3?0113?6=3?0115OK
								if(line!=null && line.endsWith("OK")){			//3?;?6?661;?3?3?3?1;?3?3?3?10000000000003?6=3?0113?6=3?0115
									line = line.replace("OK", "");
									boolean isRun = false;
									boolean output = false;
									if(getConnInfo().getSerial()==EnmSerial.SDP2new) {
										isRun = func.getRightStr(line, 9, 1).equals("1");		//3?;?6?661;?3?3?3?1;?3?3?3?10000000000003?6=3?0113[?]6=3?0115
										output = func.getRightStr(line, 3, 1).equals("1");		//3?;?6?661;?3?3?3?1;?3?3?3?10000000000003?6=3?0113?6=3?0[1]15
										isFault = func.getRightStr(line, 4, 1).equals("1");		//3?;?3?061;?3?3?3?1;?3?3?3?1000000000000067?5;0113?7=3?011301110[1]011OK
									}else if(getConnInfo().getSerial()==EnmSerial.SDP2old) {
										isRun = func.getRightStr(line, 8, 1).equals("0");		//3?;?6?661;?3?3?3?1;?3?3?3?10000000000003?6=3?0113[?]6=3?0115
										output = func.getRightStr(line, 2, 1).equals("1");
									}
									isRunningTableITP = isRun;
									if(this.isCurrConn()) {
										pscs.panITP.butIRun.setText(isRunningTableITP ? pscs.lang.getString("Lang_Stop") : pscs.lang.getString("Lang_Run"));
										if(!isTableEtpValidData) pscs.refreshButsEnable();
									}
									ps.setOutput(output);
								}
							}else {
								idxTmp++;
							}
						}
						
					}else{
						runIndex++;
					}
					if(connInfo.getBeanConnectType()==EnmBeanConnectType.RS485) this.close();
					

					//set log
					long dt = (new Date()).getTime();
					if(logN.startDateTime == null){	//not connect rs232
						logN.startTime = (new Date()).getTime();
						logN.startDateTime = new Date();
						logN.index = 0;
					}
					if(dt > logN.startTime + (long)(Sampling * logN.index *1000)){
						logN.arr.add(ps.getDisplay());//pscs.lcd.getData());//.vcs
						if(logN.arr.size()>18001){logN.arr.remove(0);}
						logN.index++;
						
						if(isCurrConn() && pscs.cpts.rbtNow.isSelected()) {
							pscs.box.initVCP_MaxMin(logN);
							if(pscs.panLog!=null) pscs.panLog.repaint();
						}
					}
				}
				try {Thread.sleep(app.timeOutMs);} catch (InterruptedException e) {}
			}
		}

	public String toString(){
		return connInfo.getName();
	}
	
	public void close(){
		try{ 
			if(serialPort!=null){	
				try {Thread.sleep(100);} catch (InterruptedException e) {}
				inputStream.close();
				outputStream.close();
				serialPort.close();
				try {Thread.sleep(100);} catch (InterruptedException e) {}
			}
		} catch (Exception e) { }
	}
	
	public void exit(){
		close();
		isRunerAutoAccess = false;
		isExit = true;
	}

	public String getCommPort(){ 
		return connInfo==null?"":connInfo.getCommPort();
	}
	
	public void setCommPort(String port){
		
		if(connInfo==null || connInfo.getBeanConnectType()==null || connInfo.getBeanConnectType()==EnmBeanConnectType.Ethernet) return;
		close();
		if(port!=null) connInfo.setCommPort(port);
		Enumeration<?> SerialPortList = CommPortIdentifier.getPortIdentifiers();
		while(SerialPortList.hasMoreElements()) {
			CommPortIdentifier portId=(CommPortIdentifier)SerialPortList.nextElement();
			if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL) {
				if(portId.getName().equals(connInfo.getCommPort())) {
					//SerialPort serialPort1 = pscs.mapRS485.get(connInfo.getCommPort());
					//if(serialPort1==null) {
						if(!use) { try { serialPort=(SerialPort) portId.open("ReadCommApp",2000); serialPort.setRTS(false); } catch(PortInUseException a){continue;} }
						try { serialPort.notifyOnOutputEmpty(true); } catch(Exception a){}
						try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch(UnsupportedCommOperationException a){}
						pscs.mapRS485.put(connInfo.getCommPort(), serialPort);
					//}else{
					//	serialPort=serialPort1;
					//	try { outputStream=serialPort.getOutputStream(); } catch(IOException a){}
					//}
					break;
				}
			}
		}
		try { 
			if(serialPort!=null){
				outputStream=serialPort.getOutputStream();
				inputStream=serialPort.getInputStream(); 
//				try{	//пѡһ֮ǰöûеPort
//					serialPort.notifyOnDataAvailable(true);	
//				}catch(java.lang.NullPointerException e){}
			}
		} catch(IOException a){}
	}

	public void setCommPortSpeed(int speed){	//9600 / 19200
		if(serialPort!=null){
			try { serialPort.setSerialPortParams(speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch(UnsupportedCommOperationException a){}
		}
	}

	private void setConnectionType(){//(BeanConnectInfo connInfo) {
		EnmConnType connType = EnmConnType.COM;
		if(connInfo.getBeanConnectType()==EnmBeanConnectType.Ethernet){
			connType = EnmConnType.TCP;	//SSP.UDP to TCP   //enmConnType = bci.getModel().startsWith("SSP") ? EnmConnType.UDP : EnmConnType.TCP;	//SSP:UDP Other:TCP
		}else if(connInfo.getBeanConnectType()==EnmBeanConnectType.RS485){
			connType = EnmConnType.COM485;
		}
		Integer speed = 9600;
		if(connInfo.getModel()!=null && connInfo.getModel().startsWith("SDP3") && connInfo.getBeanConnectType()==EnmBeanConnectType.USB) speed = 19200;
		try{
			if(connType == EnmConnType.COM || connType == EnmConnType.COM485){
				setCommPort(connInfo.getCommPort());
				setCommPortSpeed((int)(speed));
			}else if(connType == EnmConnType.TCP){
				remoteIP = connInfo.getRemoteIp();
				this.remotePort = connInfo.getRemotePort();
			}else if(connType == EnmConnType.UDP){
				remoteIP = connInfo.getRemoteIp();
				remotePort = connInfo.getRemotePort();
				try { 
					clientUDP = new DatagramSocket();
					clientUDP.setSoTimeout(400);
				} catch (SocketException e) { }
			}	
		}catch(java.lang.NullPointerException e){}
	}

	public ArrayList<String> getListPort() { return Portlist; }
    
	public int futCommUpdateMode(byte[] bs) {
		if(!ps.isFactoryMode()){return 0;}
		try {Thread.sleep(5);} catch (InterruptedException e) {}
		
    	try { outputStream.write(bs); } catch (IOException e) {serialPort.close();}
		int intRead = 0;
		byte[] readBuffer=new byte[100];
		long t=(new Date()).getTime(), a=2000;
    	try {
	    	while((new Date()).getTime()-t<a && intRead==0){ //use10 >=5 ==10
	    		try {Thread.sleep(2);} catch (InterruptedException e) {}
	    		if(inputStream.available()!=0){
	    			t=(new Date()).getTime();
	    			try {Thread.sleep(2);} catch (InterruptedException e) {}
	    			int numBytes=inputStream.read(readBuffer);
					for(int i=0;i<numBytes;i++){   
						intRead = intRead + readBuffer[i];
					}
	    		}
	    	}
		}
		catch(IOException e){}
		return intRead;	
	}

    public String send(String cmd){
    	System.out.println(connInfo.getCommPort()+"\tcmd:"+cmd);
		String cmdResource = cmd;
		String readStr = "";
		if(ps.isUpdateFirmwareMode()){return "";}
		try {
			Thread.sleep(connInfo.getBeanConnectType()==EnmBeanConnectType.RS485 ? 100 : 50);
		} catch (InterruptedException e) {}
		byte[] sendBuf;
		if(!cmd.endsWith("\r") && !isCmdTest) cmd = cmd + "\r";	//SDP3 ɼӻس
		if(connInfo.getBeanConnectType()==EnmBeanConnectType.Ethernet){ //(enmConnType == EnmConnType.TCP) {
			boolean isConn = false;
			long d = System.currentTimeMillis();
			while (!isConn && System.currentTimeMillis()-d<2000) {
				
				try {
					clientTCP =  new Socket();
					clientTCP.setSoTimeout(1000);
					clientTCP.connect(new InetSocketAddress(remoteIP, remotePort));	//remoteIPڣʱ仨Ѻܳ
					try { Thread.sleep(100); } catch (InterruptedException e) { }
					outputStreamTCP = clientTCP.getOutputStream();
					inputStreamTCP = clientTCP.getInputStream();
					isConn = true;
					sendBuf = (cmd).getBytes();
					try { outputStreamTCP.write(sendBuf); } catch (IOException e) {  }
					readStr = readTCP(cmd); // ûзֵ					
				} catch (Exception e) {
//					ps.lcd.setData(null);	//һ뿪ѭͲӣSDPҪڴ˶ϿLCDLOG¼ûжϿ
				} finally {
					try {// 󲻳ɹ쳣ر
						if (outputStreamTCP != null) outputStreamTCP.close();
						if (inputStreamTCP != null) inputStreamTCP.close();
						if (clientTCP != null) clientTCP.close();
					} catch (IOException e1) { }
				}
				try {Thread.sleep(100);} catch (InterruptedException e) {}
			}
		}else{ 	//EnmConnType.COM or RS485
			sendBuf = cmd.getBytes();
			
			//if(connInfo.getBeanConnectType()==EnmBeanConnectType.RS485) this.setCommPort(null);
			
			/** clear inputStream **/
			if(outputStream==null) return "";
			try {if(inputStream.available()!=0) inputStream.read(new byte[1000]); } catch (IOException e1) {} catch (NullPointerException e2){}//clear inputStream
			
			/** send & read **/
			try { outputStream.write(sendBuf); } catch (IOException e) {}	//{serialPort.close();}
			readStr = readCOM(cmd);
			
			//if(connInfo.getBeanConnectType()==EnmBeanConnectType.RS485) this.close();
			//================
			//this.close();
			
//			try{ 
//				if(serialPort!=null){	
//					try {Thread.sleep(100);} catch (InterruptedException e) {}
////					inputStream.close();
////					outputStream.close();
//					//serialPort.close();
//					try {Thread.sleep(100);} catch (InterruptedException e) {}
//				}
//			} catch (Exception e) { }
			//================

		} 
		String dt = (new java.text.SimpleDateFormat("yyyy/MM/dd-HH:mm:ss")).format(new Date());
		String cn = "connName:" + connInfo.getName();
		String rs485add = connInfo.getBeanConnectType()==EnmBeanConnectType.RS485? ("/"+connInfo.getRs485Str()) : "";
		String com = "commPort:"+connInfo.getCommPort()+rs485add;
		String model = "model:" + ps.getModel();
		String ct = "connType:"+connInfo.getBeanConnectType();
		String send = "send:"+cmd.replace("\r", "\\r").replace("\n", "\\n");
		String read = "read:" + readStr;// + (FrmPSCS.getIt().cpts.labStbDesc.getText().length()==0 ? "" : "\t"+FrmPSCS.getIt().cpts.labStbDesc.getText());
		final String msg = dt+"\t" + cn + "\t" + model +"\t" + ct + "\t"+com +"\t"+ send +"\t" + read;
		System.out.println(msg);	/** DEBUG **/
		new Thread(new Runnable() {
			public void run() {
				if(pscs.pscsCmdLog!=null) try { pscs.pscsCmdLog.write(msg+"\r\n"); } catch (IOException e) { }	//write log.txt
			}
		}).start();
		
		if(readStr.startsWith(cmdResource) && !isCmdTest)  return readStr.substring(cmdResource.length());
		return readStr;
    }

	/**
     * @param cmd
     * @return String
     */
	String readCOM(String cmd) {
    	if(ps.getModel()!=null && (ps.getModel().startsWith("SDP3")||ps.getModel().startsWith("KPS6")) && cmd.indexOf("?")<=0) return "";	//scpi дûзֵ
    	String strRead = "";
		long timeLast = System.currentTimeMillis();
		int timeOut = app.timeOutMs;// 180;//APP.getIt().isCalibration ? 1000 : 400;
		try {
        	while(System.currentTimeMillis()-timeLast < timeOut){ //use10 >=5 ==10
        		try {Thread.sleep(5);} catch (InterruptedException e) {}
        		if(inputStream.available()!=0){
        			byte[] readBuffer=new byte[1000];
        			timeLast = System.currentTimeMillis();
        			String lineStr = "";
        			int numBytes=inputStream.read(readBuffer);
					for(int i=0;i<numBytes;i++) lineStr = lineStr + (char)readBuffer[i];
					strRead = strRead + lineStr; 
//					if(APP.getIt().currConnect.getSerial()==EnmSerial.SDP3||APP.getIt().currConnect.getSerial()==EnmSerial.KPS6)
					if(cmd.indexOf("?")>=0)	strRead = strRead.replace("\n", "OK");
					
					//жǷɶȡ
					if(strRead.indexOf("OK")>=0) break;
					if(ps.isCalibration()){
						if(strRead.indexOf("VOL?")>=0||strRead.indexOf("CUR?")>=0||strRead.indexOf("DONE")>=0) break;
					}
        		}
        	}
		}
		catch(IOException e){}
		strRead = strRead.replace("\r", "");
		return strRead;
	}
	
	String readTCP(String cmd) {
	   	if(isSCPI() && cmd.indexOf("?")<=0) return "";	//scpi дûзֵ
    	String readStr = "";
		byte[] readBuffer=new byte[1000];
		long timeSart = System.currentTimeMillis();
		int timeOut = app.timeOutMs; //200 //APP.getIt().isCalibration ? 1000 : 400;
		if(cmd.indexOf("SYST:POWER")>=0||cmd.indexOf("SYST:LOC")>=0){
			timeOut = 1000;
		}
		try {
        	while(System.currentTimeMillis()-timeSart < timeOut){ //use10 >=5 ==10
        		try {Thread.sleep(10);} catch (InterruptedException e) {}
    			int numBytes=inputStreamTCP.read(readBuffer);
    			if(numBytes>0){
	    			String lineStr = new String(readBuffer, 0, numBytes);
	    			readStr = readStr + lineStr;
//					if(APP.getIt().currConnect.getSerial()==EnmSerial.SDP3||APP.getIt().currConnect.getSerial()==EnmSerial.KPS6){
					if(cmd.indexOf("?")>0){
//						if(readStr.indexOf("\n")>=0) break;	//жǷɶȡ
						if(readStr.indexOf("\n")>=0) break;	//жǷɶȡ
					}else{
						if(readStr.indexOf("OK")>=0) break;	//жǷɶȡ
					}
    			}
        	}
		}catch(IOException e){
		}
		readStr=readStr.replace("\r", "");
		readStr=readStr.replace("\n", "OK");
		return readStr;
	}

	private boolean isSCPI() {
		return ps.getModel()!=null && (ps.getModel().startsWith("SDP3")||ps.getModel().startsWith("KPS6"));
	}

	String readUDP(String cmd) {	//SSP8080ר
		String readStr = "";
		byte[] readBuffer=new byte[100];
		long timeSart = System.currentTimeMillis();//(new Date()).getTime();
		int timeOut = 400;
        try {
        	String lineStr = "";
        	while(System.currentTimeMillis()-timeSart < timeOut){ //use10 >=5 ==10
        		try {Thread.sleep(20);} catch (InterruptedException e) {}
        		DatagramPacket recvPacket = new DatagramPacket(readBuffer , readBuffer.length);
        		clientUDP.receive(recvPacket);
        		lineStr = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
        		if(lineStr.length()>0){
	        		readStr = readStr + lineStr; 
	        		lineStr="";
        		}        		
        		if(readStr.indexOf("OK")>=0) break;
        	}
		} catch (IOException e) { }
        readStr = readStr.replace("\r", "");
		return readStr;
	}

	public void serialEvent(SerialPortEvent arg0) {
		
		switch (arg0.getEventType()) {
		case SerialPortEvent.BI:
		case SerialPortEvent.OE:
		case SerialPortEvent.FE:
		case SerialPortEvent.PE:
		case SerialPortEvent.CD:
		case SerialPortEvent.CTS:
		case SerialPortEvent.DSR:
		case SerialPortEvent.RI:
		case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
			break;
		case SerialPortEvent.DATA_AVAILABLE:// пʱȡ,Ҹڷ
			byte[] readBuffer = new byte[1000];

			try {
				while (inputStream.available() > 0){
					try {Thread.sleep(5);} catch (InterruptedException e) {}
					inputStream.read(readBuffer);
				}
				String line = new String(readBuffer).trim();
				line.replace("\n", "OK");
				commData = commData + line;
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		}
		
	}

	public String getCommData() {
		return commData;
	}

	public void setCommData(String commData) {
		this.commData = commData;
	}

	public BeanConnectInfo getConnInfo() {
		return connInfo;
	}

	public void setConnInfo(BeanConnectInfo connInfo) {
		this.connInfo = connInfo;
	}

	public String getConnectName() {
		return connInfo==null ? null : connInfo.getName();
	}
	
	public void initLogN(){
		setSampling(pscs.cpts.sliSampling.getValue());
		logN.arr.clear();
		logN.startTime = (new Date()).getTime();
		logN.startDateTime = new Date();
		logN.index = 0;
	}

	private String saveSetFuncABC() {
		String strRe = "", cmd = "";
		float v,c;
		int s;
		isChangeFuncABC = false; 
		if(connInfo.getModel().equals("SSP8080")){//(getConnCurr().ps.getModel().equals("8080")){
		    for(int col=1; col<=3; col++){								//3 column data
		    	v = func.getFloat(pscs.panWFG.tableSetting.getValueAt(0, col).toString());
		    	c = func.getFloat(pscs.panWFG.tableSetting.getValueAt(1, col).toString());
		    	s = func.getInt(pscs.panWFG.tableSetting.getValueAt(pscs.panWFG.tableSetting.getRowCount()-1, col).toString());
		    	send("VOLT" + (col-1) + String.format("%04d",(int)(v*ps.getVoltFormatDisplay())));
		    	send("CURR" + (col-1) + String.format("%04d",(int)(c*ps.getCurrFormatDisplay())));
		    	strRe = send("SSWT" + (col-1) + String.format("%03d",s));
		    }
		    return strRe;
		}else if(connInfo.getModel().startsWith("SSP9")){	//9081
		    for(int col=1; col<pscs.panWFG.tableSetting.getColumnCount(); col++){	//10 column data
		    	v = func.getFloat(pscs.panWFG.tableSetting.getValueAt(0, col).toString());
		    	c = func.getFloat(pscs.panWFG.tableSetting.getValueAt(1, col).toString())/ps.getMachines();	//9081 /getConnCurr().ps.getMachines()
		    	s = func.getInt(pscs.panWFG.tableSetting.getValueAt(pscs.panWFG.tableSetting.getRowCount()-1, col));
		    	cmd = "SWFP";
		    	cmd = cmd + String.format("%02d",(col));								//IdNO
		    	cmd = cmd + String.format("%04d",(int)(v*ps.getVoltFormatSetting()));	//VALT
//		    	cmd = cmd + String.format("%04d",(int)(c*ps.getCurrFormatSetting()));	//CURR
		    	cmd = cmd + String.format("%04d",s);									//TIME
		    	strRe = strRe + send(cmd);
		    }
		    return strRe;
		}else if(connInfo.getModel().startsWith("KPS6")||connInfo.getModel().startsWith("NEP")){	//9081
		    for(int col=1; col<pscs.panWFG.tableSetting.getColumnCount(); col++){	//10 column data
		    	v = func.getFloat(pscs.panWFG.tableSetting.getValueAt(0, col).toString());
		    	c = func.getFloat(pscs.panWFG.tableSetting.getValueAt(1, col).toString())/ps.getMachines();	//9081 /getConnCurr().ps.getMachines()
		    	s = func.getInt(pscs.panWFG.tableSetting.getValueAt(pscs.panWFG.tableSetting.getRowCount()-1, col));
		    	cmd = "PROGram:DATA"+col+" "+v+"V,"+c+"A,"+s+"S";	//PROGram:DATA# <value1>,<value2>,<value3>
		    	strRe = strRe + send(cmd);
		    }
		    return strRe;
		}else{	//8xxx
		    for(int col=1; col<=3; col++){
		    	v = func.getFloat(pscs.panWFG.tableSetting.getValueAt(0, col).toString());
		    	c = func.getFloat(pscs.panWFG.tableSetting.getValueAt(1, col).toString());
		    	s = func.getInt(pscs.panWFG.tableSetting.getValueAt(pscs.panWFG.tableSetting.getRowCount()-1, col).toString());
		    	cmd = cmd + String.format("%04d",(int)(v*ps.getVoltFormatDisplay()));
		    	cmd = cmd + String.format("%04d",(int)(c*ps.getCurrFormatDisplay()));
		    	cmd = cmd + String.format("%03d",s);
		    }
		    return send("SETM" + cmd);
		}
	}
	private String SaveSetTime() {
		String reStr = "";
		int s;
	    for(int col=0; col<=5; col++){
	    	s = func.getInt(pscs.panWFG.tableTime.getValueAt(0, col).toString());
	        reStr = reStr + send("SDLT" + col + String.format("%02d",s));
	    }
		return reStr;			
	}
	
	public boolean isCurrConn(){
		return pscs.getConnCurr()==this;
	}

	public boolean isConnectOK() {
		return ConnectOK;
	}

	public void setConnectOK(boolean connectOK) {
		ConnectOK = connectOK;
	}

	public Object[][] getDataMemory() {
		return dataMemory;
	}

	public void setDataMemory(Object[][] data){
		dataMemory = data;
	}

	public int getSampling() {
		return Sampling;
	}

	public void setSampling(int sampling) {
		Sampling = sampling;
		if(this.isCurrConn()) {
			_FrmPSCS.getIt().cpts.labStbSampl.setText(" " + _FrmPSCS.getIt().lang.getString("Lang_Sampling") + ": " + Sampling + "S ");
		}
	}


}