Java实现RS485串口通信,发送和接收数据进行解析
最近项目有一个空气检测仪,需要得到空气检测仪的实时数据,保存到数据库当中。根据了解得到,硬件是通过rs485进行串口通讯的,需要发送16进制命令给仪器,然后通过轮询来得到数据。
需要先要下载RXTX的jar包,win64位下载地址:http://pan.baidu.com/s/1o6zLmTc);将解压后的rxtxParallel.dll和rxtxSerial.dll两个文件放在%JAVA_HOME%/jre/bin目录下,这样该包才能被正常的加载和调用。
代码如下:
package com.gpdi.sericlport; import gnu.io.*; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import com.gpdi.utils.*; public class ContinueRead extends Thread implements SerialPortEventListener { // SerialPortEventListener
// 监听器,我的理解是独立开辟一个线程监听串口数据
// 串口通信管理类
static CommPortIdentifier portId; /* 有效连接上的端口的枚举 */ static Enumeration<?> portList;
InputStream inputStream; // 从串口来的输入流
static OutputStream outputStream;// 向串口输出的流
static SerialPort serialPort; // 串口的引用
// 堵塞队列用来存放读到的数据
private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>(); @Override
/**
* SerialPort EventListene 的方法,持续监听端口上是否有数据流
*/
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:// 当有可用数据时读取数据
byte[] readBuffer = null;
int availableBytes = 0;
try {
availableBytes = inputStream.available();
while (availableBytes > 0) {
readBuffer = ContinueRead.readFromPort(serialPort);
String needData = printHexString(readBuffer);
System.out.println(new Date() + "真实收到的数据为:-----" + needData);
availableBytes = inputStream.available();
msgQueue.add(needData);
}
} catch (IOException e) {
}
default:
break;
}
} /**
* 从串口读取数据
*
* @param serialPort 当前已建立连接的SerialPort对象
* @return 读取到的数据
*/
public static byte[] readFromPort(SerialPort serialPort) {
InputStream in = null;
byte[] bytes = {};
try {
in = serialPort.getInputStream();
// 缓冲区大小为一个字节
byte[] readBuffer = new byte[1];
int bytesNum = in.read(readBuffer);
while (bytesNum > 0) {
bytes = MyUtils.concat(bytes, readBuffer);
bytesNum = in.read(readBuffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
in = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
} /**
* 通过程序打开COM4串口,设置监听器以及相关的参数
*
* @return 返回1 表示端口打开成功,返回 0表示端口打开失败
*/
public int startComPort() {
// 通过串口通信管理类获得当前连接上的串口列表
portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) {
// 获取相应串口对象
portId = (CommPortIdentifier) portList.nextElement(); System.out.println("设备类型:--->" + portId.getPortType());
System.out.println("设备名称:---->" + portId.getName());
// 判断端口类型是否为串口
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
// 判断如果COM4串口存在,就打开该串口
if (portId.getName().equals(portId.getName())) {
try {
// 打开串口名字为COM_4(名字任意),延迟为1000毫秒
serialPort = (SerialPort) portId.open(portId.getName(), 1000); } catch (PortInUseException e) {
System.out.println("打开端口失败!");
e.printStackTrace();
return 0;
}
// 设置当前串口的输入输出流
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
return 0;
}
// 给当前串口添加一个监听器
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
e.printStackTrace();
return 0;
}
// 设置监听器生效,即:当有数据时通知
serialPort.notifyOnDataAvailable(true); // 设置串口的一些读写参数
try {
// 比特率、数据位、停止位、奇偶校验位
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
return 0;
}
return 1;
}
}
}
return 0;
} @Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("--------------任务处理线程运行了--------------");
while (true) {
// 如果堵塞队列中存在数据就将其输出
if (msgQueue.size() > 0) {
String vo = msgQueue.peek();
String vos[] = vo.split(" ", -1);
getData(vos);
sendOrder();
msgQueue.take();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* @Description: 发送获取数据指令
* @Param:
* @return:
* @Author: LiangZF
* @Date: 2019/1/3
*/
public void sendOrder() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int i = 1;
if (i == 1) {
// 启动线程来处理收到的数据
try {
byte[] b = new byte[]{0x01, 0x03, 0x00, 0x00, 0x00, 0x0E, (byte) 0xC4, 0x0E};
System.out.println("发送的数据:" + b);
System.out.println("发出字节数:" + b.length);
outputStream.write(b);
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
serialPort.close();
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} /**
* @Description:通过数组解析检测数据
* @Param: [vo]
* @return: void
* @Author: LiangZF
* @Date: 2019/1/4
*/
public void getData(String[] vos) {
// 数组不为空
if (vos != null || vos.length != 0) {
// 风向数据
long wind_direction = getNum(vos[3], vos[4]);
System.out.println(wind_direction);
// 风速数据
long wind_speech = getNum(vos[5], vos[6]);
System.out.println(wind_speech);
// pm2.5
long polutionPm2 = getNum(vos[7], vos[8]);
System.out.println(polutionPm2);
// pm10
long polutionPm10 = getNum(vos[9], vos[10]);
System.out.println(polutionPm10);
// VOC
long voc = getNum(vos[11], vos[12]);
System.out.println(voc);
// 温度
long polutionPm = getNum(vos[13], vos[14]) / 10;
System.out.println(polutionPm);
// 湿度
long temperature = getNum(vos[15], vos[16]) / 10;
System.out.println(temperature);
// 大气压力
long atmosphericPressure = getNum(vos[17], vos[18]);
System.out.println(atmosphericPressure);
// 臭氧
long ozone = getNum(vos[19], vos[20]) / 1000;
System.out.println(ozone);
// CO
long co = getNum(vos[21], vos[22]) / 100;
System.out.println(co);
Map<String, Long> map = new HashMap<>();
map.put("O3", ozone);
map.put("PM2.5", polutionPm2);
map.put("PM10", polutionPm10);
Map<String, Object> uu = AqiUtil.getAqiByPollutants(map);
String pollutants = (String) uu.get("key");
Integer aqi = (Integer) uu.get("value");
insertDb(wind_direction, wind_speech, polutionPm2, polutionPm10, voc, polutionPm, temperature, atmosphericPressure, ozone, co, pollutants, aqi);
}
} // 16转10计算
public long getNum(String num1, String num2) {
long value = Long.parseLong(num1, 16) * 256 + Long.parseLong(num2, 16);
return value;
}
/**
* @Description: 保存到数据库表中
* @Param: [wind_direction, wind_speech, polutionPm2, polutionPm10, voc, polutionPm, temperature, atmosphericPressure, ozone, co, pollution, aqi]
* @return: void
* @Author: LiangZF
* @Date: 2019/1/6
*/
public void insertDb(long wind_direction, long wind_speech, long polutionPm2, long polutionPm10, long voc, long polutionPm, long temperature, long atmosphericPressure, long ozone, long co, String pollution, Integer aqi) {
Connection conn = null;
PreparedStatement ps = null;
FileInputStream in = null;
try {
conn = DBUtil.getConn();
String sql = "insert into air_status (wind_direction,wind_speed,particulate_matter,particulate_matter_one,voc,weather,humidity,air_pre,ozone,carbon_monoxide,del_flag,create_time,primary_pollutants,aqi)values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setLong(1, wind_direction);
ps.setLong(2, wind_speech);
ps.setLong(3, polutionPm2);
ps.setLong(4, polutionPm10);
ps.setLong(5, voc);
ps.setLong(6, polutionPm);
ps.setLong(7, temperature);
ps.setLong(8, atmosphericPressure);
ps.setLong(9, ozone);
ps.setLong(10, co);
ps.setInt(11, 0);
Timestamp time = new Timestamp(System.currentTimeMillis());//获取系统当前时间
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = df.format(time);
time = Timestamp.valueOf(timeStr);
ps.setTimestamp(12, time);
ps.setString(13, pollution);
ps.setInt(14, aqi);
int count = ps.executeUpdate();
if (count > 0) {
System.out.println("插入成功!");
} else {
System.out.println("插入失败!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeConn(conn);
if (null != ps) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} public static void main(String[] args) {
ContinueRead cRead = new ContinueRead();
System.out.println("asdasd");
int i = cRead.startComPort();
if (i == 1) {
// 启动线程来处理收到的数据
cRead.start();
try {
//根据提供的文档给出的发送命令,发送16进制数据给仪器
byte[] b = new byte[]{0x01, 0x03, 0x00, 0x00, 0x00, 0x0E, (byte) 0xC4, 0x0E};
System.out.println("发送的数据:" + b);
System.out.println("发出字节数:" + b.length);
outputStream.write(b);
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return;
}
} // 字节数组转字符串
private String printHexString(byte[] b) { StringBuffer sbf = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sbf.append(hex.toUpperCase() + " ");
}
return sbf.toString().trim();
}
}
MyUtils工具类
因为得到的byte数组会分成几段,需要进行合并数组操作。
/**
* 合并数组
*
* @param firstArray 第一个数组
* @param secondArray 第二个数组
* @return 合并后的数组
*/
public static byte[] concat(byte[] firstArray, byte[] secondArray) {
if (firstArray == null || secondArray == null) {
if (firstArray != null)
return firstArray;
if (secondArray != null)
return secondArray;
return null;
}
byte[] bytes = new byte[firstArray.length + secondArray.length];
System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);
System.arraycopy(secondArray, 0, bytes, firstArray.length, secondArray.length);
return bytes;
}
参考文章:https://blog.csdn.net/update_java/article/details/46898937
下载地址 https://github.com/732847260/RS485
Java实现RS485串口通信,发送和接收数据进行解析的更多相关文章
- Java实现RS485串口通信
前言 前段时间赶项目的过程中,遇到一个调用RS485串口通信的需求,赶完项目因为楼主处理私事,没来得及完成文章的更新,现在终于可以整理一下当时的demo,记录下来. 首先说一下大概需求:这个项目是机器 ...
- Python编程实现USB转RS485串口通信
---作者吴疆,未经允许,严禁转载,违权必究--- ---欢迎指正,需要源码和文件可站内私信联系--- -----------点击此处链接至博客园原文----------- 功能说明:Python编程 ...
- 手把手教你Android手机与BLE终端通信--连接,发送和接收数据
假设你还没有看上一篇 手把手教你Android手机与BLE终端通信--搜索,你就先看看吧,由于这一篇要接着讲搜索到蓝牙后的连接.和连接后的发送和接收数据. 评论里有非常多人问假设一条信息特别长,怎么不 ...
- java下的串口通信-RXTX
关于java实现的串口通信,使用的是开源项目RXTX,之前sun公司也有JCL项目,不过已经很久没有更新了,RXTX项目地址:点击打开,但是两个项目的API用法是一样的,只是导入的包不一样而已.简单的 ...
- [Socket网络编程]由于套接字没有连接并且(当使用一个 sendto 调用发送数据报套接字时)没有提供地址,发送或接收数据的请求没有被接受。
原文地址:http://blog.sina.com.cn/s/blog_70bf579801017ylu.html,记录在此方便查看 解决办法: MSDN的说明: Close 方法可关闭远程主机连接, ...
- Netty——高级发送和接收数据handler处理器
netty发送和接收数据handler处理器 主要是继承 SimpleChannelInboundHandler 和 ChannelInboundHandlerAdapter 一般用netty来发送和 ...
- netty发送和接收数据handler处理器
netty发送和接收数据handler处理器 主要是继承 SimpleChannelInboundHandler 和 ChannelInboundHandlerAdapter 一般用netty来发送和 ...
- udp网络程序-发送、接收数据
1. udp网络程序-发送数据 创建一个基于udp的网络程序流程很简单,具体步骤如下: 创建客户端套接字 发送/接收数据 关闭套接字 代码如下: #coding=utf-8from socket im ...
- socket 错误之:OSError: [WinError 10057] 由于套接字没有连接并且(当使用一个 sendto 调用发送数据报套接字时)没有提供地址,发送或接收数据的请求没有被接受。
出错的代码 #server端 import socket import struct sk=socket.socket() sk.bind(('127.0.0.1',8080)) sk.listen( ...
随机推荐
- XXL-JOB使用命令行的方式启动python时,日志过多导致阻塞的解决方式
一.Runtime.getRuntime().exec()的阻塞问题 这个问题也不能算是XXL-JOB的问题,而是Java的Runtime.getRuntime().exec()造成的,Buffere ...
- python入门基础 02
目录 1.while 2.字符串格式化 3.运算符 4.编码初始 总结 1.while # while -- 关键字 (死循环) # # if 条件: # 结果 # # while 条件: # 循环体 ...
- python安装和pycharm安装与笔记
目录 计算机的基础知识 python安装和使用 pycharm安装和使用 [TOC] 计算机的基础知识 计算机是由什么组成的 cpu-----大脑 主板----身体 电源----心脏 内存----临时 ...
- jquery实现弹出层完美居中效果
代码如下: showDiv($("#pop"));function showDiv(obj){ $(obj).show(); center(obj); $(window).scro ...
- linux技能点七 shell
shell脚本:定义,连接符,输入输出流,消息重定向,命令的退出状态,申明变量,运算符,控制语句 定义:linux下的多命令操作文件 连接符: ::用于命令的分隔符,命令会从左往右依次执行 & ...
- Python实现柱状图【数字精准展示,使用不同颜色】
一.简介 主要使用matplotlib基于python的可视化组件实现. 二.代码实现 # -*- coding: utf-8 -*- """ Created on Mo ...
- vue 对 v-for 中数组进行过滤操作
之前写angularjs的时候,filter是可以直接在ng-repeat中使用.但是到了vue好像这个不起作用. 具体解决办法: 加一个计算属性: computed:{ filterData: fu ...
- Mysql 库表操作初识
Mysql 库表操作初识 终端登录mysql 这里只演示win下, cmd 终端. 至于怎么在win下, linux, mac安装, 感觉这是一个入门级的百度搜索问题, 安装都搞不定, 确实有点尴尬, ...
- Flask入门很轻松(三)—— 模板
Jinja2模板引擎 转载请在文章开头附上原文链接地址:https://www.cnblogs.com/Sunzz/p/10959471.html Flask内置的模板语言,它的设计思想来源于 Dja ...
- MySQL-CentOS7上安装Mysql5.7
#安装 wget http://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm .noarch.rpm yum instal ...