java Rs232串口协议通讯

1.首先下载相应的jar文件

压缩包包括:RXTXcomm.jar(64位环境)、win32com.dll和javax.comm.properties。
下载地址:https://download.csdn.net/download/mr_yaoziyang/11939205
介绍:RXTXcomm.jar提供了通讯用的java API,win32com.dll提供了供RXTXcomm.jar调用的本地驱动接口,javax.comm.properties是这个驱动的类配置文件

2.拷贝RXTXcomm.jar到<JAVA_HOME>\jre\lib\ext目录下面;

3.拷贝javax.comm.properties到<JAVA_HOME>\jre\lib目录下面;

4.拷贝win32com.dll到<JAVA_HOME>\jre\bin目录下面;

5.封装Rs232Util.java 工具类


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

public class Rs232Util {
	private static Rs232Util rs232Util = null;

	static {
		// 在该类被ClassLoader加载时就初始化一个SerialTool对象
		if (rs232Util == null) {
			rs232Util = new Rs232Util();
		}
	}

	// 私有化SerialTool类的构造方法,不允许其他类生成SerialTool对象
	private Rs232Util() {

	}

	/**
	 * 获取提供服务的SerialTool对象
	 * 
	 * @return rs232Util
	 */
	public static Rs232Util getSerialTool() {
		if (rs232Util == null) {
			rs232Util = new Rs232Util();
		}
		return rs232Util;
	}

	/**
	 * 查找所有可用端口
	 * 
	 * @return 可用端口名称列表
	 */
	public static final ArrayList<String> findPort() {
		// 获得当前所有可用串口
		@SuppressWarnings("unchecked")
		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 PortInUseException
	 * @throws NoSuchPortException
	 * @throws NotASerialPort             端口指向设备不是串口类型
	 * @throws NoSuchPort                 没有该端口对应的串口设备
	 * @throws PortInUse                  端口已被占用
	 */

	public static final SerialPort openPort(String portName, int baudrate) {

		// 通过端口名识别端口
		CommPortIdentifier portIdentifier = null;
		CommPort commPort = null;
		try {
			portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
			// 打开端口,并给端口名字和一个timeout(打开操作的超时时间)
			commPort = portIdentifier.open(portName, 5000);
		} catch (NoSuchPortException e1) {
			e1.printStackTrace();
		} catch (PortInUseException e) {
			e.printStackTrace();
		}

		// 判断是不是串口
		if (commPort instanceof SerialPort) {

			SerialPort serialPort = (SerialPort) commPort;

			try {
				// 设置一下串口的波特率,载波位,停止位,校验位
				serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
						SerialPort.PARITY_NONE);
			} catch (UnsupportedCommOperationException e) {
				System.out.println("设置串口参数失败!打开串口操作未完成!");
			}

			System.out.println("Open " + portName + " sucessfully !");
			return serialPort;

		} else {
			System.out.println("端口号不是串口!");
			return null;
		}
	}

	/**
	 * 关闭串口
	 * 
	 * @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) {

		BufferedOutputStream out = null;
		try {
			out = new BufferedOutputStream(serialPort.getOutputStream());
			out.write(order);
			out.flush();
		} catch (IOException e) {
			System.out.println("串口数据发送流关闭失败!");
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (IOException e) {
				System.out.println("串口数据发送流关闭失败!");
			}
		}

	}

	/**
	 * 从串口读取数据
	 * 
	 * @param serialPort 当前已建立连接的SerialPort对象
	 * @return 读取到的数据
	 * @throws ReadDataFromSerialPortFailure     从串口读取数据时出错
	 * @throws SerialPortInputStreamCloseFailure 关闭串口对象输入流出错
	 */
	public static byte[] readFromPort(SerialPort serialPort) {

		InputStream in = null;
		byte[] bytes = null;
		try {
			in = new BufferedInputStream(serialPort.getInputStream());
			// in = serialPort.getInputStream();
			int bufflenth = in.available(); // 获取buffer里的数据长度
			if (bufflenth == 0) {
				closePort(serialPort);
				throw new NullPointerException("未返回数据");
			}
//			System.out.println("获取buffer里的数据长度:::"+bufflenth);
			while (bufflenth != 0) {
				bytes = new byte[bufflenth]; // 初始化byte数组为buffer中数据的长度
				in.read(bytes);
				bufflenth = in.available();
			}
		} catch (IOException e) {
			System.out.println("读取数据失败!");
		} finally {
			try {
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (IOException e) {
				System.out.println("串口数据读取流关闭失败!");
			}
		}
		return bytes;
	}

	/**
	 * 16进制转BCD码 发送命令请求
	 * 
	 * @param s
	 * @return
	 */
	public static byte[] hexStringToByteArray(String s) {
		int len = s.length();
		byte[] data = new byte[len / 2];
		try {
			for (int i = 0; i < len; i += 2) {
				data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
			}
		} catch (Exception e) {

		}
		return data;
	}

	/**
	 * 字节数组转16进制
	 * 
	 * @param bytes
	 * @return
	 */
	public static String bytesToHex(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() < 2) {
				sb.append(0);
			}
			sb.append(hex);
		}
		return sb.toString();
	}

	/**
	 * @函数功能: BCD码转为10进制串(阿拉伯数据)
	 * @输入参数: BCD码
	 * @输出结果: 10进制串
	 */
	public static String bcd2Str(byte[] bytes) {
		StringBuffer temp = new StringBuffer(bytes.length * 2);

		for (int i = 0; i < bytes.length; i++) {
			temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
			temp.append((byte) (bytes[i] & 0x0f));
		}
		return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp.toString().substring(1) : temp.toString();
	}

	/**
	 * @函数功能: 10进制串转为BCD码
	 * @输入参数: 10进制串
	 * @输出结果: BCD码
	 */
	public static byte[] str2Bcd(String asc) {
		int len = asc.length();
		int mod = len % 2;
		if (mod != 0) {
			asc = "0" + asc;
			len = asc.length();
		}
		byte abt[] = new byte[len];
		if (len >= 2) {
			len = len / 2;
		}
		byte bbt[] = new byte[len];
		abt = asc.getBytes();
		int j, k;
		for (int p = 0; p < asc.length() / 2; p++) {
			if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
				j = abt[2 * p] - '0';
			} else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
				j = abt[2 * p] - 'a' + 0x0a;
			} else {
				j = abt[2 * p] - 'A' + 0x0a;
			}

			if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
				k = abt[2 * p + 1] - '0';
			} else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
				k = abt[2 * p + 1] - 'a' + 0x0a;
			} else {
				k = abt[2 * p + 1] - 'A' + 0x0a;
			}
			int a = (j << 4) + k;
			byte b = (byte) a;
			bbt[p] = b;
		}
		return bbt;
	}

	/**
	 * 把byte转为字符串的bit
	 * 
	 * @param b
	 * @return
	 */
	public static String byteToBit(byte b) {
		return "" + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1) + (byte) ((b >> 5) & 0x1)
				+ (byte) ((b >> 4) & 0x1) + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1) + (byte) ((b >> 1) & 0x1)
				+ (byte) ((b >> 0) & 0x1);
	}

	/**
	 * 把bit转为字节 byte
	 * 
	 * @param byteStr
	 * @return
	 */
	public static byte bitToByte(String byteStr) {
		int re, len;
		if (null == byteStr) {
			return 0;
		}
		len = byteStr.length();
		if (len != 4 && len != 8) {
			return 0;
		}
		if (len == 8) {// 8 bit处理
			if (byteStr.charAt(0) == '0') {// 正数
				re = Integer.parseInt(byteStr, 2);
			} else {// 负数
				re = Integer.parseInt(byteStr, 2) - 256;
			}
		} else {// 4 bit处理
			re = Integer.parseInt(byteStr, 2);
		}
		return (byte) re;
	}
	/**
	 * 将字符串转成ASCII
	 * 
	 * @param value
	 * @return
	 */
	public static String stringToAscii(String value) {
		StringBuffer sbu = new StringBuffer();
		char[] chars = value.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if (i != chars.length - 1) {
				sbu.append((int) chars[i]).append(",");
			} else {
				sbu.append((int) chars[i]);
			}
		}
		return sbu.toString();
	}

	/**
	 * 将ASCII转成字符串的
	 * 
	 * @param value
	 * @return
	 */
	public static String asciiToString(String value) {
		StringBuffer sbu = new StringBuffer();
		String[] chars = value.split(",");
		for (int i = 0; i < chars.length; i++) {
			sbu.append((char) Integer.parseInt(chars[i]));
		}
		return sbu.toString();
	}
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值