iOS蓝牙接收数据判断有效性并处理(swift版)

     // MARK: - 接收到数据,开始处理
    //代理方法
    func getData(_ data: Data!) {
        let nsdata:NSData = NSData.init(data: data);
//        MyPrint("收:\(nsdata)");
       
//        MyPrint(flag);
        let tempBytes = [UInt8](data);
        for byte in tempBytes {
            if flag != .end {
                switch flag {
                case .start:
                    currentReceivedData = [];
                    receiveTempData = [];
                    receiveheMy = 0;
                    if byte == 0xC3 {
                        flag = .head1;
//                        receiveheMy += Int(byte);
                        receiveTempData.append(byte);
                    }
                case .head1:
//                    MyPrint("0xC3")
                    if byte == 0xAA{
                        flag = .head2;
                        receiveheMy += Int(byte);
                        receiveTempData.append(byte);
                    }
                case .head2:
//                    MyPrint("0xAA")
                    length = Int(byte);
//                    MyPrint(length);
                    flag = .data;
                    receiveheMy += Int(byte);
                    receiveTempData.append(byte);
                case .data:
                    if receiveTempData.count < length + 2 {
//                        MyPrint("求和前")
                        receiveTempData.append(byte);
                        receiveheMy += Int(byte);
                    }else if receiveTempData.count < length + 3{
//                        MyPrint("求和")
                        //判断数据长度是否正确
                        receiveTempData.append(byte);
                    }else{
                        MyPrint("end");
                        flag = .end;
                        flag = .start;
                    }
                default: break
                }
            }
        }
        
        if receiveTempData.count == 0 {
            return;
        }
        //checkSum,求和校验
        if receiveheMy%256 == receiveTempData[receiveTempData.count - 1] && receiveTempData.count == length + 3 {
            currentReceivedData = receiveTempData;
              flag = .start;
            let receiveNSdata:NSData = NSData.init(bytes: currentReceivedData, length: currentReceivedData.count);
            //到这里表示收到了一条完整有效的数据
            MyPrint("收:\(receiveNSdata)");
            if currentReceivedData.count < 4{
                return;
            }

相关连接: ios蓝牙工具类oc版(附下载)

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页