使用Java进行串口SerialPort通讯
1.准备工作
2.JAVA程序的操作
- package com.cams.CaMSMobileService.SerialPort;
- import gnu.io.CommPort;
- import gnu.io.CommPortIdentifier;
- import gnu.io.NoSuchPortException;
- import gnu.io.PortInUseException;
- import gnu.io.SerialPort;
- import gnu.io.SerialPortEventListener;
- import gnu.io.UnsupportedCommOperationException;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.Enumeration;
- import java.util.TooManyListenersException;
- import com.cams.CaMSMobileService.SerialPort.exception.NoSuchPort;
- import com.cams.CaMSMobileService.SerialPort.exception.NotASerialPort;
- import com.cams.CaMSMobileService.SerialPort.exception.PortInUse;
- import com.cams.CaMSMobileService.SerialPort.exception.ReadDataFromSerialPortFailure;
- import com.cams.CaMSMobileService.SerialPort.exception.SendDataToSerialPortFailure;
- import com.cams.CaMSMobileService.SerialPort.exception.SerialPortInputStreamCloseFailure;
- import com.cams.CaMSMobileService.SerialPort.exception.SerialPortOutputStreamCloseFailure;
- import com.cams.CaMSMobileService.SerialPort.exception.SerialPortParameterFailure;
- import com.cams.CaMSMobileService.SerialPort.exception.TooManyListeners;
- public class SerialPortManager {
- /**
- * 查找所有可用端口
- *
- * @return 可用端口名称列表
- */
- @SuppressWarnings("unchecked")
- public static final ArrayList<String> findPort() {
- // 获得当前所有可用串口
- Enumeration<CommPortIdentifier> portList = CommPortIdentifier
- .getPortIdentifiers();
- ArrayList<String> portNameList = new ArrayList<String>();
- // 将可用串口名添加到List并返回该List
- while (portList.hasMoreElements()) {
- String portName = portList.nextElement().getName();
- portNameList.add(portName);
- }
- return portNameList;
- }
- /**
- * 打开串口
- *
- * @param portName
- * 端口名称
- * @param baudrate
- * 波特率
- * @return 串口对象
- * @throws SerialPortParameterFailure
- * 设置串口参数失败
- * @throws NotASerialPort
- * 端口指向设备不是串口类型
- * @throws NoSuchPort
- * 没有该端口对应的串口设备
- * @throws PortInUse
- * 端口已被占用
- */
- public static final SerialPort openPort(String portName, int baudrate)
- throws SerialPortParameterFailure, NotASerialPort, NoSuchPort,
- PortInUse {
- try {
- // 通过端口名识别端口
- CommPortIdentifier portIdentifier = CommPortIdentifier
- .getPortIdentifier(portName);
- // 打开端口,设置端口名与timeout(打开操作的超时时间)
- CommPort commPort = portIdentifier.open(portName, 2000);
- // 判断是不是串口
- if (commPort instanceof SerialPort) {
- SerialPort serialPort = (SerialPort) commPort;
- try {
- // 设置串口的波特率等参数
- serialPort.setSerialPortParams(baudrate,
- SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
- SerialPort.PARITY_NONE);
- } catch (UnsupportedCommOperationException e) {
- throw new SerialPortParameterFailure();
- }
- return serialPort;
- } else {
- // 不是串口
- throw new NotASerialPort();
- }
- } catch (NoSuchPortException e1) {
- throw new NoSuchPort();
- } catch (PortInUseException e2) {
- throw new PortInUse();
- }
- }
- /**
- * 关闭串口
- *
- * @param serialport
- * 待关闭的串口对象
- */
- public static void closePort(SerialPort serialPort) {
- if (serialPort != null) {
- serialPort.close();
- serialPort = null;
- }
- }
- /**
- * 向串口发送数据
- *
- * @param serialPort
- * 串口对象
- * @param order
- * 待发送数据
- * @throws SendDataToSerialPortFailure
- * 向串口发送数据失败
- * @throws SerialPortOutputStreamCloseFailure
- * 关闭串口对象的输出流出错
- */
- public static void sendToPort(SerialPort serialPort, byte[] order)
- throws SendDataToSerialPortFailure,
- SerialPortOutputStreamCloseFailure {
- OutputStream out = null;
- try {
- out = serialPort.getOutputStream();
- out.write(order);
- out.flush();
- } catch (IOException e) {
- throw new SendDataToSerialPortFailure();
- } finally {
- try {
- if (out != null) {
- out.close();
- out = null;
- }
- } catch (IOException e) {
- throw new SerialPortOutputStreamCloseFailure();
- }
- }
- }
- /**
- * 从串口读取数据
- *
- * @param serialPort
- * 当前已建立连接的SerialPort对象
- * @return 读取到的数据
- * @throws ReadDataFromSerialPortFailure
- * 从串口读取数据时出错
- * @throws SerialPortInputStreamCloseFailure
- * 关闭串口对象输入流出错
- */
- public static byte[] readFromPort(SerialPort serialPort)
- throws ReadDataFromSerialPortFailure,
- SerialPortInputStreamCloseFailure {
- InputStream in = null;
- byte[] bytes = null;
- try {
- in = serialPort.getInputStream();
- // 获取buffer里的数据长度
- int bufflenth = in.available();
- while (bufflenth != 0) {
- // 初始化byte数组为buffer中数据的长度
- bytes = new byte[bufflenth];
- in.read(bytes);
- bufflenth = in.available();
- }
- } catch (IOException e) {
- throw new ReadDataFromSerialPortFailure();
- } finally {
- try {
- if (in != null) {
- in.close();
- in = null;
- }
- } catch (IOException e) {
- throw new SerialPortInputStreamCloseFailure();
- }
- }
- return bytes;
- }
- /**
- * 添加监听器
- *
- * @param port
- * 串口对象
- * @param listener
- * 串口监听器
- * @throws TooManyListeners
- * 监听类对象过多
- */
- public static void addListener(SerialPort port,
- SerialPortEventListener listener) throws TooManyListeners {
- try {
- // 给串口添加监听器
- port.addEventListener(listener);
- // 设置当有数据到达时唤醒监听接收线程
- port.notifyOnDataAvailable(true);
- // 设置当通信中断时唤醒中断线程
- port.notifyOnBreakInterrupt(true);
- } catch (TooManyListenersException e) {
- throw new TooManyListeners();
- }
- }
- }
使用Java进行串口SerialPort通讯的更多相关文章
- java实现串口通讯
一. 准备工作 1. 点击此下载java串口通讯相关工具 2. 将RXTXcomm.jar放到 %JAVA_HOME%\jre\lib\ext\ 目录下,工程中引入该jar包 3. 将rxtxSe ...
- java读写串口数据
本博文参考自https://www.cnblogs.com/Dreamer-1/p/5523046.html 最近接触到了串口及其读写,在此记录java进行串口读写的过程. 1.导入串口支持包 需要下 ...
- Java实现串口通信的小样例
用Java实现串口通信(windows系统下),须要用到sun提供的串口包 javacomm20-win32.zip.当中要用到三个文件,配置例如以下: 1.comm.jar放置到 JAVA_HOME ...
- 用Java通过串口发送手机短信
用Java通过串口发短信其实很简单,因为有现成的类库供我们使用.有底层的类库,也有封装好一点的类库,下面我介绍一下在 Win32 平台下发送短信的方法. 如果你想用更底层的类库开发功能更强大的应用程序 ...
- 自制单片机之十七……PC与单片机RS-232串口的通讯和控制
这次我们来试着一步步的去掌握PC与单片机通过RS-232进行通讯和控制. 先说说我硬件的情况.我用的PC是个二手的IBM240小本本,十寸屏,赛扬400,机子很老了.但也有它的优点:1.串口,并口,P ...
- Java编写串口程序
用Java编写串口程序一般都会用到这个 http://fizzed.com/oss/rxtx-for-java 根据电脑的情况下载 解压以后有安装文档 For a JDK installation: ...
- java读取串口-mfz-rxtx-2.2-20081207-win-x86
1.下载jar包 RXTXcomm.jar 2.实现代码 package main; import java.awt.*; import java.awt.event.*; import java.i ...
- gRPC java 客户端,服务器端通讯使用json格式
使用 protobuf 作为通讯内容序列化的简单例子请看:http://www.cnblogs.com/ghj1976/p/5458176.html . 本文是使用 json 做为内容序列化的简单例子 ...
- c# 串口SerialPort
创建SerialPortFun类 using System; using System.Collections.Generic; using System.Linq; using System.Tex ...
随机推荐
- 洛谷 P1609 最小回文数 题解
这题其实并不难,重点在你对回文数的了解,根本就不需要高精度. 打个比方: 对于一个形如 ABCDEFGH 的整数 有且仅有一个比它大的最小回文数 有且仅有一个比它小的最大回文数 而整数 ABCDDCB ...
- 【干货】已Window7 系统为例,谈谈boot引导程序-------附带看看数据隐藏
来源:Unit 3: Unix/Linux File System 3.1 Unix/Linux File System Booting Process 使用工具:EnCase Forensic 学习 ...
- 恶意代码分析实战-PE资源提取
场景 1.提取恶意代码中的资源部分内容 思路 存在Loadresource函数的时候说明有一部分内容在资源里. 技术点 Lab1-4 ResourceHacker打开保存资源,载入IDA查看
- Phantomjs 抓取、分析某个页面加载时浏览器发起的所有的子请求
var page = require('webpage').create(), system = require('system'), address; if (system.args.length ...
- C# Json To Object 无废话
json字符串如下: { success : 0, errorMsg : "错误消息", data : { total : "总记录数", rows : [ { ...
- WCF开发中将net.tcp协议寄宿到IIS的方法
1 部署IIS 1.1 安装WAS IIS原本是不支持非HTTP协议的服务,为了让IIS支持net.tcp,必须先安装WAS(Windows Process Activation Service),即 ...
- c语言字符串函数大全(转)
函数名: stpcpy 功 能: 拷贝一个字符串到另一个 用 法: char *stpcpy(char *destin, char *source); 程序例: #include <stdio. ...
- Java web项目使用webSocket
前端: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8&qu ...
- ModelDriven 和 Preparable 拦截器
Params 拦截器 Parameters 拦截器将把表单字段映射到 ValueStack 栈的栈顶对象的各个属性中. 如果某个字段在模型里没有匹配的属性, Param 拦截器将尝试 ValueSta ...
- 【Java】 遍历HashMap
1.遍历键值对 使用map.entrySet(),注意foreach语句中的类型为Map.Entry<K, V> 2.遍历Key 使用map.keySet() 3.遍历Value 使用ma ...