串口编程

从网上看到的,好用,记录下,侵权的话我立马删除

maven

<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

<dependency>
    <groupId>org.bidib.jbidib.org.qbang.rxtx</groupId>
    <artifactId>rxtxcomm</artifactId>
    <version>2.2</version>
</dependency>

串口必要参数接收类

/**
 * 串口必要参数接收类
 * @author: LinWenLi
 * @date: 2018年7月21日 下午4:30:40
 */
public class ParamConfig {

    private String serialNumber;// 串口号
    private int baudRate; // 波特率
    private int checkoutBit; // 校验位
    private int dataBit; // 数据位
    private int stopBit; // 停止位

    public ParamConfig() {}

    /**
     * 构造方法
     * @param serialNumber 串口号
     * @param baudRate 波特率
     * @param checkoutBit 校验位
     * @param dataBit 数据位
     * @param stopBit 停止位
     */
    public ParamConfig(String serialNumber, int baudRate, int checkoutBit, int dataBit, int stopBit) {
        this.serialNumber = serialNumber;
        this.baudRate = baudRate;
        this.checkoutBit = checkoutBit;
        this.dataBit = dataBit;
        this.stopBit = stopBit;
    }

    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public int getBaudRate() {
        return baudRate;
    }

    public void setBaudRate(int baudRate) {
        this.baudRate = baudRate;
    }

    public int getCheckoutBit() {
        return checkoutBit;
    }

    public void setCheckoutBit(int checkoutBit) {
        this.checkoutBit = checkoutBit;
    }

    public int getDataBit() {
        return dataBit;
    }

    public void setDataBit(int dataBit) {
        this.dataBit = dataBit;
    }

    public int getStopBit() {
        return stopBit;
    }

    public void setStopBit(int stopBit) {
        this.stopBit = stopBit;
    }

    @Override
    public String toString() {
        return "ParamConfig{" +
                "serialNumber='" + serialNumber + '\'' +
                ", baudRate=" + baudRate +
                ", checkoutBit=" + checkoutBit +
                ", dataBit=" + dataBit +
                ", stopBit=" + stopBit +
                '}';
    }
}

返回封装类

import java.io.Serializable;


public class ResponseObject implements Serializable {
    private static final long serialVersionUID = 1L;

    /** 列表数据 */
    private String data;

    /** 消息状态码 */
    private int code;

    /** 消息内容 */
    private String msg;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "ResponseObject{" +
                "data='" + data + '\'' +
                ", code=" + code +
                ", msg='" + msg + '\'' +
                '}';
    }
}

读取串口工具类

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import com.qwings.ipmgbascale.config.ParamConfig;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

public class SerialPortUtils implements SerialPortEventListener {

    // 检测系统中可用的通讯端口类
    private CommPortIdentifier commPortId;
    // 枚举类型
    private Enumeration<CommPortIdentifier> portList;
    // RS232串口
    private SerialPort serialPort;
    // 输入流
    private InputStream inputStream;
    // 输出流
    private OutputStream outputStream;
    // 保存串口返回信息
    private String data;
    // 保存串口返回信息十六进制
    private String dataHex;

    /**
     * 初始化串口
     *
     * @throws
     * @author LinWenLi
     * @date 2018年7月21日下午3:44:16
     * @Description: TODO
     * @param: paramConfig  存放串口连接必要参数的对象(会在下方给出类代码)
     * @return: void
     */
    @SuppressWarnings("unchecked")
    public void init(ParamConfig paramConfig) {
        // 获取系统中所有的通讯端口
        portList = CommPortIdentifier.getPortIdentifiers();
        // 记录是否含有指定串口
        boolean isExsist = false;
        // 循环通讯端口
        while (portList.hasMoreElements()) {
            commPortId = portList.nextElement();
            // 判断是否是串口
            if (commPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // 比较串口名称是否是指定串口
                if (paramConfig.getSerialNumber().equals(commPortId.getName())) {
                    // 串口存在
                    isExsist = true;
                    // 打开串口
                    try {
                        // open:(应用程序名【随意命名】,阻塞时等待的毫秒数)
                        serialPort = (SerialPort) commPortId.open(Object.class.getSimpleName(), 2000);
                        // 设置串口监听
                        serialPort.addEventListener(this);
                        // 设置串口数据时间有效(可监听)
                        serialPort.notifyOnDataAvailable(true);
                        // 设置串口通讯参数:波特率,数据位,停止位,校验方式
                        serialPort.setSerialPortParams(paramConfig.getBaudRate(), paramConfig.getDataBit(),
                                paramConfig.getStopBit(), paramConfig.getCheckoutBit());
                    } catch (PortInUseException e) {
                        System.out.println("端口被占用");
                    } catch (TooManyListenersException e) {
                        System.out.println("监听器过多");
                    } catch (UnsupportedCommOperationException e) {
                        System.out.println("不支持的COMM端口操作异常");
                    }
                    // 结束循环
                    break;
                }
            }
        }
        // 若不存在该串口则抛出异常
        if (!isExsist) {
            System.out.println("不存在该串口!");
        }
    }

    /**
     * 实现接口SerialPortEventListener中的方法 读取从串口中接收的数据
     */
    @Override
    public void serialEvent(SerialPortEvent event) {
        switch (event.getEventType()) {
            case SerialPortEvent.BI: // 通讯中断
            case SerialPortEvent.OE: // 溢位错误
            case SerialPortEvent.FE: // 帧错误
            case SerialPortEvent.PE: // 奇偶校验错误
            case SerialPortEvent.CD: // 载波检测
            case SerialPortEvent.CTS: // 清除发送
            case SerialPortEvent.DSR: // 数据设备准备好
            case SerialPortEvent.RI: // 响铃侦测
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 输出缓冲区已清空
                break;
            case SerialPortEvent.DATA_AVAILABLE: // 有数据到达
                // 调用读取数据的方法
                readComm();
                break;
            default:
                break;
        }
    }

    /**
     * 读取串口返回信息
     *
     * @author LinWenLi
     * @date 2018年7月21日下午3:43:04
     * @return: void
     */
    public void readComm() {
        try {
            inputStream = serialPort.getInputStream();
            // 通过输入流对象的available方法获取数组字节长度
            byte[] readBuffer = new byte[inputStream.available()];
            // 从线路上读取数据流
            int len = 0;
            while ((len = inputStream.read(readBuffer)) != -1) {
                //直接获取到的数据
                data = new String(readBuffer, 0, len).trim();
                //转为十六进制数据
                dataHex = bytesToHexString(readBuffer);
                //System.out.println("data::" + data);
                //System.out.println("dataHex:" + dataHex);// 读取后置空流对象
                //System.out.println("code1:" + dataHex.substring(6, 10));
                //System.out.println("code2:" + dataHex.substring(10, 14));
                //String ts = new BigInteger(dataHex.substring(6, 10), 16).toString();
                //String rs = new BigInteger(dataHex.substring(10, 14), 16).toString();
                //System.out.println("温度:" + Double.valueOf(rs)/10);
                //System.out.println("湿度:" + Double.valueOf(ts)/10);
                inputStream.close();
                inputStream = null;
                break;
            }
        } catch (IOException e) {
            System.out.println("读取串口数据时发生IO异常");
        }
    }

    /**
     * 发送信息到串口
     *
     * @throws
     * @author LinWenLi
     * @date 2018年7月21日下午3:45:22
     * @param: data
     * @return: void
     */
    public void sendComm(String data) {
        byte[] writerBuffer = null;
        try {
            writerBuffer = hexToByteArray(data);
            //writerBuffer = new byte[]{(byte)0x01, (byte)0x03, (byte) 0x00, (byte) 0x00,(byte) 0x00,(byte) 0x02,(byte) 0xc4,(byte) 0x0b};
        } catch (NumberFormatException e) {
            //throw new CustomException("命令格式错误!");
            System.out.println("命令格式错误!");
        }
        try {
            outputStream = serialPort.getOutputStream();
            outputStream.write(writerBuffer);
            outputStream.flush();
        } catch (NullPointerException e) {
            //throw new CustomException("找不到串口。");
            System.out.println("找不到串口。");
        } catch (IOException e) {
            //throw new CustomException("发送信息到串口时发生IO异常");
            System.out.println("发送信息到串口时发生IO异常");
        }
    }

    /**
     * 关闭串口
     *
     * @throws
     * @author LinWenLi
     * @date 2018年7月21日下午3:45:43
     * @Description: 关闭串口
     * @param:
     * @return: void
     */
    public void closeSerialPort() {
        if (serialPort != null) {
            serialPort.notifyOnDataAvailable(false);
            serialPort.removeEventListener();
            if (inputStream != null) {
                try {
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    //throw new CustomException("关闭输入流时发生IO异常");
                    System.out.println("发送信息到串口时发生IO异常");
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                    outputStream = null;
                } catch (IOException e) {
                    //throw new CustomException("关闭输出流时发生IO异常");
                    System.out.println("关闭输出流时发生IO异常");
                }
            }
            serialPort.close();
            serialPort = null;
        }
    }

    /**
     * 十六进制串口返回值获取
     */
    public String getDataHex() {
        String result = dataHex;
        // 置空执行结果
        dataHex = null;
        // 返回执行结果
        return result;
    }

    /**
     * 串口返回值获取
     */
    public String getData(StringBuilder sb) {
        String result = data;
        System.out.println("result::" + result);
        sb.append(result);
        System.out.println("sb::" + sb);
        // 置空执行结果
        data = null;
        // 返回执行结果
        return result;
    }

    /**
     * Hex字符串转byte
     *
     * @param inHex 待转换的Hex字符串
     * @return 转换后的byte
     */
    public static byte hexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    /**
     * hex字符串转byte数组
     *
     * @param inHex 待转换的Hex字符串
     * @return 转换后的byte数组结果
     */
    public static byte[] hexToByteArray(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            // 奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            inHex = "0" + inHex;
        } else {
            // 偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = hexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    /**
     * 数组转换成十六进制字符串
     *
     * @param
     * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
}

controller类

import com.qwings.ipmgbascale.config.ParamConfig;
import com.qwings.ipmgbascale.response.ResponseObject;
import com.qwings.ipmgbascale.util.SerialPortUtils;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/balance")
@CrossOrigin
public class IpmgbaScaleBalanceController {

    @Value(value = "${com.qwings.ipmgbascale.serialNumber}")
    private String serialNumber;

    @Value(value = "${com.qwings.ipmgbascale.baudRate}")
    private Integer baudRate;

    @Value(value = "${com.qwings.ipmgbascale.checkoutBit}")
    private Integer checkoutBit;

    @Value(value = "${com.qwings.ipmgbascale.dataBit}")
    private Integer dataBit;

    @Value(value = "${com.qwings.ipmgbascale.stopBit}")
    private Integer stopBit;

    @RequestMapping("/getMessage")
    @CrossOrigin
    public String getMessage(@RequestParam("callback") String callback){
        ResponseObject ro = new ResponseObject();
        // 实例化串口操作类对象
        SerialPortUtils serialPort = new SerialPortUtils();
        // 创建串口必要参数接收类并赋值,赋值串口号,波特率,校验位,数据位,停止位
        ParamConfig paramConfig = new ParamConfig(serialNumber, baudRate, checkoutBit, dataBit, stopBit);
        // 初始化设置,打开串口,开始监听读取串口数据
        serialPort.init(paramConfig);
        // 调用串口操作类的sendComm方法发送数据到串口
        serialPort.sendComm("52");// R 对应 ASII码值 52
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 获取十进制的返回信息  类似于  188.34 g
        ro.setData(serialPort.getData(new StringBuilder()));
        // 关闭串口
        serialPort.closeSerialPort();
        ro.setCode(200);
        ro.setMsg("OK");
        JSONObject jsonObject = JSONObject.fromObject(ro);
        System.out.println(callback + "(" + jsonObject + ")");
        return callback + "(" + jsonObject + ")";
    }
}

yml

server:
  servlet:
    context-path: /
  port: 9999
  ssl:
    protocol: TLS
    key-store: classpath:server.keystore
    key-store-password: 12345678
    key-store-type: JKS


com:
  qwings: 
    ipmgbascale:
      serialNumber: COM3
      baudRate: 9600
      checkoutBit: 0
      dataBit: 8
      stopBit: 1
    ipmgbascaleweighbridge:
      serialNumber: COM3   # USB-SERIAL CH340 # 串口号
      baudRate: 9600 # 波特率
      checkoutBit: 0  # 校验位
      dataBit: 8  # 数据位
      stopBit: 1  # 停止位

jsonp

// 地秤
function weighbridge(rowData){
	var id = rowData["ID"];
    $.ajax({
      type : "GET",
      url : "https://localhost:443/weighbridge/getMessage",
      dataType: 'jsonp',  // 请求方式为jsonp
      crossDomain: true,
      data : {},
      success : function(data){
        var weight = data.data;
	   $.ajax({
		type : "POST",
		url : "./jd",
		dataType : "text",
		data : {
		  cmd : "com.qwings.apps.resource.updateWeight",
		  sid : $("#sid").val(),
		  weight: weight,
		  id: id,
		  bindId : $("#processInstId").val()
	  },
	  success : function(res){
        var responseObject = JSON.parse(res);
        if (responseObject.result == "ok") {
          $("#FormGridTB_59103b18-22b6-44e7-84ec-6c2e3f736a06_Btn_Refresh").trigger("click");      
        }
	  }
	  });
      },
	 error : function(ro){
       console.log('ssssss')
	 }
    });
}

Java制作证书的工具keytool用法详解

有证书可以支持https,没有证书只能使用http

https://www.jb51.net/article/238417.htm