package com.example.terminalprotocol;

import com.example.terminalprotocol.R;
import com.sdses.JniCommonInterface;

import android.support.v7.app.ActionBarActivity;
import android.R.integer;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	private static final String tag = MainActivity.class.getSimpleName();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);		
	}
	
	public long Handle;
		    
	public void OnOpenPortClick(View v) {
		EditText ETPortType=(EditText)findViewById(R.id.etPortType);	
		EditText ETPortPara=(EditText)findViewById(R.id.etPortPara);
		EditText ETExtendPara=(EditText)findViewById(R.id.etExtend);
		String PortType=ETPortType.getText().toString();
		String PortPara=ETPortPara.getText().toString();
		String ExtendPara=ETExtendPara.getText().toString();
    	//ret = JniCommonInterface.OpenDevice("COM/dev/ttyMT3", "115200", "");
    	//ret = JniCommonInterface.OpenDevice("COM/dev/ttyS4", "115200", "");
		//PortType="COM/dev/ttyMT3", PortPara="115200", ExtendPara=""
    	//Handle = JniCommonInterface.OpenDevice("USB", "261A0011", ExtendPara);
		
		if(PortType.substring(0,3).equals("usb") || PortType.substring(0,3).equals("USB"))
		{
			int Vid = Integer.parseInt(PortPara.substring(0, 4), 16);
			int Pid = Integer.parseInt(PortPara.substring(4, 8), 16);
			
			//if(Pid == 0x0C)//M05设备
			//{
			//	JniCommonInterface.SetTerminalLibrary("libTerminalProtocolM05.so");
			//}
			
			//----连接USB设备----
			long UsbPermission = JniCommonInterface.GetUsbPermission(this, Vid, Pid);
			if(UsbPermission!=0)
			{
				Toast.makeText(this, "获取USB权限失败或未插入设备",0).show();
				return;
			}			
		    Handle=JniCommonInterface.OpenDevice(PortType, PortPara, ExtendPara);	
		    //------------------ 
		}
		else
		{
			Handle=JniCommonInterface.OpenDevice(PortType, PortPara, ExtendPara);	
		}
			    
		if(Handle<0)
		{
			Toast.makeText(this, "连接设备失败，错误代码："+Handle,0).show();
			return;
		}		
		Intent intent = new Intent(getApplicationContext(),
				SecondActivity.class);
		startActivity(intent);
		Toast.makeText(this, "连接设备成功，设备句柄："+Handle,0).show();	
	}
}

