java 实现串口通讯

1、引入依赖

<dependency><groupId>org.scream3r</groupId><artifactId>jssc</artifactId><version>2.8.0</version>
</dependency>

2、配置启动串口

@Component
public class ContextHolder implements ApplicationContextAware{private static ApplicationContext applicationContext = null;@Overridepublic void setApplicationContext(ApplicationContext arg0) throws BeansException {if(ContextHolder.applicationContext == null){ContextHolder.applicationContext  = arg0;}System.out.println("========ApplicationContext配置成功,ContextHolder.getAppContext()获取applicationContext对象,applicationContext="+ ContextHolder.applicationContext+"========");}//获取applicationContextpublic static ApplicationContext getApplicationContext() {return applicationContext;}//通过name获取 Bean.public static Object getBean(String name){return getApplicationContext().getBean(name);}//通过class获取Bean.public static <T> T getBean(Class<T> clazz){return getApplicationContext().getBean(clazz);}//通过name,以及Clazz返回指定的Beanpublic static <T> T getBean(String name,Class<T> clazz){return getApplicationContext().getBean(name, clazz);}}
@Slf4j
@Component
public class SerialPortCanContext{//串口映射public static Map<String, SerialPort> serialPortMap = new ConcurrentHashMap<>();@PostConstructpublic void initSerialPort() throws Exception{String portName = "COM2";startSerialPort(portName);}/*** 初始化串口* @param portName*/public synchronized void startSerialPort(String portName){//如果有之前的串口就关闭SerialPort serialPort1 = serialPortMap.get(portName);if (serialPort1 != null){try {serialPort1.removeEventListener();serialPort1.closePort();} catch (SerialPortException e) {log.error(e.getMessage());}}//生成新的串口并打开SerialPort serialPort = new SerialPort(portName);try {serialPort.openPort();serialPort.setParams(SerialPort.BAUDRATE_256000,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_EVEN);serialPort.addEventListener(new HhdSerialPortListener());} catch (SerialPortException e) {log.error(e.getMessage());}serialPortMap.put(portName,serialPort);}
}
/*** @author fangyuan* @description 串口监听器* @date 2023年11月7日09:08:43**/
public class SerialPortListener implements SerialPortEventListener {private static Logger logger= LoggerFactory.getLogger(HhdSerialPortListener.class);private SerialPortCanContext serialPortCanContext;public SerialPortListener() {this.serialPortCanContext = ContextHolder.getBean(SerialPortCanContext.class);}@Overridepublic void serialEvent(SerialPortEvent serialPortEvent) {String portName = serialPortEvent.getPortName();if (StringUtils.isBlank(portName)){return;}//通过缓存拿到串口 没有就生成一下SerialPort serialPort = SerialPortCanContext.serialPortMap.get(portName);if (serialPort == null){serialPortCanContext.startSerialPort(portName);}try {String body = serialPort.readString();if (StringUtils.isBlank(body)){return;}logger.info("SerialPort : {}  received : {}",portName,body);int size = body.length() / 2;ByteBuf buf = Unpooled.buffer(size);buf.writeBytes(hexToBytes(body));//todo 再将buf数据进行后续处理} catch (SerialPortException e) {logger.error(e.getMessage());}}/*** 将16进制字符串转换为byte[]* @param hexStr* @return*/public static byte[] hexToBytes(String hexStr) {int len = hexStr.length();hexStr = hexStr.toUpperCase();byte[] des;if (len % 2 != 0 || len == 0) {return null;} else {int halfLen = len / 2;des = new byte[halfLen];char[] tempChars = hexStr.toCharArray();for (int i = 0; i < halfLen; ++i) {char c1 = tempChars[i * 2];char c2 = tempChars[i * 2 + 1];int tempI = 0;if (c1 >= '0' && c1 <= '9') {tempI += ((c1 - '0') << 4);} else if (c1 >= 'A' && c1 <= 'F') {tempI += (c1 - 'A' + 10) << 4;} else {return null;}if (c2 >= '0' && c2 <= '9') {tempI += (c2 - '0');} else if (c2 >= 'A' && c2 <= 'F') {tempI += (c2 - 'A' + 10);} else {return null;}des[i] = (byte) tempI;// system.out.println(des[i]);}return des;}}
}

3、 模拟串口发送消息

3、1 安装 Configure Virtual Serial Port Driver

链接:https://pan.baidu.com/s/1fQ76Fh07kzqPeKho9nb7CA?pwd=6533
提取码:6533
解压后安装,将安装后的 这两个文件复制到安装目录并覆盖之前的文件
在这里插入图片描述

在这里插入图片描述

增加映射串口
在这里插入图片描述
打开 我点电脑----> 右键属性 -------> 设备管理 --------->端口查看
有数据表示串口映射成功
在这里插入图片描述

3、2 安装打开 sscom

链接:https://pan.baidu.com/s/13csdZ5XEkZ-E9r5XRYXWVA?pwd=6533
提取码:6533

在这里插入图片描述

3、3 发送消息

在这里插入图片描述

接收消息
在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode【12】整数转罗马数字

题目&#xff1a; 思路&#xff1a; https://blog.csdn.net/m0_71120708/article/details/128769894 代码&#xff1a; public String intToRoman(int num) {String[] thousands new String[] {"", "M", "MM", "MMM"};String[] hun…

python基础练习题库实验3

题目1 编写一个程序&#xff0c;根据以下定价计算成本。 Number of itemsCost1-50每件3美元 邮费: 10美元超过50每件2美元 邮寄&#xff1a;免费 举个例子&#xff1a; 代码 items_num input("Enter the number of items: ") items_num_i int(items_num) ite…

linux如何重置root密码

目录 当我们想要重置root管理员密码时&#xff0c;我们可以有两种方法进行&#xff1a; 方法一、init方法 1、重启系统&#xff0c;在下图所示界面按e键 2、随后进入以下界面&#xff0c;、将ro修改为rw&#xff0c;在行末尾添加init/bin/sh。​编辑 3、随后按Ctrlx启动到s…

预定义宏指令

#define _CRT_SECURE_NO_WARNINGS #include <stdio.h>int main() {printf("%s\n", __FILE__);printf("%d\n", __LINE__);printf("%s\n", __DATE__);printf("%s\n", __TIME__);return 0; } 运行结果&#xff1a;

记录将excel表无变形的弄进word里面来

之前关于这个问题记录过一篇文章&#xff1a; 将excel中的表快速复制粘贴进word中且不变形-CSDN博客 今天记录另外一种方法&#xff1a;举例表述&#xff0c;excel表如图&#xff1a; 按F12&#xff0c;出现“另存为...”对话框&#xff0c;选择“单个文件网页”&#xff0c;…

算法 LeetCode 题解 | 最小栈

大家好&#xff0c;我是木川 一、题目描述 请你设计一个 最小栈 。它提供 push &#xff0c;pop &#xff0c;top 操作&#xff0c;并能在常数时间内检索到最小元素的栈。 实现 MinStack 类: MinStack() 初始化堆栈对象。void push(int val) 将元素val推入堆栈。void pop() 删除…

宏--offsetof使用

文章目录 宏介绍结构体测试代码运行结果 宏介绍 宏--offsetof(type, member)&#xff0c;type就是结构的类型&#xff0c;member就是需要的成员名。表达式的结果是一个size_t的值&#xff0c;表示这个指定成员开始存储的位置距离结构开始存储的位置偏移几个字节结构体 typede…

FISCO BCOS 3.0【03】配置和使用pythonSDK

官方技术文档&#xff1a;https://fisco-bcos-doc.readthedocs.io/zh-cn/latest/index.html 我们在官方技术文档的基础上&#xff0c;进行&#xff0c;对文档中一些不清楚的地方进行修正 依赖软件 Ubuntu sudo apt install -y zlib1g-dev libffi6 libffi-dev wget git初始化…

漫谈广告机制设计 | 万剑归宗:聊聊广告机制设计与收入提升的秘密(2)

书接上文漫谈广告机制设计 | 万剑归宗&#xff1a;聊聊广告机制设计与收入提升的秘密&#xff08;1&#xff09;&#xff0c;我们谈到流量作为一种有限资源&#xff0c;其分配方式&#xff08;或者交易方式&#xff09;也经历了几个阶段&#xff1a;第一个是谈判定价阶段&#…

【Go学习之 go mod】gomod小白入门,在github上发布自己的项目(项目初始化、项目发布、项目版本升级等)

参考 Go语言基础之包 | 李文周的博客Go mod的使用、发布、升级 | weiGo Module如何发布v2及以上版本1.2.7. go mod命令 — 新溪-gordon V1.7.9 文档golang go 包管理工具 go mod的详细介绍-腾讯云开发者社区-腾讯云Go Mod 常见错误的原因 | walker的博客 项目案例 oceanweav…

数据结构【DS】树的性质

度为m的树 m叉树 至少有一个节点的度m 允许所有节点的度都<m 一定是非空树&#xff0c;至少有m1个节点 可以是空树 节点数 总度数 1m叉树&#xff1a; 高度为h的m叉树 节点数最少为&#xff1a;h具有n个结点的m叉树 最大高度&#xff1a;n度为m的树&#xff1a; 具有…