美文网首页
2021-07-23 uart api 代码

2021-07-23 uart api 代码

作者: fjasmin | 来源:发表于2021-07-23 10:35 被阅读0次

UartCommImpl

public class UartCommImpl{
    static final String TAG = "UartComm";
    HashMap<Integer, SerialPort> mSerialPorts = new HashMap<Integer, SerialPort>(6);

    static {
        System.loadLibrary("SerialAPIForSystem");
    }

    public native int native_uartInit(String device);
    public int uartInit(String device) {
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > 19) {
            try {
                SerialPort tmp = new SerialPort(new File(device), 9600, 0);
                for (int i = 0; i < 6; i++) {
                    String str = "/dev/ttyS" + i;
                    String str1 = "/dev/ttyXRUSB" + i;
                    String str2 = "/dev/ttysWK" + i;
                    String str3 = "/dev/ttyUSB" + i;
                        if (str.equals(device) || str1.equals(device) || str2.equals(device) || str3.equals(device)) {
                            mSerialPorts.put(i, tmp);
                            return i;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return -1;
        } else
            return native_uartInit(device);
    }


    private native int native_uartDestroy(int fd);
    public int uartDestroy(int fd) {
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > 19) {
            SerialPort tmp = mSerialPorts.get(fd);
            if (tmp == null)
                return -1;
            tmp.close();
            mSerialPorts.remove(fd);
            return 0;
        } else
            return native_uartDestroy(fd);
    }


    private native int native_setOpt(int fd, int baud, int dataBits, int parity, int stopBits);

    public int setOpt(int fd, int baud, int dataBits, int parity, int stopBits) {

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;

        if (currentapiVersion > 19) {
            try {
                SerialPort tmp = mSerialPorts.get(fd);
                if (tmp == null)
                    return -1;
                return tmp.setOpt(baud, dataBits, parity, stopBits, 0);
            } catch (Exception e) {
                return -1;
            }
        } else
            return native_setOpt(fd, baud, dataBits, parity, stopBits);
    }


    private native int native_send(int fd, int[] val, int length);
    public int send(int fd, int[] val, int length) {
        //android6.0
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > 19) {
            byte data[] = new byte[length];
            for (int i = 0; i < length; i++) {
                data[i] = (byte) (val[i] & 0xff);
            }
            try {
                SerialPort tmp = mSerialPorts.get(fd);
                if (tmp == null)
                    return -1;
                tmp.getOutputStream().write(data);
                return length;
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        } else
            return native_send(fd, val, length);
    }


    private native int native_recv(int fd, int[] val, int length);
    public int recv(int fd, int[] val, int length) {
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;

        if (currentapiVersion > 19) {
            byte data[] = new byte[length];
            try {
                SerialPort tmp = mSerialPorts.get(fd);
                if (tmp == null)
                    return -1;
                int size = tmp.getInputStream().read(data);

                for (int i = 0; i < size; i++) {
                    val[i] = (data[i] & 0xff);
                }
                return size;
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
        } else
            return native_recv(fd, val, length);
    }


    private native int native_recvWithTimeOut(int fd, int[] val, int length, int ms);
    public int recvWithTimeOut(int fd, int[] val, int length, int ms) {
        int timeOutCnt = 0;
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > 19) {
            while (true) {
                byte data[] = new byte[length];
                try {
                    SerialPort tmp = mSerialPorts.get(fd);
                    if (tmp == null)
                        return -1;
                    int canRead = tmp.getInputStream().available();
                    if (canRead < length) {
                        Thread.sleep(10);
                        timeOutCnt++;
                        if (timeOutCnt * 10 > ms) {
                            if (canRead > 0) {
                                return recv(fd, val, length);
                            }
                            return 0;
                        }
                    } else
                        return recv(fd, val, length);
                } catch (IOException e) {
                    e.printStackTrace();
                    return -1;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } else
            return native_recvWithTimeOut(fd, val, length, ms);
    }


    private native int native_setRS485WriteRead(int writeRead);
    public int setRS485WriteRead(int writeRead){
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > 19) {
            return 0;
        }
        else
            return native_setRS485WriteRead(writeRead);
    }

    public class Rs485 {
        private int fd;

        private native boolean native_rs485Init();
        public boolean rs485Init() {
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentapiVersion > 19) {
                fd = UartCommImpl.this.uartInit("/dev/ttyS3");
                if (fd < 0) {
                    Log.e(TAG, "rs485Init error ");
                    return false;
                }
                UartCommImpl.this.setOpt(fd, 9600, 8, 0, 0);
                return true;
            } else {
                native_rs485Init();
                return true;
            }
        }


        private native void native_rs485Destroy();
        public void rs485Destroy() {
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentapiVersion > 19)
                UartCommImpl.this.uartDestroy(fd);
            else
                native_rs485Destroy();
        }


        private native int native_rs485GetBoardAddress(int addrnum, int maxAddr, int[] retInfo);
        public int rs485GetBoardAddress(int addrnum, int maxAddr, int[] retInfo) {
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            int ret,i,boardIndex;
            int xwdata[] = { 0X81,0X01,0x01,0x99,0x19};
            int xrdata[] = new int[5];
            int buf[] = new int[5];
            boardIndex = 0;
            if (currentapiVersion > 19) {
                for(i=0; i<maxAddr; i++) {
                    xwdata[1] = i;
                    xwdata[4] = (xwdata[0] ^ xwdata[1] ^ xwdata[2] ^ xwdata[3]) & 0xff;
                    ret = UartCommImpl.this.send(fd, xwdata, 5);
                    if (ret < 0) {
                        Log.e(TAG, "rs485GetBoardAddress send error ");
                        return -1;
                    }
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ret = UartCommImpl.this.recvWithTimeOut(fd, xrdata, 5,1500);
                    if (ret < 0) {
                        Log.e(TAG, "rs485GetBoardAddress recv error ");
                        return -1;
                    }
                    if(ret != 0 && (xrdata[0] == 0x81) &&
                            ((xrdata[0]^xrdata[1]^xrdata[2]^xrdata[3]^xrdata[4]) == 0x0)) {
                        buf[boardIndex] = xrdata[1];
                        boardIndex++;
                        if (boardIndex >= addrnum){
                            int size = retInfo.length<5?retInfo.length:5;
                            for(i=0; i < size; i++)
                                retInfo[i] = buf[i];
                            return boardIndex;
                        }
                    }
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int size = retInfo.length<5?retInfo.length:5;
                for(i=0; i < size; i++)
                    retInfo[i] = buf[i];
                return boardIndex;
            } else
                return native_rs485OpenGrid(addrnum,maxAddr,retInfo);
        }




        private native int native_rs485OpenGrid(int boardID, int doorID, int[] retInfo);
        public int rs485OpenGrid(int boardID, int doorID, int[] retInfo) {
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            int ret,len,i;
            int xwdata[] = {0X8A, boardID, doorID, 0x11,0x00};
            int xrdata[] = new int[5];

            if (currentapiVersion > 19) {
                xwdata[4] = (xwdata[0] ^ xwdata[1] ^ xwdata[2] ^ xwdata[3]) & 0xff;
                ret = UartCommImpl.this.send(fd,xwdata,5);

                if(ret < 0){
                    Log.e(TAG, "send error");
                    return -1;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ret = UartCommImpl.this.recvWithTimeOut(fd,xrdata,5,1500);
                if(ret < 0){
                    Log.e(TAG, "recv error");
                    return -1;
                }
                if(xrdata == null)
                    return 0;
                else
                {
                    for(i=0;i<5;i++)
                        retInfo[i] = xrdata[i];
                }
                return 0;
            } else
                return native_rs485OpenGrid(boardID,doorID,retInfo);
        }


        private native int native_rs485GetDoorState(int boardID, int doorID, int[] retInfo);
        public int rs485GetDoorState(int boardID, int doorID, int[] retInfo) {
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            int len,ret;
            if (currentapiVersion > 19) {
                int xwdata[] = {0X80,boardID,doorID,0x33,0x00};
                xwdata[4] = (xwdata[0] ^ xwdata[1] ^ xwdata[2] ^ xwdata[3]) & 0xff;
                ret = UartCommImpl.this.send(fd,xwdata,5);
                if(ret < 0){
                    return -1;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(doorID == 0)
                    len = 7;
                else
                    len = 5;
                ret = UartCommImpl.this.recvWithTimeOut(fd,retInfo,len,1500);
                if(ret < 0){
                    return -1;
                }
                return 0;
            } else
                return native_rs485GetDoorState(boardID,doorID,retInfo);
        }


        private native int native_rs485GetProtocalID(int boardID, int[] retInfo);
        public int rs485GetProtocalID(int boardID, int[] retInfo) {
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            int ret;
            if (currentapiVersion > 19) {
                int xwdata[] = {0X91,0X0,0xfe,0xfe ,0x6f};
                xwdata[1] = boardID;
                xwdata[4] = (xwdata[0] ^ xwdata[1] ^ xwdata[2] ^ xwdata[3]) & 0xff;
                ret = UartCommImpl.this.send(fd,xwdata,5);
                if(ret < 0){
                    return -1;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ret = UartCommImpl.this.recvWithTimeOut(fd,retInfo,5,1500);
                if(ret < 0){
                    return -1;
                }
                return 0;
            } else
                return native_rs485GetProtocalID(boardID, retInfo);
        }
    }
}

UartComm

public class UartComm {

    static final String TAG = "UartComm";
    UartCommImpl mUartCommImpl = null;

    public UartComm() {
        mUartCommImpl = new UartCommImpl();
    }

    /*
     * 初始化串口 device为需要打开串口的名字,如/dev/ttyS1 /dev/ttyS3. RS485固定为/dev/ttyS3
     * 返回值: 所打开文件句柄
     * */
    public int uartInit(String device) {
        return mUartCommImpl.uartInit(device);
    }

    /*
     * 释放串口资源
     * fd: 需要释放资源串口的句柄,由uartInit()函数返回
     * */
    public int uartDestroy(int fd) {
        return mUartCommImpl.uartDestroy(fd);
    }

    /*
     * 设置串口属性
     *  fd: 所设置串口的句柄,由uartInit()函数返回
     * baud: 波特率 值为2400/4800/9600/19200/38400/57600/115400
     * dataBits:数据位数  5/6/7/8
     * parity: 校验
     *      0: 无校验
     *      1: 奇校验
     *      2:  偶校验
     * stopBits:停止位 1/2
     * 如setOPt(9600,8,0,1)为设置9600波特率, 8N1属性
     */
    public int setOpt(int fd, int baud, int dataBits, int parity, int stopBits) {
        return mUartCommImpl.setOpt(fd, baud, dataBits, parity, stopBits);
    }

    /**
     * 把数据发送出去
     * fd: 需要发送数据串口的句柄, 由uartInit()函数返回12
     * byteBuf:数据缓冲
     * length: 要发送数据的长度
     */
    public int send(int fd, int[] val, int length) {
        return mUartCommImpl.send(fd, val, length);
    }

    /**
     * 读取串口数据
     * fd: 需要接收数据串口的句柄, 由uartInit()函数返回
     * byteBuf: 数据缓冲
     * length: 要读取的数据长度
     * return : int
     */
    public int recv(int fd, int[] val, int length) {
        return mUartCommImpl.recv(fd, val, length);
    }

    public int recvWithTimeOut(int fd, int[] val, int length, int ms) {
        return mUartCommImpl.recvWithTimeOut(fd, val, length, ms);
    }
}

SerialPort

public class SerialPort {

    private static final String TAG = "SerialPort";

    /*
     * Do not remove or rename the field mFd: it is used by native method close();
     */
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

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

        /* Check access permission */
        /*if (!device.canRead() || !device.canWrite()) {
            try {

                Process su;
                su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n"
                        + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead()
                        || !device.canWrite()) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new SecurityException();
            }
        }*/

        mFd = open(device.getAbsolutePath(), baudrate, flags);
        if (mFd == null) {
            Log.e(TAG, "native open returns null");
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

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

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    public native int setOpt(int baudrate, int dataBits, int parity, int stopBits, int isCTSRTS);

    // JNI
    private native static FileDescriptor open(String path, int baudrate, int flags);

    public native void close();
}

相关文章

  • 2021-07-23 uart api 代码

    UartCommImpl UartComm SerialPort

  • UART接口

    认识UART接口UART详解---简单的讲:(UART与COM) 嵌入式里面说的串口,一般是指UART口, 但是我...

  • GPIO 模拟Uart 通信 (soft uart/serial

    GPIO 模拟Uart 通信 (soft uart/serial) 在Uart不够用的时候可以通过GPIO 来模拟...

  • pcDuino3使能多串口

    pcDuino3标准的接口中只提供了UART0和UART2,UART0作为默认系统debug口使用,UART2定义...

  • 2018-07-23~29周目标

    工作: 1.uart驱动代码走查。 2.SPI代码走查。 3.弄懂JFLASH使用方法:读完文档,原理验证。 4....

  • 12.12每日总结

    今天我们学习的是UART,UART是异步串行通讯,他是PYB里边的类from pyb import UART,下午...

  • Raspberry UARTs

    相比树莓派零、1、2 以及 3 的双串口 UART0(PL011)和 UART1(mini UART),树莓派4 ...

  • 简单介绍两款UART接口的WiFi模块

    UART接口 UART接口是通用的异步串行接口,按照标准波特率完成双向通讯,传输速度较慢。采用UART接口,WiF...

  • 2017 .12.12

    今天上午学习了Uart串行异步通信 UART.any() # 返回缓冲区中接收的字符数 UART.read([nb...

  • 2017-12-12

    今天我们黄老师为我们讲解了UART 通用异步串行通信,UART--通用异步串行通信接口的总称,UART允许在串行链...

网友评论

      本文标题:2021-07-23 uart api 代码

      本文链接:https://www.haomeiwen.com/subject/drbumltx.html