串口通信

关于android单片机串口通信

网上有很多关于android串口读写的结果,但是搜出来的都不太让我满意 ,下面贴出我写的SerialPortUtils类的代码:

  public class SerialPortUtils {
    private static SerialPortUtils serialPortUtils = null;
    private SerialPort serialPort;
    private InputStream inputStream;
    private OutputStream outputStream;
    private SCMDataReceiveListener SCMDataReceiveListener;
    private ReadThread readThread;

    private byte[] mData = null;
    private TimerThread timerThread;
    //超时时间(超时检测线程是每次休眠固定时间,通过休眠次数来判断超时)
    private int TimeOut=3000;
    private int timeOutCount = 0;//timeOutCount=TimeOut/sleepTime
    //超时线程睡眠时间
    private int sleepTime=50;
    //休眠次数
    private int sleepCount = 0;

    public static SerialPortUtils getInstance() {
        if (serialPortUtils == null) {
            serialPortUtils = new SerialPortUtils();
        }
        return serialPortUtils;
    }

    public void setSCMDataReceiveListener(SCMDataReceiveListener SCMDataReceiveListener) {
        this.SCMDataReceiveListener = SCMDataReceiveListener;
    }

    public void openSerialPort() {
        try {
            String PORT_PATH = "/dev/ttyUSB0";
            int BAUD_RATE = 9600;
            serialPort = new SerialPort(new File(PORT_PATH), BAUD_RATE, 0);
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
            if (timerThread == null) {
                MyApp.getInstance().isReceived=true;
                timerThread = new TimerThread();
                timerThread.setName("TIMER THREAD");
                timerThread.setPriority(1);
                timerThread.start();
            }
            setTomeOut(TimeOut);
        } catch (IOException e) {
            Log.e("open serial log",e.getMessage());
            e.printStackTrace();
        }
    }

    public void setThreadStatus(boolean status){
        if(status){
        }
    }

    public void closeSerialPort() {

        try {
            try {
                inputStream.close();
                outputStream.close();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            serialPort.close();
        } catch (IOException e) {
            Log.e("close log",e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 启动线程接收数据
     */
    public void readReceivedData() {
        if (inputStream == null) {
            return;
        }
        Log.i("zy", "线程进行中" + inputStream.toString());
        if (readThread == null) {
            readThread = new ReadThread();
            readThread.setName("READ THREAD");
            readThread.setPriority(1);
            readThread.start();
        }
    }


    public void sendDataToSerialPort(byte[] data) {
        mData = data;
        if (serialPort == null) {
            openSerialPort();
        }
        try {

            if (data != null) {
                int dataLength = data.length;
                Log.e("DATASIZE", String.valueOf(dataLength));

                if (dataLength > 0) {
                    outputStream.write(data);
                    outputStream.flush();
                    sleepCount=0;
                    MyApp.getInstance().isReceived = false;
                    Log.e("timerThred status",timerThread.isAlive()?"isAlive":"noAlive");
                    Log.e("readThread status",readThread.isAlive()?"isAlive":"noAlive");
                }
            }

        } catch (IOException e) {
            Log.e("send log",e.getMessage());
            e.printStackTrace();
        }
    }

    //设置超时时间
    private void setTomeOut(long mesc) {
        //超时检测线程是每次休眠固定时间,通过休眠次数来判断超时
        timeOutCount = (int) (mesc / sleepTime);
    }


    /**
     * 判断是否超时的线程
     */
    private class TimerThread extends Thread {
        @Override
        public void run() {
            while (MyApp.getInstance().isStart) {
                try {
                    sleep(sleepTime);
                    if (!MyApp.getInstance().isReceived && MyApp.getInstance().sendDataCount <= 10) {
                        if (sleepCount > timeOutCount) {//超时
                            ParseProtocolUtils.setStatusData("重发第"+MyApp.getInstance().sendDataCount+"次");
                            Log.e("test data resend","重发第"+MyApp.getInstance().sendDataCount+"次");
                            Log.e("status",(timerThread.isInterrupted() ?"true":"false")+","+(readThread.isInterrupted() ?"true":"false"));
                            MyApp.getInstance().sendDataCount++;
                            sendDataToSerialPort(mData);
                        } else {
                            sleepCount++;
                        }
                    }else {
                        sleepCount=0;
                        if(MyApp.getInstance().sendDataCount>10){
                        }
                    }
                } catch (Exception e) {
                    Log.e("timer log",e.getMessage());
                    e.printStackTrace();
                }


            }
        }
    }


    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            // 定义一个包的最大长度
            int maxLength = 215;
            byte[] buffer = new byte[maxLength];
            // 每次收到实际长度
            int available = 0;
            // 当前已经收到包的总长度
            int currentLength = 0;
            // 协议头长度(帧头、命令字、数据长度)
            int headerLength = 5;
            //校验位
            int checkBitLength=1;

            while (!isInterrupted()) {
                try {
                    available = inputStream.available();
                    if (available > 0) {
                        // 防止超出数组最大长度导致溢出
                        if (available > maxLength - currentLength) {
                            available = maxLength - currentLength;
                        }
                        inputStream.read(buffer, currentLength, available);
                        currentLength += available;
                    }

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

                int cursor = 0;
                // 如果当前收到包大于头的长度,则解析当前包
                while (currentLength >= headerLength) {
                    // 取到头部第一个字节
                    if (buffer[cursor] != intToByte(0xaa)&&buffer[cursor] != intToByte(0x55)) {
                        if(buffer[cursor+1]!=intToByte(0x75)){
                            --currentLength;
                            ++cursor;
                            continue;
                        }
                    }

                    int contentLenght = parseLen(buffer, cursor, headerLength);
                    // 如果内容包的长度大于最大内容长度或者小于等于0,则说明这个包有问题,丢弃
                    if (contentLenght <= 0 || contentLenght > maxLength - headerLength-checkBitLength) {
                        currentLength = 0;
                        break;
                    }
                    // 如果当前获取到长度小于整个包的长度,则跳出循环等待继续接收数据
                    int factPackLen = contentLenght + headerLength+checkBitLength;
                    if (currentLength < contentLenght + headerLength+checkBitLength) {
                        break;
                    }

                    // 一个完整包即产生
                    MyApp.getInstance().isStart=true;
                    MyApp.getInstance().isReceived = true;
                    MyApp.getInstance().sendDataCount = 1;
                    SCMDataReceiveListener.dataRecevie(buffer, cursor, factPackLen);
                    currentLength -= factPackLen;
                    cursor += factPackLen;
                }
                // 残留字节移到缓冲区首
                if (currentLength > 0 && cursor > 0) {
                    System.arraycopy(buffer, cursor, buffer, 0, currentLength);
                }
            }
        }
    }
    public  byte intToByte(int x) {
        return (byte) x;
    }

    /**
     * 获取协议内容长度
     */
    public int parseLen(byte buffer[], int index, int headerLength) {

        int rlt=buffer[3]*200+buffer[4];
        return rlt;
    }

    public interface SCMDataReceiveListener {

        void dataRecevie(byte[] str,int cursor, int size);
    }
}

我这里做的有超时重发的功能,但是总感觉这样做不怎么好,因为线程一直在运行太消耗性能了,但是又不知道其他方法做出来超时重发的效果,希望广大网友可以提出宝贵的意见,谢谢。

恭喜IG夺冠 哈哈哈哈

后记:
忘了说了,上面接收数据的byte数组在接收到超过127的数字的时候会变成负数,至于原因随便百度就知道了,转换的时候需要特别注意下

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容