How - Orange pi - Android - Доступ к последовательному порту USB - PullRequest
0 голосов
/ 28 июня 2018

Я пытаюсь получить доступ к последовательному порту на Orange Pi Android. Но я не мог видеть никакой документации. Как я могу получить доступ к последовательному порту и как я могу отправлять данные или получать данные с помощью обработчика? Версия Android должна быть 4.4.2.

Большое спасибо.

1 Ответ

0 голосов
/ 21 июля 2018

вы можете использовать такие команды оболочки, как это

public class SerialPort {

    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    public SerialPort(File device, int baudrate) throws SecurityException, IOException {

        /* Check access permission */
        if (!device.canRead() || !device.canWrite()) {
            try {
                /* Missing read/write permission, trying to chmod the file */
                Process su;
                su = Runtime.getRuntime().exec("su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n";
                String cmd2 = "stty -F " + device.getAbsolutePath() + " 9600 parenb time 1 -icrnl -ixon -isig -icanon -iexten -echo\nexit\n";

                su.getOutputStream().write(cmd.getBytes());
                su.getOutputStream().write(cmd2.getBytes());

                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new SecurityException();
            }
        }

        Process su;
        su = Runtime.getRuntime().exec("su");
        String cmd2 = "stty -F " + device.getAbsolutePath() + " 9600 parenb time 1 -icrnl -ixon -isig -icanon -iexten -echo\nexit\n";
        su.getOutputStream().write(cmd2.getBytes());
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mFileInputStream = new FileInputStream(device);
        mFileOutputStream = new FileOutputStream(device);
    }

    // Getters and setters
    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }
}

Это код получателя

public abstract class SerialPortActivity extends Activity {

protected Application mApplication;
protected SerialPort mSerialPort;
protected OutputStream mOutputStream;
private InputStream mInputStream;
private ReadThread mReadThread;
CustomConverters CusCon = new CustomConverters();
private class ReadThread extends Thread {

    @Override
    public void run() {
        super.run();
int Count=0;
int TimeOut=0;

        while (!isInterrupted() ) {
            byte[] bufferSum = new byte[256];
            byte[] buffer = new byte[128];

            int size=0;
            try {
                if (mInputStream == null) return;
                while (TimeOut < 17)
                {   try {
                    String Received="";
                    if(mInputStream.available()>0) {
                        Log.println(Log.INFO, "DLTSERIAL: ", "Received");
                        size = mInputStream.read(buffer);
                        System.arraycopy(buffer, 0, bufferSum, Count, size);
                        for (int i = 0; i < size; i++) {
                            Received = Received + "," + CusCon.BCDtoString(buffer[i]);
                        }
                        if(Arrays.asList(buffer).indexOf((byte)0x16)>-1)
                        {
                            TimeOut = 10;
                            Log.println(Log.INFO, "DLTSERIALBREAK: ", Received);

                        }
                        else
                        {
                            Log.println(Log.INFO, "DLTSERIAL: ", Received);
                        }
                        Count += size;
                        TimeOut=0;
                        Thread.sleep(10);

                    }
                } catch (Exception Ex) {}
                    TimeOut++;}
                if (Count > 0) {
                    onDataReceived(bufferSum, Count);
                }
                TimeOut=0;
          Count=0;
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }

    }
}

private void DisplayError(int resourceId) {
    AlertDialog.Builder b = new AlertDialog.Builder(this);
    b.setTitle("Error");
    b.setMessage(resourceId);
    b.setPositiveButton("OK", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            SerialPortActivity.this.finish();
        }
    });
    b.show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mApplication = new Application();
    try {
        mSerialPort = mApplication.getSerialPort();
        mOutputStream = mSerialPort.getOutputStream();
        mInputStream = mSerialPort.getInputStream();

        /* Create a receiving thread */
        mReadThread = new ReadThread();
        mReadThread.start();
    } catch (SecurityException e) {
        Log.println(Log.DEBUG, "DEBUG:", e.toString());
    } catch (IOException e) {
        Log.println(Log.DEBUG, "DEBUG:", e.toString());
    } catch (InvalidParameterException e) {
        Log.println(Log.DEBUG, "DEBUG:", e.toString());
    }
}

protected abstract void onDataReceived(final byte[] buffer, final int size);

@Override
protected void onDestroy() {
    if (mReadThread != null) mReadThread.interrupt();
    mApplication.closeSerialPort();
    mSerialPort = null;
    super.onDestroy();
}

}

...