蓝牙发送数据和接收数据

2019-04-17  本文已影响0人  金卡戴珊ugly

蓝牙通信代码片段记录

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MassageFragment extends BaseBleFragment {
    private int selectPosition=5;//选中档位默认5
    private String addressDev;
    boolean openOrClose = false;
    private boolean isOpenClicked;//用作设备无响应提示
    private OpenBleHelper mOpenBleHelper;

    private static MyUIHandler mUIHandler;

    private static class MyUIHandler extends UIHandler<MassageFragment> {
        MyUIHandler(MassageFragment cls) {
            super(cls);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MassageFragment activity = ref.get();
            if (activity != null) {
                if (activity.getActivity()!=null&&activity.getActivity().isFinishing()) return;
                switch (msg.what) {
                    case 0:
                        //8秒后,未搜索到设备,重试
                        if(!LinkState.getInstance().getState()){
                            BluetoothLeService.ME.close();
                            activity.bleModel.connectDevice(activity.addressDev);
                        }
                        break;
                    case 1:
                        activity.initBleComponent(activity.addressDev);//用于写数据
                        break;
                }
            }
        }
    }

    @Override
    protected void initView(View view) {
        listenBroadcastBle();//监听蓝牙状态切换,重新连接蓝牙设备
        if(getArguments()!=null){//获取蓝牙data
            String bleData = getArguments().getString("bleData");
            addressDev = getArguments().getString("addressDev");
            if(bleData !=null && addressDev!=null){
                showData(bleData);
                mUIHandler.sendEmptyMessageDelayed(1,500);//延迟500毫秒
            } else {//此时是,有缓存的情况。在此我们判断蓝牙状态,开启服务,根据缓存的address,连接设备
                addressDev = SharePerferenceHelper.createSharePerference("private").getString("address","");
                initBleComponent(addressDev);//用于写数据
                if (mOpenBleHelper.isBleEnable()) {
                    bleModel.connectDevice(addressDev);
                    mUIHandler.sendEmptyMessageDelayed(0,8*1000);//8秒后重试
                }
            }
        }
        WaveView_top_left.setDrawProcessText(false);
        WaveView_top_right.setDrawProcessText(false);
        WaveView_bottom_left.setDrawProcessText(false);
        WaveView_bottom_right.setDrawProcessText(false);

        //取缓存的档位设置到控件中
        int degreeProgress = SharePerferenceHelper.createSharePerference("private").getInt("massageDegree",5);
        seekBar.setProgress(degreeProgress);
        seekBar.setEnabled(false);
    }

    private void listenBroadcastBle() {
        mOpenBleHelper = new OpenBleHelper(getActivity());
        if (!mOpenBleHelper.isBleEnable()) {
            mOpenBleHelper.setListener(bleStatusChangedListener);
        }
    }

    OpenBleHelper.OnBleStatusChangedListener bleStatusChangedListener = new OpenBleHelper.OnBleStatusChangedListener() {
        @Override
        public void onBleOpened() {
            mOpenBleHelper.setListener(null);
            bleModel.connectDevice(addressDev);//连接蓝牙设备
            mUIHandler.sendEmptyMessageDelayed(0,8*1000);//8秒后重试
        }
        @Override
        public void onBleClosed() {
            toast(getStringByResource(R.string.not_check_ble_open));
        }
        @Override
        public void onUnSupportBle() {
            mOpenBleHelper.setListener(null);
            toast(getStringByResource(R.string.unsupport_ble));
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        seekBar.setOnSeekChangeListener(new OnSeekChangeListener() {
            @Override
            public void onSeeking(SeekParams seekParams) {
                selectPosition = seekParams.thumbPosition+1;
            }
            @Override
            public void onStartTrackingTouch(IndicatorSeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(IndicatorSeekBar seekBar) {
                //在此处做一个判断,提交数据,设置档位值
                changeGearPosition(selectPosition);
            }
        });
        return rootView;
    }

    //写数据得到回调
    @Override
    public void showData(String data, String address) {
        super.showData(data, address);

        showData(data);//得到通知

        //有数据返回说明连接成功
        LinkState.getInstance().setState(true);
        //通知mainActivity更新状态图片
        EventBus.getDefault().post(new StateImgEvent(true));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MassageEvent event) {
        if(seekBar!=null) {
            seekBar.showIndicator(event.getSelected());
        }
        if (event.getSelected()) {
            initBleComponent(addressDev);//重复监听
        }
    }

    //实现与腰部支撑的互斥
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MassageOrLumbarMassageEvent event) {
        if(!event.isMassage() && openOrClose){
            openOrClose = false;
            TextView_enter.setSelected(false);
            TextView_enter.setText("开始");
            stopAnimation();
            seekBar.setEnabled(openOrClose);
        }
    }

    //删除设备,断开连接的通知
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BleDisconnectEvent event) {
        bleModel.disconnectDevice(addressDev);
        bleModel.releaseActivity();
        bleModel.finish();
    }

    @OnClick({R.id.TextView_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.TextView_enter:
                //设置开关状态
                massageOpenClose();
                break;
        }
    }

    //解析蓝牙数据,并赋值给view
    public void showData(String data) {
        byte[] dataByte = ConvertUtils.hexStringToBytes(data);
        if (dataByte[0] == 0x55 && dataByte[1] == 0x01) {
            //设置按摩开关状态
            if (dataByte[2] == 0x01) {
                openOrClose = true;
                TextView_enter.setSelected(true);
                TextView_enter.setText("关闭");
                startAnimation();
            } else {
                openOrClose = false;
                TextView_enter.setSelected(false);
                TextView_enter.setText("开始");
                stopAnimation();
            }
            //通知service当前状态改变了
            EventBus.getDefault().post(new MassageOpenEvent(dataByte[2] == 0x01));
            //设置档位值
            int pro;
            if(dataByte[3]==10){
                pro = 100;
            }else{
                pro = dataByte[3]*10-10;
            }
            //缓存档位值在sp中
            SharePerferenceHelper.createSharePerference("private").putInt("massageDegree",pro);
            selectPosition = dataByte[3];
            seekBar.setProgress(pro);
            //开关未打开时,换挡控件是禁用的。
            seekBar.setEnabled(openOrClose);
        }
        //收到多次蓝牙数据,第二次的数据传递给腰部支撑fragment
        if(dataByte[0] == 0x55 && dataByte[1] == 0x03){
            EventBus.getDefault().post(new BleDataEvent(data));
        }
        //收到多次蓝牙数据,第三次的数据传递给加热fragment
        if(dataByte[0] == 0x55 && dataByte[1] == 0x05){
            EventBus.getDefault().post(new BleHeatingDataEvent(data));
        }
        //收到多次蓝牙数据,第四次的数据传递给通风fragment
        if(dataByte[0] == 0x55 && dataByte[1] == 0x06){
            EventBus.getDefault().post(new BleVentilationDataEvent(data));
        }
        isOpenClicked=false;
    }

    public void massageOpenClose() {
        openOrClose=!openOrClose;
        byte[] warmParams = new byte[5];
        warmParams[0] = 0x55;
        warmParams[1] = 0x01;
        if (openOrClose) {//开始
            warmParams[2] = 0x01;
            EventBus.getDefault().post(new MassageOrLumbarLumbarEvent(true));//通知腰部支撑页
        } else {//停止
            warmParams[2] = 0x00;
        }
        warmParams[3] = (byte) selectPosition;
        String str = HexDump.getBCC(warmParams);
        Integer in = Integer.valueOf(str,16);
        warmParams[4] = (byte) (int) in;
//        byte[] sendData = ConvertUtils.getXORData(warmParams);
//        if (sendData == null) return;
        blePresenter.writeData(warmParams, addressDev,true);
        isOpenClicked = true;
        //添加设备无响应的提示
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(isOpenClicked){
                    ToastUtils.makeText("设备无响应。");
                    openOrClose=!openOrClose;
                }
            }
        },2000);
    }

    public void changeGearPosition(int position) {
        byte[] warmParams = new byte[5];
        warmParams[0] = 0x55;
        warmParams[1] = 0x02;
        warmParams[2] = 0x01;
        warmParams[3] = (byte) (position);
        String str = HexDump.getBCC(warmParams);
        Integer in = Integer.valueOf(str,16);
        warmParams[4] = (byte) (int) in;
        byte[] sendData = ConvertUtils.getXORData(warmParams);
        if (sendData == null) return;
        blePresenter.writeData(sendData, addressDev,true);
    }

    private void startAnimation() {
        WaveView_top_left.setProgressWithAnim(1, 12000);
        WaveView_top_right.setProgressWithAnim(1, 12000);
        WaveView_bottom_left.setProgressWithAnim(1, 12000);
        WaveView_bottom_right.setProgressWithAnim(1, 12000);
    }

    private void stopAnimation() {
        WaveView_top_left.setAnimationStop();
        WaveView_top_right.setAnimationStop();
        WaveView_bottom_left.setAnimationStop();
        WaveView_bottom_right.setAnimationStop();
    }
}

OpenBleHelper.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class OpenBleHelper {

    private static final String TAG = "OpenBleHelper";
    private static final boolean DEBUG = true;

    private static final int REQUEST_CODE_ENABLE_BLE = 0X330;
    private static final int ON_REQUEST_OPEN_BLE_DELAY_CHECK = 6 * 1000;

    private FragmentActivity mActivity;
    private BleHelperFragment mBleHelperFragment;
    private BluetoothAdapter bluetoothAdapter;
    private BleStatusBroadCastReciver mReciver;
    private OnBleStatusChangedListener mListener;
    private Handler mMainHandler;

    public OpenBleHelper(FragmentActivity activity) {
        mActivity = activity;
        init();
    }

    private void init() {
        mBleHelperFragment = getBleFragment(mActivity);
        mBleHelperFragment.setBleHelper(this);
        BluetoothManager bluetoothManager = (BluetoothManager) mActivity.getApplicationContext()
                .getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        mReciver = new BleStatusBroadCastReciver(mActivity, this);
        mReciver.regiseter();
        mMainHandler = new Handler();
    }

    private BleHelperFragment getBleFragment(FragmentActivity activity) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        BleHelperFragment fragment = (BleHelperFragment) fragmentManager.findFragmentByTag(BleHelperFragment.TAG);
        if (fragment == null) {
            fragment = new BleHelperFragment();
            fragmentManager.beginTransaction().add(fragment, BleHelperFragment.TAG).commit();
        }
        return fragment;
    }

    public void setListener(OnBleStatusChangedListener listener) {
        mListener = listener;
    }

    /**
     * 开启蓝牙
     */
    public void openBle() {
        if (isSupportBle()) {
            if (isBleEnable()) {
                dispatchOnBleOpened();
            } else {
                requestOpenBle();
            }
        } else {
            dispatchUnSupportBle();
        }
    }

    /**
     * 判断当前是否支持蓝牙
     */
    public boolean isSupportBle() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                && mActivity.getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
    }

    /**
     * 判断蓝牙是否已开启
     */
    public boolean isBleEnable() {
        if (bluetoothAdapter != null) {
            return bluetoothAdapter.isEnabled();
        }
        return false;
    }

    //通过intent的方式去请求开启蓝牙
    private void requestOpenBle() {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (isIntentAvailable(mActivity, intent)) {
            mBleHelperFragment.startActivityForResult(intent, REQUEST_CODE_ENABLE_BLE);
        } else {
            dispatchOnBleClosed();
        }
    }

    //检测Intent 是否有效
    private boolean isIntentAvailable(Context context, Intent intent) {
        if (context == null) {
            return false;
        }
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolves = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return resolves != null && !resolves.isEmpty();
    }

    //主线程中传递蓝牙已开启回调
    private void dispatchOnBleOpened() {
        if (mListener != null && mMainHandler != null) {
            mMainHandler.post(new Runnable() {
                @Override
                public void run() {
                    mListener.onBleOpened();
                }
            });
        }
    }

    //主线程中传递蓝牙已关闭回调
    private void dispatchOnBleClosed() {
        if (mListener != null && mMainHandler != null) {
            mMainHandler.post(new Runnable() {
                @Override
                public void run() {
                    mListener.onBleClosed();
                }
            });
        }
    }

    //主线程中传递不支持蓝牙
    private void dispatchUnSupportBle() {
        if (mListener != null && mMainHandler != null) {
            mMainHandler.post(new Runnable() {
                @Override
                public void run() {
                    mListener.onUnSupportBle();
                }
            });
        }
    }

    /**
     * 系统弹窗申请开启蓝牙之后,延时一段时间检查蓝牙的开启状态,避免用户点击拒绝而无响应
     */
    private void onRequestResultDelayCheckBleStatus() {
        if (mMainHandler != null) {
            mMainHandler.removeCallbacksAndMessages(null);
            mMainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isBleEnable()) {
                        dispatchOnBleOpened();
                    } else {
                        dispatchOnBleClosed();
                    }
                }
            }, ON_REQUEST_OPEN_BLE_DELAY_CHECK);
        }
    }

    /**
     * 移除延迟检测
     */
    private void removeOnRequestResultDelayCheckBleStatus() {
        if (mMainHandler != null) {
            mMainHandler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 会自动释放
     */
    protected void release() {
        if (mBleHelperFragment != null) {
            mBleHelperFragment.release();
            mBleHelperFragment = null;
        }
        if (mReciver != null) {
            mReciver.release();
            mReciver = null;
        }
        if (mMainHandler != null) {
            mMainHandler.removeCallbacksAndMessages(null);
            mMainHandler = null;
        }
        mListener = null;
        bluetoothAdapter = null;
        mActivity = null;
    }

    @SuppressLint("ValidFragment")
    public static class BleHelperFragment extends Fragment {

        private static final String TAG = "com.lib.fast.helper.OpenBleHelper.BleHelperFragment";

        OpenBleHelper mBleHelper;

        private void setBleHelper(OpenBleHelper helper) {
            mBleHelper = helper;
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == REQUEST_CODE_ENABLE_BLE) {
                d("use request open ble, activity result");
                mBleHelper.onRequestResultDelayCheckBleStatus();
            }
        }

        private void release() {
            mBleHelper = null;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mBleHelper.release();
        }
    }

    //监听蓝牙开启状态广播
    private class BleStatusBroadCastReciver extends BroadcastReceiver {

        private Context mContext;
        private OpenBleHelper mOpenBleHelper;
        private boolean isRegisted;
        private String[] boradcasts = new String[]{BluetoothAdapter.ACTION_STATE_CHANGED};

        private BleStatusBroadCastReciver(Context context, OpenBleHelper openBleHelper) {
            mContext = context.getApplicationContext();
            mOpenBleHelper = openBleHelper;
        }

        public void regiseter() {
            if (!isRegisted) {
                IntentFilter intentFilter = new IntentFilter();
                for (String action : boradcasts) {
                    intentFilter.addAction(action);
                }
                mContext.registerReceiver(this, intentFilter);
                isRegisted = true;
            }
        }

        public void unRegister() {
            if (isRegisted) {
                mContext.unregisterReceiver(this);
                isRegisted = false;
            }
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                mOpenBleHelper.removeOnRequestResultDelayCheckBleStatus();
                int bleStatus = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
                if (bleStatus == BluetoothAdapter.STATE_ON) {
                    mOpenBleHelper.dispatchOnBleOpened();
                } else if (bleStatus == BluetoothAdapter.STATE_OFF) {
                    mOpenBleHelper.dispatchOnBleClosed();
                }
            }
        }

        public void release() {
            unRegister();
            mOpenBleHelper = null;
            mContext = null;
        }
    }

    private static void d(String msg, Object... args) {
        if (DEBUG) {
            Log.d(TAG, String.format(msg, args));
        }
    }

    public interface OnBleStatusChangedListener {

        /**
         * 蓝牙已开启
         */
        void onBleOpened();

        /**
         * 蓝牙已关闭或者开启失败
         */
        void onBleClosed();

        void onUnSupportBle();
    }

}

HexDump.java

/**
 * Clone of Android's HexDump class, for use in debugging. Cosmetic changes
 * only.十六进制数据操作
 */
public class HexDump {
    private final static char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 转换为字符串
     */
    public static String dumpHexString(byte[] array) {
        return dumpHexString(array, 0, array.length);
    }

    /**
     * 转换为字符串
     */
    public static String dumpHexString(byte[] array, int offset, int length) {
        return bytesToHexFun1(array, offset, length);
    }

    /**
     * 格式化数组输出
     */
    public static String toHexString(byte b) {
        return toHexString(toByteArray(b));
    }

    /**
     * 格式化数组输出
     */
    public static String toHexString(byte[] array) {
        return toHexString(array, 0, array.length);
    }

    /**格式化数组输出*/
    public static String toHexString(byte[] array, int offset, int length) {
        return bytesToHexFun2(array, offset, length);
    }

    private static String byteToHexFun3(byte[] array, int offset, int length) {
        StringBuilder result = new StringBuilder();

        byte[] line = new byte[16];
        int lineIndex = 0;

        result.append("0x");
        result.append(toHexString(offset));

        for (int i = offset; i < offset + length; i++) {
            if (lineIndex == 16) {
                result.append(" ");

                for (int j = 0; j < 16; j++) {
                    if (line[j] > ' ' && line[j] < '~') {
                        result.append(new String(line, j, 1));
                    } else {
                        result.append(".");
                    }
                }

                result.append("\n0x");
                result.append(toHexString(i));
                lineIndex = 0;
            }

            byte b = array[i];
            result.append(" ");
            result.append(HEX_DIGITS[(b >>> 4) & 0x0F]);
            result.append(HEX_DIGITS[b & 0x0F]);

            line[lineIndex++] = b;
        }

        if (lineIndex != 16) {
            int count = (16 - lineIndex) * 3;
            count++;
            for (int i = 0; i < count; i++) {
                result.append(" ");
            }

            for (int i = 0; i < lineIndex; i++) {
                if (line[i] > ' ' && line[i] < '~') {
                    result.append(new String(line, i, 1));
                } else {
                    result.append(".");
                }
            }
        }

        return result.toString();
    }

    private static String bytesToHexFun1(byte[] array, int offset, int length) {
        char[] buf = new char[length * 2];

        int bufIndex = 0;
        for (int i = offset; i < offset + length; i++) {
            byte b = array[i];
            buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
            buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
        }

        return new String(buf);
    }

    /**
     * byte[] to hex string
     *
     * @param bytes
     * @return
     */
    private static String bytesToHexFun2(byte[] bytes, int offset, int length) {
        StringBuffer buf = new StringBuffer();
        buf.append("[ ");
        for (int i = offset; i < offset + length; i++) {
            byte b = bytes[i];
            buf.append(String.format("%02x ", new Integer(b & 0xff)).toUpperCase());
            if ((i - offset + 1) % 4 == 0) {
                buf.append(" ");
            }
        }
        buf.append("]");
        return buf.toString();
    }

    public static String toHexString(int i) {
        return toHexString(toByteArray(i));
    }

    public static String toHexString(short i) {
        return toHexString(toByteArray(i));
    }

    public static byte[] toByteArray(byte b) {
        byte[] array = new byte[1];
        array[0] = b;
        return array;
    }

    public static byte[] toByteArray(int i) {
        byte[] array = new byte[4];

        array[3] = (byte) (i & 0xFF);
        array[2] = (byte) ((i >> 8) & 0xFF);
        array[1] = (byte) ((i >> 16) & 0xFF);
        array[0] = (byte) ((i >> 24) & 0xFF);

        return array;
    }

    public static byte[] shortToByteArray(short s) {
        byte[] array = new byte[]{(byte) s};
        return array;
    }

    public static byte intToByte(int i) {
        byte b = (byte) i;
        return b;
    }

    public static byte[] toByteArray(short i) {
        byte[] array = new byte[2];

        array[1] = (byte) (i & 0xFF);
        array[0] = (byte) ((i >> 8) & 0xFF);

        return array;
    }

    private static int toByte(char c) {
        if (c >= '0' && c <= '9')
            return (c - '0');
        if (c >= 'A' && c <= 'F')
            return (c - 'A' + 10);
        if (c >= 'a' && c <= 'f')
            return (c - 'a' + 10);

        throw new RuntimeException("Invalid hex char '" + c + "'");
    }

    public static byte[] hexStringToByteArray(String hexString) {
        int length = hexString.length();
        byte[] buffer = new byte[length / 2];

        for (int i = 0; i < length; i += 2) {
            buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString
                    .charAt(i + 1)));
        }
        return buffer;
    }

    /**
     * 手机号码验证
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
//      Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Pattern p = Pattern.compile("^1[3|4|5|8][0-9]\\d{8}$");

        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * md5加密方法
     *
     * @param info 密码源
     * @return
     */
    public static String getMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }

            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * 异或和
     */

    private static final char[] bcdLookup = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    public static final int MESSAGE_DEVICE_NAME = 4;


    public static String XORAnd(byte[] bytes) {
        int str = 0;
        for (int i = 0; i < bytes.length; i++) {
            str ^= Integer.valueOf((bcdLookup[(bytes[i] >>> MESSAGE_DEVICE_NAME) & 15] + "" + bcdLookup[bytes[i] & 15] + ""), 16);
        }
        return Integer.toHexString(str);
    }

    /**
     * 比较两个byte[]时候一致
     */
    public static boolean bytesEquals(byte[] bs1, byte[] bs2) {
        if (bs1 == null || bs2 == null || bs1.length != bs2.length) return false;
        if (bs1.length == 0 && bs1.length == bs2.length) return true;
        for (int i = 0; i < bs1.length; i++) {
            if (bs1[i] != bs2[i]) return false;
        }
        return true;
    }

    public static boolean bytesStartWith(byte[] fromBytes, byte[] toBytes) {
        if (fromBytes == null || toBytes == null || fromBytes.length < toBytes.length) return false;
        for (int i = 0; i < toBytes.length; i++) {
            if (fromBytes[i] != toBytes[i]) return false;
        }
        return true;
    }

    public static boolean bytesEndWith(byte[] fromBytes, byte[] toBytes) {
        if (fromBytes == null || toBytes == null || fromBytes.length < toBytes.length) return false;
        for (int i = 1; i <= toBytes.length; i++) {
            if (fromBytes[fromBytes.length - i] != toBytes[toBytes.length - i]) return false;
        }
        return true;
    }

    /**
     * 获取高四位
     */
    public static int getHeight4(byte data) {
        int height;
        height = ((data & 0xf0) >> 4);
        return height;
    }

    /**
     * 获取低四位
     */
    public static int getLow4(byte data) {
        int low;
        low = (data & 0x0f);
        return low;
    }

    public static String getBCC(byte[] data) {
        try{
            String ret = "";
            byte BCC[]= new byte[1];
            for(int i=0;i<data.length;i++)
            {
                BCC[0]=(byte) (BCC[0] ^ data[i]);
            }
            String hex = Integer.toHexString(BCC[0] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += hex.toUpperCase();
            return ret;
        } catch(Exception e){
            e.printStackTrace();
            return "";
        }
    }

    /**
     * bytes字符串转换为Byte值
     * @param src Byte字符串,每个Byte之间没有分隔符
     * @return byte[]
     */
    public static byte[] hexStr2Bytes(String src)
    {
        int m=0,n=0;
        int l=src.length()/2;
        System.out.println(l);
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++)
        {
            m=i*2+1;
            n=m+1;
            ret[i] = Byte.decode("0x" + src.substring(i*2, m) + src.substring(m,n));
        }
        return ret;
    }

}
上一篇下一篇

猜你喜欢

热点阅读