Java串口通信

1.javax.comm(过于陈旧)

 <dependency>
      <groupId>javax.comm</groupId>
      <artifactId>comm</artifactId>
      <version>2.0.3</version>
 </dependency>

2.gnu.io.*(新) 32位本地库

<dependency>
     <groupId>org.rxtx</groupId>
     <artifactId>rxtx</artifactId>
     <version>2.1.7</version>
     <scope>test</scope>
 </dependency>

64位的需要依赖2.2.pre版本,maven仓无法找到

windows 需要依赖本地库,rxtxSerial.jar
linux 需要依赖本地库,rxtxSerial.so
http://mvnrepository.com/

public class SerialUtils {

    private static final Logger logger = LoggerFactory.getLogger(SerialUtils.class);

    static {
        String path = Class.class.getClass().getResource("/").getPath();
        path = path.substring(0, path.indexOf("target"));
        System.load(path + "src\\main\\resource\\lib\\rxtxSerial.dll");
        System.load(path + "src\\main\\resource\\lib\\rxtxParallel.dll");
    }

    /**
     * 查找所有可用端口
     *
     * @return 可用端口名称列表
     */
    public static ArrayList<String> findPort() {
        //获得当前所有可用串口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
        ArrayList<String> portNameList = new ArrayList<>();

        //将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }
        return portNameList;
    }

    /**
     * 打开串口
     *
     * @param portName 端口名称
     * @param baudrate 波特率
     * @return 串口对象
     */
    public static SerialPort openPort(String portName, int baudrate) {
        try {
            //通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            //打开端口,并给端口名字和一个timeout(打开操作的超时时间)
            CommPort commPort = portIdentifier.open(portName, 2000);
            //判断是不是串口
            if (commPort instanceof SerialPort && portIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                SerialPort serialPort = (SerialPort) commPort;
                //设置一下串口的波特率等参数
                serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                return serialPort;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 往串口发送数据
     *
     * @param serialPort 串口对象
     * @param order      待发送数据
     */
    public static void sendToPort(SerialPort serialPort, byte[] order) {
        OutputStream out = null;
        try {
            out = serialPort.getOutputStream();
            out.write(order);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从串口读取数据
     *
     * @param serialPort 当前已建立连接的SerialPort对象
     * @return 读取到的数据
     */
    public static byte[] readFromPort(SerialPort serialPort) {
        InputStream in = null;
        byte[] bytes = null;
        try {
            in = serialPort.getInputStream();
            int bufflenth = in.available();        //获取buffer里的数据长度
            while (bufflenth != 0) {
                bytes = new byte[bufflenth];    //初始化byte数组为buffer中数据的长度
                in.read(bytes);
                bufflenth = in.available();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    /**
     * 自定义串口指令实例
     * @param serialPort
     * @param serialCmd
     * @param sendWaitTime
     * @param respOutTime
     * @return
     */
    public static String writeAndRead(SerialPort serialPort, String serialCmd, long sendWaitTime, long respOutTime) {
        serialCmd = serialCmd + "\n";
        byte[] cmdSend = serialCmd.getBytes();
        logger.info("serialCmd:" + serialCmd);
        sendToPort(serialPort, cmdSend);
        String res = null;
        try {
            Thread.sleep(sendWaitTime);
            long start = System.currentTimeMillis();
            byte[] result = readFromPort(serialPort);
            while ((respOutTime - sendWaitTime) > (System.currentTimeMillis() - start)) {
                if (result != null) {
                    res = new String(result);
                    res = res.replace("\r\n", "").trim();
                    logger.info("relust:" + res);
                    return res;
                }
            }
            logger.info("serialCmd TimeOut!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * SerialCmdEntity 封装传入
     * @param serialPort
     * @param serialCmdEntity
     * @return
     */
    public static String writeAndRead(SerialPort serialPort, SerialCmdEntity serialCmdEntity) {
        String serialCmd = serialCmdEntity.getCmd() + "\n";
        byte[] cmdSend = serialCmd.getBytes();
        logger.info("serialCmd:" + serialCmd);
        sendToPort(serialPort, cmdSend);
        String res = null;
        try {
            Thread.sleep(serialCmdEntity.getSendWaitTime());
            long start = System.currentTimeMillis();
            byte[] result = readFromPort(serialPort);
            while ((serialCmdEntity.getRespOutTime() - serialCmdEntity.getSendWaitTime()) > (System.currentTimeMillis() - start)) {
                if (result != null) {
                    res = new String(result);
                    res = res.replace("\r\n", "").trim();
                    logger.info("relust:" + res);
                    return res;
                }
            }
            logger.info("serialCmd TimeOut!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭串口
     *
     * @param serialPort 待关闭的串口对象
     */
    public static void closePort(SerialPort serialPort) {
        if (serialPort != null) {
            serialPort.close();
            serialPort = null;
        }
    }
}

学习:https://blog.csdn.net/u013363811/article/details/44225303
https://blog.csdn.net/kong_gu_you_lan/article/details/52302075

    public synchronized static String exeCmd(String commandStr) {
        BufferedReader br = null;
        try {
            p = Runtime.getRuntime().exec(commandStr);
            p.waitFor();
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            //System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    res = sb.toString();
                    br.close();
                    p.destroy();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值