EMDK串行通信找不到端口

时间:2019-06-24 18:27:55

标签: android serial-port motorola-emdk

我正在尝试创建一个Android活动,该活动通过串行端口发送数据作为产品测试。我有一些用于执行此操作的代码,到目前为止,该代码在我的设备上找不到任何肯定具有串行端口的串行端口。我打算将此活动与设备串行端口上的回送连接器一起使用,以验证读取和写入功能。我已经尝试了以下两个程序:

import android.app.Activity;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKManager.EMDKListener;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.serialcomm.SerialComm;
import com.symbol.emdk.serialcomm.SerialCommException;
import com.symbol.emdk.serialcomm.SerialCommManager;
import com.symbol.emdk.serialcomm.SerialCommResults;
import com.symbol.emdk.serialcomm.SerialPortInfo;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;

public class SerialTry3 extends Activity implements EMDKListener{


    private String TAG = SerialTry3.class.getSimpleName();
    private EMDKManager emdkManager = null;
    private SerialComm serialCommPort = null;
    private SerialCommManager serialCommManager = null;
    private EditText txtDataToSend = null;
    private TextView txtStatus = null;
    private Button btnRead = null;
    private Button btnWrite = null;
    private Spinner spinnerPorts = null;
    public HashMap<String, SerialPortInfo> supportedPorts = null;


    @Override @SuppressWarnings("SetTextI18n")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.serial_try);

        txtDataToSend = (EditText) findViewById(R.id.txtDataToSend);
        txtDataToSend.setText("Serial Communication Write Data Testing.");

        spinnerPorts = (Spinner)findViewById(R.id.spinnerPorts);
        btnWrite = (Button) findViewById(R.id.btnWrite);
        btnRead = (Button) findViewById(R.id.btnRead);

        txtStatus = (TextView) findViewById(R.id.statusView);
        txtStatus.setText("");
        txtStatus.requestFocus();


        EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
        if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
            new AsyncStatusUpdate().execute("EMDKManager object request failed!");
        }

        new AsyncUiControlUpdate().execute(false);
    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManager = emdkManager;

        Log.d(TAG, "EMDK opened");

        try{
            serialCommManager = (SerialCommManager) this.emdkManager.getInstance(FEATURE_TYPE.SERIALCOMM_EX);
            if(serialCommManager != null) {
                populatePorts();
            }
            else
            {
                new AsyncStatusUpdate().execute(FEATURE_TYPE.SERIALCOMM_EX.toString() +  " Feature not supported.");
            }
        }
        catch(Exception e)
        {
            Log.d(TAG, e.getMessage());
            new AsyncStatusUpdate().execute(e.getMessage());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.splash_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        deinitSerialComm();

        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        deinitSerialComm();

        serialCommManager = null;
        supportedPorts = null;
        // Release the serialComm manager resources
        if (emdkManager != null) {
            emdkManager.release(FEATURE_TYPE.SERIALCOMM_EX);
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        // Acquire the serialComm manager resources
        if (emdkManager != null) {
            serialCommManager = (SerialCommManager) emdkManager.getInstance(FEATURE_TYPE.SERIALCOMM_EX);

            if (serialCommManager != null) {
                populatePorts();
                if (supportedPorts != null)
                    initSerialComm();
            }
        }


    }


    void populatePorts()
    {
        try {

            if(serialCommManager != null) {
                List<SerialPortInfo> serialPorts = serialCommManager.getSupportedPorts();
                if(serialPorts.size()>0) {
                    supportedPorts = new HashMap<String, SerialPortInfo> ();
                    String[] ports = new String[serialPorts.size()];
                    int count = 0;
                    for (SerialPortInfo info : serialPorts) {
                        supportedPorts.put(info.getFriendlyName(), info);
                        ports[count] = info.getFriendlyName();
                        count++;
                    }

                    spinnerPorts.setAdapter(new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_dropdown_item, ports));

                    spinnerPorts.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                            //Disabling previous serial port before getting the new one
                            deinitSerialComm();
                            initSerialComm();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> adapterView) {

                        }
                    });

                }
                else
                {
                    new AsyncStatusUpdate().execute("Failed to get available ports");
                    Toast.makeText(this, "Failed to get available ports, serial communication may not be supported.", Toast.LENGTH_LONG).show();
                    finish();
                }
            }
            else
            {
                new AsyncStatusUpdate().execute("SerialCommManager is null");
            }

        }
        catch (Exception ex)
        {
            Log.d(TAG, ex.getMessage());
            new AsyncStatusUpdate().execute(ex.getMessage());
        }
    }



    void initSerialComm() {
        new AsyncEnableSerialComm().execute(supportedPorts.get(spinnerPorts.getSelectedItem()));
    }

    @Override
    public void onClosed() {

        if(emdkManager != null) {
            emdkManager.release();
        }
        new AsyncStatusUpdate().execute("EMDK closed unexpectedly! Please close and restart the application.");
    }


    public void btnReadOnClick(View arg)
    {
        new AsyncReadData().execute();
    }

    public void btnWriteOnClick(View arg)
    {
        new AsyncUiControlUpdate().execute(false);
        try {
            String writeData = txtDataToSend.getText().toString();
            int bytesWritten = serialCommPort.write(writeData.getBytes(), writeData.getBytes().length);
            new AsyncStatusUpdate().execute("Bytes written: "+ bytesWritten);

        } catch (SerialCommException e) {
            new AsyncStatusUpdate().execute("write: "+ e.getResult().getDescription());
        }
        catch (Exception e) {
            new AsyncStatusUpdate().execute("write: "+ e.getMessage() + "\n");
        }
        new AsyncUiControlUpdate().execute(true);
    }


    void deinitSerialComm() {

        if (serialCommPort != null) {
            try {

                serialCommPort.disable();
                serialCommPort = null;

            } catch (Exception ex) {
                Log.d(TAG, "deinitSerialComm disable Exception: " + ex.getMessage());
            }
        }
    }

    @SuppressWarnings("StaticFieldLeak")
    private class AsyncStatusUpdate extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            return params[0];
        }

        @Override
        protected void onPostExecute(String result) {

            txtStatus.setText(result);

        }
    }

    @SuppressWarnings("StaticFieldLeak")
    private class AsyncUiControlUpdate extends AsyncTask<Boolean, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Boolean... arg0) {

            return arg0[0];
        }

        @Override
        protected void onPostExecute(Boolean bEnable) {

            btnRead.setEnabled(bEnable);
            btnWrite.setEnabled(bEnable);
            txtDataToSend.setEnabled(bEnable);
            spinnerPorts.setEnabled(bEnable);
        }
    }

    @SuppressWarnings("StaticFieldLeak")
    private class AsyncEnableSerialComm extends AsyncTask<SerialPortInfo, Void, SerialCommResults>
    {
        @Override
        protected SerialCommResults doInBackground(SerialPortInfo... params) {

            SerialCommResults returnvar = SerialCommResults.FAILURE;
            try {
                serialCommPort = serialCommManager.getPort(params[0]);

            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if (serialCommPort != null) {
                try {
                    serialCommPort.enable();
                    returnvar = SerialCommResults.SUCCESS;

                } catch (SerialCommException e) {
                    Log.d(TAG, e.getMessage());
                    e.printStackTrace();
                    returnvar = e.getResult();
                }
            }

            return returnvar;
        }

        @Override @SuppressWarnings("SetTextI18n")
        protected void onPostExecute(SerialCommResults result) {
            super.onPostExecute(result);
            if (result == SerialCommResults.SUCCESS) {
                new AsyncStatusUpdate().execute("Serial comm channel enabled: (" + spinnerPorts.getSelectedItem().toString() + ")");
                txtDataToSend.setText("Serial Communication Write Data Testing " + spinnerPorts.getSelectedItem().toString() + ".");
                new AsyncUiControlUpdate().execute(true);
            } else {
                new AsyncStatusUpdate().execute(result.getDescription());
                new AsyncUiControlUpdate().execute(false);
            }
        }
    }

    @SuppressWarnings("StaticFieldLeak")
    private class AsyncReadData extends AsyncTask<Void, Void, String>
    {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            new AsyncUiControlUpdate().execute(false);
            new AsyncStatusUpdate().execute("Reading..");
        }

        @Override
        protected String doInBackground(Void... params) {
            String statusText = "";
            try {

                byte[] readBuffer = serialCommPort.read(10000); //Timeout after 10 seconds

                if (readBuffer != null) {
                    String tempString = new String(readBuffer);
                    statusText = "Data Read:\n" + tempString;
                } else {
                    statusText = "No Data Available";
                }

            } catch (SerialCommException e) {
                statusText = "read:" + e.getResult().getDescription();
            } catch (Exception e) {
                statusText = "read:" + e.getMessage();
            }
            return statusText;
        }

        @Override
        protected void onPostExecute(String statusText) {
            super.onPostExecute(statusText);
            new AsyncUiControlUpdate().execute(true);
            new AsyncStatusUpdate().execute(statusText);
        }

    }
}

import android.app.Activity;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKManager.FEATURE_TYPE;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.serialcomm.SerialComm;
import com.symbol.emdk.serialcomm.SerialCommException;

import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.symbol.emdk.serialcomm.SerialCommManager;
import com.symbol.emdk.serialcomm.SerialPortInfo;

import java.util.List;

public class SerialTry extends Activity implements EMDKManager.EMDKListener {
    private String TAG = SerialTry.class.getSimpleName();
    private EMDKManager emdkManager = null;
    private SerialComm serialComm = null;
    private SerialCommManager serialCommMan = null;

    private EditText editText = null;
    private TextView statusView = null;
    private Button readButton = null;
    private Button writeButton = null;

    @Override @SuppressWarnings("SetTextI18n")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.serial_try);

        editText = (EditText) findViewById(R.id.editText1);
        editText.setText("Serial Communication Write Data Testing.");

        statusView = (TextView) findViewById(R.id.statusView);
        statusView.setText("");
        statusView.requestFocus();


        EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), this);
        if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
            statusView.setText("Failed to open EMDK");
        } else {
            statusView.setText("Opening EMDK...");
        }


        //

        // Get the serialComm/port object by passing a SerialPortInfo object:
        addReadButtonEvents();
        writeButtonEvents();
        setEnabled(false);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.splash_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (emdkManager != null) {
            emdkManager.release();
            emdkManager = null;
        }
    }

    @Override
    public void onOpened(EMDKManager emdkManager) {
        this.emdkManager = emdkManager;

        Log.d(TAG, "EMDK opened");

        try{
            serialCommMan = (SerialCommManager) this.emdkManager.getInstance(EMDKManager.FEATURE_TYPE.SERIALCOMM_EX);

            List<SerialPortInfo> serialPorts = serialCommMan.getSupportedPorts();
            serialComm = serialCommMan.getPort(serialPorts.get(0));
            System.out.println("Supported Ports::::::" + serialPorts);
            Thread readThread = new Thread(new Runnable() {
                @Override
                public void run() {

                    String statusText;
                    if (serialComm != null) {
                        try{
                            serialComm.enable();
                            statusText = "Serial comm channel enabled";

                            setEnabled(true);

                        } catch(SerialCommException e){
                            Log.d(TAG, e.getMessage());
                            e.printStackTrace();
                            statusText = e.getMessage();
                            setEnabled(false);
                        }
                    } else {
                        statusText = FEATURE_TYPE.SERIALCOMM_EX.toString() + " Feature not supported or initilization error.";
                        setEnabled(false);
                    }
                    displayMessage(statusText);
                }

            });
            readThread.start();
        }
        catch(Exception e)
        {
            Log.d(TAG, e.getMessage());

            e.printStackTrace();

            displayMessage(e.getMessage());
        }
    }

    @Override
    public void onClosed() {
        if(emdkManager != null) {
            emdkManager.release();
        }
        displayMessage("EMDK closed abruptly.");
    }

    private void addReadButtonEvents() {
        readButton = (Button) findViewById(R.id.btnRead);
        readButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Thread readThread = new Thread(new Runnable() {
                    @Override
                    public void run() {

                        setEnabled(false);
                        String statusText;
                        try {

                            byte[] readBuffer = serialComm.read(10000); //Timeout after 10 seconds

                            if(readBuffer != null) {
                                String tempString = new String(readBuffer);
                                statusText = "Data Read:\n" + tempString;
                            } else {
                                statusText = "No Data Available";
                            }

                        }catch (SerialCommException e) {
                            statusText ="read:"+ e.getResult().getDescription();
                            e.printStackTrace();
                        }
                        catch (Exception e) {
                            statusText = "read:"+ e.getMessage();
                            e.printStackTrace();
                        }
                        setEnabled(true);
                        displayMessage(statusText);
                    }
                });
                readThread.start();
            }
        });
    }

    @SuppressWarnings("SetTextI18n")
    private void writeButtonEvents() {
        writeButton = (Button) findViewById(R.id.btnWrite);

        writeButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setEnabled(false);
                try {
                    String writeData = editText.getText().toString();
                    int bytesWritten = serialComm.write(writeData.getBytes(), writeData.getBytes().length);
                    statusView.setText("Bytes written: "+ bytesWritten);
                } catch (SerialCommException e) {
                    statusView.setText("write: "+ e.getResult().getDescription());
                }
                catch (Exception e) {
                    statusView.setText("write: "+ e.getMessage() + "\n");
                }
                setEnabled(true);
            }
        });
    }

    @SuppressWarnings("SetTextI18n")
    void displayMessage(String message) {

        final String tempMessage = message;
        runOnUiThread(new Runnable() {
            public void run() {
                statusView.setText(tempMessage + "\n");
            }
        });
    }

    void setEnabled(boolean enableState) {

        final boolean tempState = enableState;
        runOnUiThread(new Runnable() {
            public void run() {
                readButton.setEnabled(tempState);
                writeButton.setEnabled(tempState);
                editText.setEnabled(tempState);
            }
        });
    }


}

问题似乎出在我的代码上,还是我对设备本身不了解?任何帮助,将不胜感激。谢谢您的宝贵时间。

0 个答案:

没有答案