Java 串口通讯 Demo

news2024/10/7 16:16:21

为什么写这篇文章

之前职业生涯中遇到的都是通过tcp协议与其他设备进行通讯,而这个是通过串口与其他设备进行通讯,意识到这里是承重板的连接,但实际上比如拉力、压力等模拟信号转换成数字信号的设备应该是有相当一大部分是通过这种方式通讯的。

研究了2天,有初步的成果,特此记录

整体结构

这几天公司弄来了几台称重板,需要通过程序读取称重板的重量数值。
称重板没有wifi,目前是通过串口与PC相连的形式工作,结构类似如下
在这里插入图片描述
在这里插入图片描述
称重板通过线(不知道叫什么线,有黄绿黑红4根细线组成,其中红黑应该是电源线)与485转usb的工具插电脑上
在这里插入图片描述

说说Java如何与串口通信

整体来说,java与串口通信有三种模式

  1. Jdk自带的接口comm.jar,没有测试,据说是比较老了,基本不用
  2. RXTXcomm.jar:也是比较老了,2012年开始就没有更新,但是网上很多教程是基于这个的,比如:https://www.jianshu.com/p/7c03ad8a6139,应该是只能在windows下面使用(不确定),需要copy两个dll文件到jdk的安装目录。如果要maven里面引入是这样的
    <dependency>
        <groupId>org.rxtx</groupId>
        <artifactId>rxtx</artifactId>
        <version>2.1.7</version>
    </dependency>
    
  3. JSerialComm:较新、且与平台无关

个人认为使用JSerialComm是比较合适的,本文Demo也是基于此实现

JAVA代码

<dependency>
    <groupId>com.fazecast</groupId>
    <artifactId>jSerialComm</artifactId>
    <version>[2.0.0,3.0.0)</version>
</dependency>
package com.bt.rs232.JSerialCommDemo2;

import com.bt.rs232.util.StringUtil;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;

/**
 * @author :GuangXiZhong
 * @date :Created in 2023/7/19 11:29
 * @description:https://blog.csdn.net/qq_36666559/article/details/122027164
 */
public class Test {
    public static void main(String[] args) throws InterruptedException {
        SerialPort[] serialPorts = SerialPort.getCommPorts();//查找所有串口
        for (SerialPort port : serialPorts) {
            System.out.println("Port:" + port.getSystemPortName());//打印串口名称,如COM4
            System.out.println("PortDesc:" + port.getPortDescription());//打印串口类型,如USB Serial
            System.out.println("PortDesc:" + port.getDescriptivePortName());//打印串口的完整类型,如USB-SERIAL CH340(COM4)

            port.addDataListener(new SerialPortDataListener() {//添加监听器。由于该监听器有两个函数,无法使用Lambda表达式

                @Override
                public int getListeningEvents() {
                    return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;//返回要监听的事件类型,以供回调函数使用。可发回的事件包括:SerialPort.LISTENING_EVENT_DATA_AVAILABLE,SerialPort.LISTENING_EVENT_DATA_WRITTEN,SerialPort.LISTENING_EVENT_DATA_RECEIVED。分别对应有数据在串口(不论是读的还是写的),有数据写入串口,从串口读取数据。如果AVAILABLE和RECEIVED同时被监听,优先触发RECEIVED
                }

                @Override
                public void serialEvent(SerialPortEvent event) {//事件处理函数
                    String data = "";
                    if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
                        return;//判断事件的类型
                    }
                    while (port.bytesAvailable() != 0) {
                        //同样使用循环读取法读取所有数据
                        //由于这里是监听函数,所以也可以不使用循环读取法,在监听器外创建一个全局变量,然后将每次读取到的数据添加到全局变量里
                        byte[] newData = new byte[port.bytesAvailable()];
                        int numRead = port.readBytes(newData, newData.length);
//                        String newDataString = new String(newData);
                        String newDataString = StringUtil.bytesToHexString(newData);
                        data = data + newDataString;
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("readString:" + data);
                }
            });
        }
        SerialPort serialPort = serialPorts[0];//获取到第一个串口
        serialPort.setBaudRate(19200);//设置波特率为112500
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);//设置超时
        serialPort.setRTS();//设置RTS。也可以设置DTR
        serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);//设置串口的控制流,可以设置为disabled,或者CTS, RTS/CTS, DSR, DTR/DSR, Xon, Xoff, Xon/Xoff等
        // 一次性设置所有的串口参数,第一个参数为波特率,默认9600;
        // 第二个参数为每一位的大小,默认8,可以输入5到8之间的值;
        // 第三个参数为停止位大小,只接受内置常量,可以选择(ONE_STOP_BIT, ONE_POINT_FIVE_STOP_BITS, TWO_STOP_BITS);
        // 第四位为校验位,同样只接受内置常量,可以选择 NO_PARITY, EVEN_PARITY, ODD_PARITY, MARK_PARITY,SPACE_PARITY。
        serialPort.setComPortParameters(19200, 8, SerialPort.ONE_STOP_BIT, SerialPort.EVEN_PARITY);

        boolean isCommOpeded = serialPort.openPort();//判断串口是否打开,如果没打开,就打开串口。打开串口的函数会返回一个boolean值,用于表明串口是否成功打开了
        if (!isCommOpeded) {
            System.out.println("串口打开失败,请确认是否有其他设备正在使用此串口!");
        }
//        for (SerialPort port : serialPorts) {
        // 一开始以为要用这个转,用了虚拟助手才发现传输的是16个字节,排查下来需要用new byte,这边要特别注意
        String writeData = "0203002C000205F1";//要发送的字符串
//            byte[] bytes = writeData.getBytes();//将字符串转换为字节数组
        byte[] bytes = StringUtil.hexStringToByteArray(writeData);

        byte[] bytes1 = new byte[8];
        bytes1[0] = (byte) Integer.parseInt("02", 16);
        bytes1[1] = (byte) Integer.parseInt("03", 16);
        bytes1[2] = (byte) Integer.parseInt("00", 16);
        bytes1[3] = (byte) Integer.parseInt("2C", 16);
        bytes1[4] = (byte) Integer.parseInt("00", 16);
        bytes1[5] = (byte) Integer.parseInt("02", 16);
        bytes1[6] = (byte) Integer.parseInt("05", 16);
        bytes1[7] = (byte) Integer.parseInt("F1", 16);

        serialPort.writeBytes(bytes, bytes.length);//将字节数组全部写入串口
        Thread.sleep(1000);//休眠0.1秒,等待下位机返回数据。如果不休眠直接读取,有可能无法成功读到数据
//            String readData = "";
//            while (serialPort.bytesAvailable() > 0) {//循环读取所有的返回数据。如果可读取数据长度为0或-1,则停止读取
//                byte[] newData = new byte[serialPort.bytesAvailable()];//创建一个字节数组,长度为可读取的字节长度
//                int numRead = serialPort.readBytes(newData, newData.length);//将串口中可读取的数据读入字节数组,返回值为本次读取到的字节长度
//                String newDataString = new String(newData);//将新数据转为字符串
//                readData = readData + newDataString;//组合字符串
//                Thread.sleep(20);//休眠0.02秒,等待下位机传送数据到串口。如果不休眠,直接再次使用port.bytesAvailable()函数会因为下位机还没有返回数据而返回-1,并跳出循环导致数据没读完。休眠时间可以自行调试,时间越长,单次读取到的数据越多。
//            }
//            System.out.println("readString:" + readData);
//        }
        serialPort.closePort();//关闭串口。该函数同样会返回一个boolean值,表明串口是否成功关闭
    }
}
public class StringUtil {

    /**
     * 16进制表示的字符串转换为字节数组
     *
     * @param hexString 16进制表示的字符串
     * @return byte[] 字节数组
     */
    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
                    .digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}

推荐两个好用的调试工具

  1. 友善串口调试助手(可以手动往某个串口发送数据)
    在这里插入图片描述

  2. Virtual Serial Port Driver Pro(串口虚拟工具,用以模拟一个串口)
    在这里插入图片描述

总结自己调试过程中遇到的问题

一开始我遵循了协议往对应的串口发,却没有办法收到称重板给的返回数据,经过排查是我发送的方法错误

String writeData = "0203002C000205F1";//要发送的字符串
byte[] bytes = writeData.getBytes();//将字符串转换为字节数组
serialPort.writeBytes(bytes, bytes.length);

但实际上不能这样,这里得转换一下,相当于把字符串表示的16进制数值转化为一个字节数组(有点绕,相当于字符串的内容是16进制的数值,但是用的是字符串表示),比如可以这样

byte[] bytes1 = new byte[8];
bytes1[0] = (byte) Integer.parseInt("02", 16);
bytes1[1] = (byte) Integer.parseInt("03", 16);
bytes1[2] = (byte) Integer.parseInt("00", 16);
bytes1[3] = (byte) Integer.parseInt("2C", 16);
bytes1[4] = (byte) Integer.parseInt("00", 16);
bytes1[5] = (byte) Integer.parseInt("02", 16);
bytes1[6] = (byte) Integer.parseInt("05", 16);
bytes1[7] = (byte) Integer.parseInt("F1", 16);

具体看上面StringUtil里面的 StringUtil.hexStringToByteArray

关于CRC16校验码

我调试的这个设备最后两位是指CRC16校验码,这个东西相当于对一整段数据的简单校验,用以接收方判断收到的数据是否完整,生成CRC校验码的代码如下

package com.yrt.common.utils;

import com.yrt.project.api.socket.SocketServer;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CRC16Util {
    static byte[] crc16_tab_h = {(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0,
            (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
            (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
            (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
            (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40};

    static byte[] crc16_tab_l = {(byte) 0x00, (byte) 0xC0, (byte) 0xC1, (byte) 0x01, (byte) 0xC3, (byte) 0x03, (byte) 0x02, (byte) 0xC2, (byte) 0xC6, (byte) 0x06, (byte) 0x07, (byte) 0xC7, (byte) 0x05, (byte) 0xC5, (byte) 0xC4, (byte) 0x04, (byte) 0xCC, (byte) 0x0C, (byte) 0x0D, (byte) 0xCD, (byte) 0x0F, (byte) 0xCF, (byte) 0xCE, (byte) 0x0E, (byte) 0x0A, (byte) 0xCA, (byte) 0xCB, (byte) 0x0B, (byte) 0xC9, (byte) 0x09, (byte) 0x08, (byte) 0xC8, (byte) 0xD8, (byte) 0x18, (byte) 0x19, (byte) 0xD9, (byte) 0x1B, (byte) 0xDB, (byte) 0xDA, (byte) 0x1A, (byte) 0x1E, (byte) 0xDE, (byte) 0xDF, (byte) 0x1F, (byte) 0xDD, (byte) 0x1D, (byte) 0x1C, (byte) 0xDC, (byte) 0x14, (byte) 0xD4, (byte) 0xD5, (byte) 0x15, (byte) 0xD7, (byte) 0x17, (byte) 0x16, (byte) 0xD6, (byte) 0xD2, (byte) 0x12,
            (byte) 0x13, (byte) 0xD3, (byte) 0x11, (byte) 0xD1, (byte) 0xD0, (byte) 0x10, (byte) 0xF0, (byte) 0x30, (byte) 0x31, (byte) 0xF1, (byte) 0x33, (byte) 0xF3, (byte) 0xF2, (byte) 0x32, (byte) 0x36, (byte) 0xF6, (byte) 0xF7, (byte) 0x37, (byte) 0xF5, (byte) 0x35, (byte) 0x34, (byte) 0xF4, (byte) 0x3C, (byte) 0xFC, (byte) 0xFD, (byte) 0x3D, (byte) 0xFF, (byte) 0x3F, (byte) 0x3E, (byte) 0xFE, (byte) 0xFA, (byte) 0x3A, (byte) 0x3B, (byte) 0xFB, (byte) 0x39, (byte) 0xF9, (byte) 0xF8, (byte) 0x38, (byte) 0x28, (byte) 0xE8, (byte) 0xE9, (byte) 0x29, (byte) 0xEB, (byte) 0x2B, (byte) 0x2A, (byte) 0xEA, (byte) 0xEE, (byte) 0x2E, (byte) 0x2F, (byte) 0xEF, (byte) 0x2D, (byte) 0xED, (byte) 0xEC, (byte) 0x2C, (byte) 0xE4, (byte) 0x24, (byte) 0x25, (byte) 0xE5, (byte) 0x27, (byte) 0xE7,
            (byte) 0xE6, (byte) 0x26, (byte) 0x22, (byte) 0xE2, (byte) 0xE3, (byte) 0x23, (byte) 0xE1, (byte) 0x21, (byte) 0x20, (byte) 0xE0, (byte) 0xA0, (byte) 0x60, (byte) 0x61, (byte) 0xA1, (byte) 0x63, (byte) 0xA3, (byte) 0xA2, (byte) 0x62, (byte) 0x66, (byte) 0xA6, (byte) 0xA7, (byte) 0x67, (byte) 0xA5, (byte) 0x65, (byte) 0x64, (byte) 0xA4, (byte) 0x6C, (byte) 0xAC, (byte) 0xAD, (byte) 0x6D, (byte) 0xAF, (byte) 0x6F, (byte) 0x6E, (byte) 0xAE, (byte) 0xAA, (byte) 0x6A, (byte) 0x6B, (byte) 0xAB, (byte) 0x69, (byte) 0xA9, (byte) 0xA8, (byte) 0x68, (byte) 0x78, (byte) 0xB8, (byte) 0xB9, (byte) 0x79, (byte) 0xBB, (byte) 0x7B, (byte) 0x7A, (byte) 0xBA, (byte) 0xBE, (byte) 0x7E, (byte) 0x7F, (byte) 0xBF, (byte) 0x7D, (byte) 0xBD, (byte) 0xBC, (byte) 0x7C, (byte) 0xB4, (byte) 0x74,
            (byte) 0x75, (byte) 0xB5, (byte) 0x77, (byte) 0xB7, (byte) 0xB6, (byte) 0x76, (byte) 0x72, (byte) 0xB2, (byte) 0xB3, (byte) 0x73, (byte) 0xB1, (byte) 0x71, (byte) 0x70, (byte) 0xB0, (byte) 0x50, (byte) 0x90, (byte) 0x91, (byte) 0x51, (byte) 0x93, (byte) 0x53, (byte) 0x52, (byte) 0x92, (byte) 0x96, (byte) 0x56, (byte) 0x57, (byte) 0x97, (byte) 0x55, (byte) 0x95, (byte) 0x94, (byte) 0x54, (byte) 0x9C, (byte) 0x5C, (byte) 0x5D, (byte) 0x9D, (byte) 0x5F, (byte) 0x9F, (byte) 0x9E, (byte) 0x5E, (byte) 0x5A, (byte) 0x9A, (byte) 0x9B, (byte) 0x5B, (byte) 0x99, (byte) 0x59, (byte) 0x58, (byte) 0x98, (byte) 0x88, (byte) 0x48, (byte) 0x49, (byte) 0x89, (byte) 0x4B, (byte) 0x8B, (byte) 0x8A, (byte) 0x4A, (byte) 0x4E, (byte) 0x8E, (byte) 0x8F, (byte) 0x4F, (byte) 0x8D, (byte) 0x4D,
            (byte) 0x4C, (byte) 0x8C, (byte) 0x44, (byte) 0x84, (byte) 0x85, (byte) 0x45, (byte) 0x87, (byte) 0x47, (byte) 0x46, (byte) 0x86, (byte) 0x82, (byte) 0x42, (byte) 0x43, (byte) 0x83, (byte) 0x41, (byte) 0x81, (byte) 0x80, (byte) 0x40};

    byte[] bytes = new byte[]{(byte) 0xaa, (byte) 0x55, (byte) 0x01, (byte) 0x05, (byte) 0x0d, (byte) 0x31, (byte) 0x10, (byte) 0x01, (byte) 0x0c, (byte) 0x00, (byte) 0x01, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x59};

    /**
     * 计算CRC16校验  对外的接口
     *
     * @param data 需要计算的数组
     * @return CRC16校验值
     */
    public static int calcCrc16(byte[] data) {
        return calcCrc16(data, 0, data.length);
    }

    /**
     * 计算CRC16校验
     *
     * @param data   需要计算的数组
     * @param offset 起始位置
     * @param len    长度
     * @return CRC16校验值
     */
    public static int calcCrc16(byte[] data, int offset, int len) {
        return calcCrc16(data, offset, len, 0xffff);
    }

    /**
     * 计算CRC16校验
     *
     * @param data   需要计算的数组
     * @param offset 起始位置
     * @param len    长度
     * @param preval 之前的校验值
     * @return CRC16校验值
     */
    public static int calcCrc16(byte[] data, int offset, int len, int preval) {
        int ucCRCHi = (preval & 0xff00) >> 8;
        int ucCRCLo = preval & 0x00ff;
        int iIndex;
        for (int i = 0; i < len; ++i) {
            iIndex = (ucCRCLo ^ data[offset + i]) & 0x00ff;
            ucCRCLo = ucCRCHi ^ crc16_tab_h[iIndex];
            ucCRCHi = crc16_tab_l[iIndex];
        }
        return ((ucCRCHi & 0x00ff) << 8) | (ucCRCLo & 0x00ff) & 0xffff;
    }

    /**
     * 把数值转化为16进制字符串并且高低位中间加空格
     *
     * @param res
     * @return
     */
    public static String getCrc(int res) {
        String format = String.format("%04x", res);
        String substring = format.substring(0, 2);
        String substring1 = format.substring(2, 4);
        return substring1.concat(" ").concat(substring);
    }

    /**
     * byte转16进制取低位
     * @param b
     * @return
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    public static String getCountCode(String s){
        byte[] bytes = SocketServer.hexStringToByteArray(s);
        byte count = 0;
        for (byte aByte : bytes) {
            count += aByte;
        }
        return byteToHex(count);
    }

    /**
     * 16 进制的高低位倒置
     *
     * @param hex
     * @return
     */
    public static String reverseHex(String hex) {
        char[] charArray = hex.toCharArray();
        int length = charArray.length;
        int times = length / 2;
        for (int c1i = 0; c1i < times; c1i += 2) {
            int c2i = c1i + 1;
            char c1 = charArray[c1i];
            char c2 = charArray[c2i];
            int c3i = length - c1i - 2;
            int c4i = length - c1i - 1;
            charArray[c1i] = charArray[c3i];
            charArray[c2i] = charArray[c4i];
            charArray[c3i] = c1;
            charArray[c4i] = c2;
        }
        return new String(charArray);
    }

    public static void main(String[] args) {

//        System.out.println(reverseHex("这是名称的位置"));

        String s = "36 10 01 07 00 01 04 3F 80 00 00";
        int i = CRC16Util.calcCrc16(SocketServer.hexStringToByteArray(s));
        String crc = getCrc(i);
        System.out.println(s + " " + crc);
    }
//    public static void main(String[] args) {
//        String str = Test.packageInstruct("36",12,null);
//        int i = CRC16Util.calcCrc16(SocketServer.hexStringToByteArray(str));
//        String crc = getCrc(i);
//        System.out.println(str + " " + crc);
//    }
}
int i = CRC16Util.calcCrc16(SocketServer.hexStringToByteArray(instruct));
String crc = CRC16Util.getCrc(i);
return instruct + " " + crc;
输入instruct:31 10 01 00 00 01 0C B2E2CAD4C3FBB3C630373139
返回:31 10 01 00 00 01 0C B2E2CAD4C3FBB3C630373139 80 cb

有时候协议中需要传入数据的长度

在这里插入图片描述
获取数据长度的代码如下,返回的长度是以16进制表示的

private static String bytesToHex(String name) {
    int length = 0;
    try {
        length = name.getBytes("GBK").length;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    StringBuilder sb = new StringBuilder(8);
    char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    while (length != 0) {
        sb = sb.append(b[length % 16]);
        length = length / 16;
    }
    String value = sb.reverse().toString();
    if (value.length() == 1) {
        value = "0" + value;
    }
    return value;
}
输入:测试名称0719
返回:0C

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/772024.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

为你精选5款体验极佳的原型设计工具!

在绘制原型图的过程中&#xff0c;使用一款的简单易操作的原型设计工具是非常重要的&#xff0c;本文精选了5款好用的原型工具与大家分享&#xff0c;一起来看看吧&#xff01; 1、即时设计 即时设计是国内很多设计师都在用的原型设计工具&#xff0c;同时它也是国产的原型设…

JMeter正则表达式提取器和JSON提取器基础用法,小白必会!

最近在利用JMeter做接口自动化测试&#xff0c;正则表达式提取器和JSON提取器用的还挺多&#xff0c;想着分享下&#xff0c;希望对大家的接口自动化测试项目有所启发。 在 JMeter 中&#xff0c;正则表达式和 JSON 提取器都是用于从响应数据中提取所需内容&#xff0c;但它们的…

界面控件Telerik UI for WinForms R2 2023——发布全新的热图控件

Telerik UI for WinForms拥有适用Windows Forms的110多个令人惊叹的UI控件。所有的UI for WinForms控件都具有完整的主题支持&#xff0c;可以轻松地帮助开发人员在桌面和平板电脑应用程序提供一致美观的下一代用户体验。 在本文中&#xff0c;我们将揭秘一下Telerik UI for W…

vue数组对象快速获取最大值和最小值(linq插件各种常用好用方法),提高开发效率

需求&#xff1a;因后端传入的数据过多&#xff0c;前端需要在数组中某一值的的最大值和最小值计算&#xff0c;平常用的最多的不就是遍历之后再比对吗&#xff0c;或者用sort方法等实现&#xff0c;同事交了我一招&#xff0c;一句话就可以获取到数组对象中最大值和最小值&…

【Docker】Docker基本概念

Docker基本概念 1.Docker概述1.1 Docker是什么&#xff1f;1.2 Docker的宗旨1.3 容器的优点1.4 Docker与虚拟机的区别1.5 容器在内核中支持的两种技术1.6 namespace的六大类型 2.Docker核心概念2.1 镜像2.2 容器2.3 仓库 3. 知识点总结3.1 Docker是什么&#xff1f;3.2 容器和虚…

Fortinet Accelerate 2023·中国区巡展收官丨让安全成就未来

7月18日&#xff0c;2023 Fortinet Accelerate Summit在上海成功举办&#xff01;这亦象征着“Fortinet Accelerate2023中国区巡展”圆满收官。Fortinet携手来自多个典型行业的百余位代表客户&#xff0c;以及亚马逊云科技、Telstra - PBS 太平洋电信、Tenable等多家生态合作伙…

RT-Thread 学习-Env开发环境搭建(一)

Env是什么 Env 是 RT-Thread 推出的开发辅助工具&#xff0c;针对基于 RT-Thread 操作系统的项目工程&#xff0c;提供编译构建环境、图形化系统配置及软件包管理功能。 其内置的 menuconfig 提供了简单易用的配置剪裁工具&#xff0c;可对内核、组件和软件包进行自由裁剪&…

PROFIBUS-DP主站转ETHERNET/IP网关ethernet有哪些协议

远创智控YC-DPM-EIP是自主研发的一款PROFIBUS-DP主站功能的通讯网关。该产品主要功能是将各种PROFIBUS-DP从站接入到ETHERNET/IP网络中。 1, 本网关连接到PROFIBUS总线中作为主站使用&#xff0c;连接到ETHERNET/IP总线中作为从站使用。 1.2 产品特点 ◆ PROFIBUS-DP/V0 协议…

AtcoderABC243场

A - Shampoo A - Shampoo ] 题目大意 高桥家有三个人&#xff1a;高桥、他的父亲和他的母亲。每个人每晚都在浴室洗头发。他们按照顺序使用AA、BB和CC毫升的洗发水。 问&#xff0c;今天早上瓶子里有VV毫升的洗发水。在不重新装满的情况下&#xff0c;谁会第一个用完洗发水洗头…

【Maven四】——maven聚合和继承

系列文章目录 Maven之POM介绍 maven命令上传jar包到nexus 【Maven二】——maven仓库 【Maven三】——maven生命周期和插件 聚合和继承 系列文章目录前言一、什么是maven的聚合和继承&why二、聚合三、继承1.可继承的POM元素2.依赖管理3.插件管理 四、聚合与继承的关系五、约…

java电子病历系统源码

电子病历系统采取结构化与自由式录入的新模式&#xff0c;自由书写&#xff0c;轻松录入。化实现病人医疗记录&#xff08;包含有首页、病程记录、检查检验结果、医嘱、手术记录、护理记录等等。&#xff09;的保存、管理、传输和重现&#xff0c;取代手写纸张病历。不仅实现了…

【Docker】Docker安装与操作

docker的安装与命令 一、安装 docker1. 安装依赖包2. 信息查看 二、Docker 镜像操作1. 搜索镜像2. 获取镜像3. 镜像加速下载4. 查看镜像相关信息5. 删除镜像6. 上传镜像7. 存出和载入镜像 三、Docker 容器操作1. 创建容器2. 查看容器3. 启动容器4. 停止容器5. 进入容器6. 容器与…

四、DML-4.小结

一、数据记录操作 1、添加数据 给指定字段添加数据 insert into employee(id, workno, name, gender, age, idcard,entrydate) values (1, 001,Itcast, 男, 18, 123456789012345678, 2023-12-12); INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (值1, 值2, ...); 给全部…

Linux--使用者管理(job control)

Linux–使用者管理(job control) 文章目录 Linux--使用者管理(job control)前言一、任务管理(job control)二、&三、 将目前的任务丢到后台中暂停 -- ctrlz四、jobs -- 查看目前的后台任务状态五、fg -- 将后台任务拿到前台来处理六、bg -- 让任务在后台下的状态变为运行中…

LeetCode 1493. 删掉一个元素以后全为 1 的最长子数组 - 二分 + 滑动窗口

删掉一个元素以后全为 1 的最长子数组 提示 中等 90 相关企业 给你一个二进制数组 nums &#xff0c;你需要从中删掉一个元素。 请你在删掉元素的结果数组中&#xff0c;返回最长的且只包含 1 的非空子数组的长度。 如果不存在这样的子数组&#xff0c;请返回 0 。 提示 1&a…

2023-07-18力扣今日二题-太难了吧

链接&#xff1a; LCP 75. 传送卷轴 题意&#xff1a; 给一个正方形迷宫&#xff0c;主角是A&#xff0c;每次可以上下左右走一格子&#xff0c;有四种类型的格子&#xff1a;墙、初始位置、魔法水晶、空地 另一个人B&#xff0c;可以传送一次A&#xff0c;只能在空地传送&…

Twisted Circuit

题目描述 输入格式 The input consists of four lines, each line containing a single digit 0 or 1. 输出格式 Output a single digit, 0 or 1. 题意翻译 读入四个整数 00 或者 11&#xff0c;作为如图所示的电路图的输入。请输出按照电路图运算后的结果。 感谢PC_DOS …

算法与数据结构-排序

文章目录 一、如何分析一个排序算法1.1 排序算法的执行效率1.1.1 最好情况、最坏情况、平均情况时间复杂度1.1.1.1 最好、最坏情况分析1.1.1.2 平均情况分析 1.1.2 时间复杂度的系数、常数 、低阶1.1.3 比较次数和交换&#xff08;或移动&#xff09;次数 1.2 排序算法的内存消…

第六届字节跳动青训营报录比(宣传大使)

统计 前端基础卷&#xff1a;105 前端基础班&#xff1a;120-22(笔试不过基础班&#xff0c;宣传大使奖励进入&#xff09;98 前端进阶卷&#xff1a;77 前端进阶班&#xff1a;18-216 后端基础卷&#xff1a;151 后端基础班&#xff1a;220 后端进阶卷&#xff1a;133 后端进…

【论文笔记】KDD2019 | KGAT: Knowledge Graph Attention Network for Recommendation

Abstract 为了更好的推荐&#xff0c;不仅要对user-item交互进行建模&#xff0c;还要将关系信息考虑进来 传统方法因子分解机将每个交互都当作一个独立的实例&#xff0c;但是忽略了item之间的关系&#xff08;eg&#xff1a;一部电影的导演也是另一部电影的演员&#xff09…