关于CRC的一些骚鸡儿操作

package com.vortex.test;

import android.os.Bundle;
import android.os.KpocomAPIServiceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.vortex.rxtest.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator (chenPS) on 2019/8/1.
 */

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;

    private KpocomAPIServiceManager mKPApi;

    private ExecutorService thPool = Executors.newCachedThreadPool();

    private String testStr = "ac55a55a3d0032303138313130383030323419051108395603842cd04198946d4170c43241000000000000000000000000a0f7a246d60000000000000000000000";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = findViewById(R.id.a_main_showReceived);
        mKPApi = (KpocomAPIServiceManager) getSystemService("kpocomapiservice");
        mKPApi.openPort(2, (byte) 3, (byte) 0, (byte) 0, (byte) 0);


        String CRCStr2 = CRC_16_XMODEM(toBytes(testStr), 0);
        CRCStr2 = getCrcString(CRCStr2);
        Log.e("env======",
                " CRC生成校验码" + "   " + CRCStr2);
        thPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    byte[] data = mKPApi.readPort(2);

                    if (data != null) {
                        String str = bytesToHex(data);
                        Log.e("env======",
                                " 接收数据长度" + str.length());
                        Log.e("env=====", str);
                        WeightModel we = doneData(str);
                        Log.e("env=====", we.toString());
                        String deviceNum = getDeviceNumber(str);
                        Log.e("env=====", "设备号:" + deviceNum);
                        String timeStr = getWeighTime(str);
                        Log.e("env=====", "称重时间:" + timeStr);
                        String backHeader = getHead(str);
                        Log.e("env=====", "回复头儿:" + backHeader);
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }


    /**
     * 接收到的byte 数组转化为16进制字符串
     *
     * @param bytes
     * @return
     */
    public String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();

    }

    /**
     * 获取重量
     *
     * @param sourceStr
     * @return
     */
    private WeightModel doneData(String sourceStr) {
        WeightModel weightModel = null;

        if (sourceStr.length() < 54) {
            Log.v("env====", "数据异常");
            return weightModel;
        }

        String codeStr = sourceStr.substring(48, 50);
        if (codeStr.equals("03")) {
            Log.v("env====", "设备到服务器");
        }
        String weightStr = sourceStr.substring(50, sourceStr.length() - 4);
        Log.v("env=====", weightStr + " " + (weightStr.length() % 8 == 0));
        if (weightStr.length() % 8 == 0) {
            String[] weightData = new String[weightStr.length() / 8];
            int j = 0;
            for (int i = 0; i < weightStr.length(); i = i + 8) {
                String subStr = weightStr.substring(i, i + 8);
                Log.v("env===", subStr + " 分割的字符串");
                weightData[j] = subStr;
                j++;
            }
            Log.v("env===", weightData.length + " 重量数组长度 ");
            weightModel = new WeightModel();
            for (int i = 0; i < weightData.length; i++) {
                String weights = weightData[i];
                if (i == 7) {
                    int times = getReverseTimesData(weights);
                    weightModel.setTimes(times);
                    continue;
                }
                Float weightF = getReverseWeighData(weights);
                weightModel.setData(weightF, i);
            }
        }
        return weightModel;
    }


    /**
     * 获取反序16进制字符串的重量     16进制 转  float
     *
     * @param str 反序之前的16进制字符串
     * @return 反序之后的重量(Float)
     */

    private Float getReverseWeighData(String str) {
        Log.v("env====", "操作之前的字符串  " + str);
        Float weight = 0.0f;
        if (str.length() == 8) {
            String[] weightStr = new String[4];
            int j = 0;
            for (int i = 0; i < 4; i++) {
                String subStr = str.substring(j, j + 2);
                weightStr[i] = subStr;
                j = j + 2;
            }
            StringBuffer sb = new StringBuffer();
            for (int i = 4; i > 0; i--) {

                sb.append(weightStr[i - 1]);
            }
            Log.d("env====", "反序之后的字符串  " + sb.toString());
            Long l = Long.parseLong(sb.toString(), 16);

            weight = Float.intBitsToFloat(l.intValue());
        }
        Log.w("env====", "反序之后的重量  " + weight);

        return weight;
    }


    /**
     * 获取反序16进制字符串的重量     16进制 转  float
     *
     * @param str 反序之前的16进制字符串
     * @return 反序之后的重量(Float)
     */

    private int getReverseTimesData(String str) {
        Log.v("env====", "操作之前的字符串  " + str);
        int times = 0;
        if (str.length() == 8) {
            String[] weightStr = new String[4];
            int j = 0;
            for (int i = 0; i < 4; i++) {
                String subStr = str.substring(j, j + 2);
                weightStr[i] = subStr;
                j = j + 2;
            }
            StringBuffer sb = new StringBuffer();
            for (int i = 4; i > 0; i--) {

                sb.append(weightStr[i - 1]);
            }
            Log.d("env====", "反序之后的字符串  " + sb.toString());
            times = Integer.parseInt(sb.toString(), 16);

        }
        Log.w("env====", "反序之后的重量  " + times);

        return times;
    }

    /**
     * 获取称重设备号
     *
     * @param str
     * @return
     */
    private String getDeviceNumber(String str) {
        String resultStr = "";
        if (str.length() < 54) {
            return resultStr;
        }
        String strNum = str.substring(12, 36);
        Log.i("env====", "16进制设备号字符串  " + strNum);
        resultStr = hexStr2Str(strNum);
        return resultStr;
    }

    /**
     * 字符串 16进制 转 普通字符串
     *
     * @param hexStr
     * @return
     */
    public String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 获取称重时间
     *
     * @return
     */
    private String getWeighTime(String str) {
        String time = "";
        if (str.length() < 54) {
            return time;
        }

        String timeStr = str.substring(36, 48);
        Log.i("env====", "16进制时间  " + timeStr);
        if (timeStr.length() == 12) {
            String[] timeArray = new String[6];
            int j = 0;
            for (int i = 0; i < 12; i = i + 2) {
                timeArray[j] = timeStr.substring(i, i + 2);
                j++;
            }
            StringBuffer sb = new StringBuffer();
            sb.append("20");
            sb.append(timeArray[0]);
            sb.append("-");
            sb.append(timeArray[1]);
            sb.append("-");
            sb.append(timeArray[2]);
            sb.append(" ");
            sb.append(timeArray[3]);
            sb.append(":");
            sb.append(timeArray[4]);
            sb.append(":");
            sb.append(timeArray[5]);
            time = sb.toString();
        }
        return time;
    }

    /**
     * 数据头
     *
     * @param str
     * @return
     */
    private String getHead(String str) {
        String resultStr = "";
        if (str.length() < 54) {
            return resultStr;
        }
        String strNum = str.substring(12, 36);
        String timeStr = getCurrentTime();
        Log.i("env====", "设备时间  " + timeStr);

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("AC55A55A");
        stringBuffer.append("1E00");
        stringBuffer.append(strNum);
        stringBuffer.append(timeStr);
        stringBuffer.append("0401");
        resultStr = stringBuffer.toString();
        return resultStr;
    }


    private String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        Date date = new Date();
        return sdf.format(date);
    }


    /**
     * 计算产生校验码
     *
     * @param data 需要校验的数据
     * @return 校验码
     */
    public static String Make_CRC(byte[] data) {
        byte[] buf = new byte[data.length];// 存储需要产生校验码的数据
        for (int i = 0; i < data.length; i++) {
            buf[i] = data[i];
        }
        int len = buf.length;
        int crc = 0xFFFF;//16位
        for (int pos = 0; pos < len; pos++) {
            if (buf[pos] < 0) {
                crc ^= (int) buf[pos] + 256; // XOR byte into least sig. byte of
                // crc
            } else {
                crc ^= (int) buf[pos]; // XOR byte into least sig. byte of crc
            }
            for (int i = 8; i != 0; i--) { // Loop over each bit
                if ((crc & 0x0001) != 0) { // If the LSB is set
                    crc >>= 1; // Shift right and XOR 0xA001
                    crc ^= 0xA001;
                } else
                    // Else LSB is not set
                    crc >>= 1; // Just shift right
            }
        }
        String c = Integer.toHexString(crc);
        if (c.length() == 4) {
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 3) {
            c = "0" + c;
            c = c.substring(2, 4) + c.substring(0, 2);
        } else if (c.length() == 2) {
            c = "0" + c.substring(1, 2) + "0" + c.substring(0, 1);
        }
        return c;
    }


    /**
     * 把 CRC 校验码 高低位互换位置
     *
     * @param str
     * @return  WARNNING 这个计算有可能不是四位  不是四位的话 需要补0不然有问题
     */
  public String getCrcString(String str) {
        String CRCStr2 = CRC_16_XMODEM(toBytes(str), 0);
        String result = "";
        if (CRCStr2.length() != 4) {
            if (CRCStr2.length() < 4) {
                while (CRCStr2.length() < 4) {
                    CRCStr2 = "0" + CRCStr2;
                }
            } else if (CRCStr2.length() > 4) {
                return "";
            }
        }
        String str1 = CRCStr2.substring(0, 2);
        String str2 = CRCStr2.substring(2, 4);
        result = str2 + str1;
        return result;
    }

    /**
     * byte 生成 crc16xmodem 校验码   结果要高低位互换
     *
     * @param bytes
     * @param length
     * @return    
     */
    private String CRC_16_XMODEM(byte[] bytes, int length) {
        int crc = 0x0000; // initial value
        int polynomial = 0x1021; // poly value
        for (int index = 0; index < bytes.length; index++) {
            byte b = bytes[index];
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }
        crc &= 0xffff;
        // 输出String字样的16进制
        String strCrc = Integer.toHexString(crc).toUpperCase();
        return strCrc;
    }

    /**
     * 把16进制字符串 搞成 16进制的 数组
     *
     * @param str
     * @return
     */
    private byte[] toBytes(String str) {
        if (TextUtils.isEmpty(str)) {
            return new byte[0];
        }
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }


}
~~

你可能感兴趣的:(关于CRC的一些骚鸡儿操作)