程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> JAVA串口通訊程序

JAVA串口通訊程序

編輯:JAVA綜合教程

JAVA串口通訊程序


package com.jetf.serialport;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;

import javax.imageio.ImageIO;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import com.jetf.mm.CRC16;
import com.jfinal.kit.StrKit;

public class JavaRs232 extends JFrame implements ActionListener,
		SerialPortEventListener {

	/**
	 * JDK Serial Version UID
	 */
	private static final long serialVersionUID = -7270865686330790103L;

	protected int WIN_WIDTH = 500;
	protected int WIN_HEIGHT = 420;

	private JComboBox portCombox, rateCombox, dataCombox, stopCombox,
			parityCombox, parityCombox1;

	private Button openPortBtn, closePortBtn, sendMsgBtn, sendMsgBtn1;

	private TextField sendTf;
	private TextField sendD1;
	private TextField sendD2;
	private TextField sendD3;

	private TextField sendTf1;

	private TextArea readTa;

	private JLabel statusLb;

	private String portname, rate, data, stop, parity;

	protected CommPortIdentifier portId;

	protected Enumeration ports;

	protected List portList;

	protected SerialPort serialPort;

	protected OutputStream outputStream = null;

	protected InputStream inputStream = null;

	protected String mesg;
	protected String mesg1;
	protected String mesg_info_D1;
	protected String mesg_info_D2;
	protected String mesg_info_D3;

	protected String[] mesgs;

	protected int sendCount, reciveCount;

	/**
	 * 默認構造函數
	 */
	public JavaRs232() {
		super("Java串口通信測試程序");
		setSize(WIN_WIDTH, WIN_HEIGHT);
		setLocationRelativeTo(null);
		Image icon = null;
		try {
			icon = ImageIO.read(JavaRs232.class
					.getResourceAsStream("rs232.png"));
		} catch (IOException e) {
			showErrMesgbox(e.getMessage());
		}
		setIconImage(icon);
		setResizable(false);
		scanPorts();
		initComponents();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

	/**
	 * 初始化各UI組件
	 * 
	 * @since 2012-3-22 下午11:56:39
	 */
	public void initComponents() {
		// 共用常量
		Font lbFont = new Font("微軟雅黑", Font.TRUETYPE_FONT, 14);

		// 創建左邊面板
		JPanel northPane = new JPanel();
		northPane.setLayout(new GridLayout(1, 1));
		// 設置左邊面板各組件
		JPanel leftPane = new JPanel();
		leftPane.setOpaque(false);
		leftPane.setLayout(new GridLayout(3, 2));
		JLabel portnameLb = new JLabel("串口號:");
		portnameLb.setFont(lbFont);
		portnameLb.setHorizontalAlignment(SwingConstants.RIGHT);
		portCombox = new JComboBox((String[]) portList.toArray(new String[0]));
		portCombox.addActionListener(this);
		JLabel databitsLb = new JLabel("數據位:");
		databitsLb.setFont(lbFont);
		databitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
		// 設置中間面板各組件
		dataCombox = new JComboBox(new Integer[] { 5, 6, 7, 8 });
		dataCombox.setSelectedIndex(3);
		dataCombox.addActionListener(this);
		JLabel parityLb = new JLabel("校驗位:");
		parityLb.setFont(lbFont);
		parityLb.setHorizontalAlignment(SwingConstants.RIGHT);
		parityCombox = new JComboBox(new String[] { "NONE", "ODD", "EVEN",
				"MARK", "SPACE" });
		parityCombox.addActionListener(this);

		JLabel parityLb1 = new JLabel("01寫:");
		parityLb1.setFont(lbFont);
		parityLb1.setLayout(new GridLayout(1, 1));
		parityLb1.setHorizontalAlignment(SwingConstants.RIGHT);
		// 設置中間面板各組件
		sendD1 = new TextField(5);

		JLabel parityLb2 = new JLabel("03讀:");
		parityLb2.setFont(lbFont);
		parityLb2.setLayout(new GridLayout(1, 1));
		parityLb2.setHorizontalAlignment(SwingConstants.RIGHT);
		// 設置中間面板各組件
		sendD3 = new TextField(5);

		JLabel parityLb3 = new JLabel("0002:");
		parityLb3.setFont(lbFont);
		parityLb3.setLayout(new GridLayout(1, 1));
		parityLb3.setHorizontalAlignment(SwingConstants.RIGHT);
		// 設置中間面板各組件
		sendD2 = new TextField(5);

		// 添加組件至面板

		leftPane.add(portnameLb);
		leftPane.add(portCombox);
		leftPane.add(databitsLb);
		leftPane.add(dataCombox);
		leftPane.add(parityLb);
		leftPane.add(parityCombox);

		leftPane.add(parityLb1);
		leftPane.add(sendD1);
		leftPane.add(parityLb2);
		leftPane.add(sendD3);
		leftPane.add(parityLb3);
		leftPane.add(sendD2);

		// 創建右邊面板
		JPanel rightPane = new JPanel();
		rightPane.setLayout(new GridLayout(3, 2));
		// 設置右邊面板各組件
		JLabel baudrateLb = new JLabel("波特率:");
		baudrateLb.setFont(lbFont);
		baudrateLb.setHorizontalAlignment(SwingConstants.RIGHT);
		rateCombox = new JComboBox(new Integer[] { 2400, 4800, 9600, 14400,
				19200, 38400, 56000 });
		rateCombox.setSelectedIndex(2);
		rateCombox.addActionListener(this);

		JLabel stopbitsLb = new JLabel("停止位:");
		stopbitsLb.setFont(lbFont);
		stopbitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
		stopCombox = new JComboBox(new String[] { "1", "2", "1.5" });
		stopCombox.addActionListener(this);

		// JLabel stopbitsLb4 = new JLabel("DDDD:");
		// stopbitsLb4.setFont(lbFont);
		// stopbitsLb4.setHorizontalAlignment(SwingConstants.RIGHT);
		// sendTf = new TextField(5);

		openPortBtn = new Button("start");
		openPortBtn.addActionListener(this);
		closePortBtn = new Button("coles");
		closePortBtn.addActionListener(this);
		// 添加組件至面板
		rightPane.add(baudrateLb);
		rightPane.add(rateCombox);
		rightPane.add(stopbitsLb);
		rightPane.add(stopCombox);

		// rightPane.add(stopbitsLb4);
		// rightPane.add(sendTf);

		rightPane.add(openPortBtn);
		rightPane.add(closePortBtn);
		// 將左右面板組合添加到北邊的面板
		northPane.add(leftPane);
		northPane.add(rightPane);

		JLabel stopbitsLbdd = new JLabel("地址端口:");
		stopbitsLbdd.setFont(lbFont);
		stopbitsLbdd.setHorizontalAlignment(SwingConstants.RIGHT);

		// 創建中間面板
		JPanel centerPane = new JPanel();
		// 設置中間面板各組件
		sendTf = new TextField(30);
		readTa = new TextArea(8, 50);
		readTa.setEditable(false);
		readTa.setBackground(new Color(225, 242, 250));
		centerPane.add(sendTf);
		sendMsgBtn = new Button("send ");
		sendMsgBtn.addActionListener(this);

		JLabel stopbitsLbdd1 = new JLabel("地址:");
		stopbitsLbdd1.setFont(lbFont);
		stopbitsLbdd1.setHorizontalAlignment(SwingConstants.RIGHT);
		sendTf1 = new TextField(20);
		sendMsgBtn1 = new Button("send2 ");
		sendMsgBtn1.addActionListener(this);

		JLabel parityLb4 = new JLabel("命令:");
		parityLb4.setFont(lbFont);
		parityLb4.setHorizontalAlignment(SwingConstants.RIGHT);
		parityCombox1 = new JComboBox(new String[] { "上傳開關量", "上傳SOE整定值",
				"標志信息模擬量" });
		parityCombox1.addActionListener(this);

		// 添加組件至面板
		centerPane.add(stopbitsLbdd);
		centerPane.add(sendTf);
		centerPane.add(sendMsgBtn);
		centerPane.add(readTa);
		centerPane.add(parityLb4);
		centerPane.add(parityCombox1);
		centerPane.add(stopbitsLbdd1);
		centerPane.add(sendTf1);
		centerPane.add(sendMsgBtn1);
		// 設置南邊組件
		statusLb = new JLabel();
		statusLb.setText(initStatus());
		statusLb.setOpaque(true);

		// 獲取主窗體的容器,並將以上三面板以北、中、南的布局整合
		JPanel contentPane = (JPanel) getContentPane();
		contentPane.setLayout(new BorderLayout());
		contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
		contentPane.setOpaque(false);
		contentPane.add(northPane, BorderLayout.NORTH);
		contentPane.add(centerPane, BorderLayout.CENTER);

		contentPane.add(statusLb, BorderLayout.SOUTH);
	}

	/**
	 * 初始化狀態標簽顯示文本
	 * 
	 * @return String
	 * @since 2012-3-23 上午12:01:53
	 */
	public String initStatus() {
		portname = portCombox.getSelectedItem().toString();
		rate = rateCombox.getSelectedItem().toString();
		data = dataCombox.getSelectedItem().toString();
		stop = stopCombox.getSelectedItem().toString();
		parity = parityCombox.getSelectedItem().toString();

		StringBuffer str = new StringBuffer("當前串口號:");
		str.append(portname).append(" 波特率:");
		str.append(rate).append(" 數據位:");
		str.append(data).append(" 停止位:");
		str.append(stop).append(" 校驗位:");
		str.append(parity);
		return str.toString();
	}

	/**
	 * 掃描本機的所有COM端口
	 * 
	 * @since 2012-3-23 上午12:02:42
	 */
	public void scanPorts() {
		portList = new ArrayList();
		Enumeration en = CommPortIdentifier.getPortIdentifiers();
		CommPortIdentifier portId;
		while (en.hasMoreElements()) {
			portId = (CommPortIdentifier) en.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				String name = portId.getName();
				if (!portList.contains(name)) {
					portList.add(name);
				}
			}
		}
		if (null == portList || portList.isEmpty()) {
			showErrMesgbox("未找到可用的串行端口號,程序無法啟動!");
			System.exit(0);
		}
	}

	/**
	 * 打開串行端口
	 * 
	 * @since 2012-3-23 上午12:03:07
	 */
	public void openSerialPort() {
		// 獲取要打開的端口
		try {
			portId = CommPortIdentifier.getPortIdentifier(portname);
		} catch (NoSuchPortException e) {
			showErrMesgbox("抱歉,沒有找到" + portname + "串行端口號!");
			setComponentsEnabled(true);
			return;
		}
		// 打開端口
		try {
			serialPort = (SerialPort) portId.open("JavaRs232", 3927);
			statusLb.setText(portname + "串口已經打開!");
		} catch (PortInUseException e) {
			showErrMesgbox(portname + "端口已被占用,請檢查!");
			setComponentsEnabled(true);
			return;
		}
		// 打開端口的IO流管道
		try {
			outputStream = serialPort.getOutputStream();
			inputStream = serialPort.getInputStream();
		} catch (IOException e) {
			showErrMesgbox(e.getMessage());
		}

		// 給端口添加監聽器
		try {
			serialPort.addEventListener(this);
		} catch (TooManyListenersException e) {
			showErrMesgbox(e.getMessage());
		}

		serialPort.notifyOnDataAvailable(true);
		// 設置端口參數
		try {
			int rate = Integer.parseInt(this.rate);
			int data = Integer.parseInt(this.data);
			int stop = stopCombox.getSelectedIndex() + 1;
			int parity = parityCombox.getSelectedIndex();
			System.out.println("rate:" + rate);
			System.out.println("data:" + data);
			System.out.println("stop:" + stop);
			System.out.println("parity:" + parity);
			serialPort.setSerialPortParams(rate, data, stop, parity);
		} catch (UnsupportedCommOperationException e) {
			showErrMesgbox(e.getMessage());
		}

	}

	/**
	 * 給串行端口發送數據
	 * 
	 * @since 2012-3-23 上午12:05:00
	 */
	public void sendDataToSeriaPort(String mesg_info) {
		byte[] sbuf = null;
		String s_info = "";
		sbuf = CRC16.getSendBuf(mesg_info);
		s_info = CRC16.getBufHexStr(sbuf);
		try {
			sendCount++;
			outputStream.write(hexStringToBytes(s_info));
			outputStream.flush();
			StringBuilder receivedMsg = new StringBuilder();
			receivedMsg.append(receivedMsg)
					.append("發送數據: " + mesg_info + " \n");
			readTa.append(receivedMsg.toString());
		} catch (IOException e) {
			showErrMesgbox(e.getMessage());
			System.out.println(mesg_info);
		}
		statusLb.setText("  發送: " + sendCount
				+ "                                      接收: " + reciveCount);
	}

	/**
	 * 關閉串行端口
	 * 
	 * @since 2012-3-23 上午12:05:28
	 */
	public void closeSerialPort() {
		try {
			if (outputStream != null)
				outputStream.close();
			if (serialPort != null)
				serialPort.close();
			serialPort = null;
			statusLb.setText(portname + "串口已經關閉!");
			sendCount = 0;
			reciveCount = 0;
			sendTf.setText("");
			sendTf1.setText("");
			sendD1.setText("");
			sendD2.setText("");
			sendD3.setText("");
			readTa.setText("");
		} catch (Exception e) {
			showErrMesgbox(e.getMessage());
		}
	}

	/**
	 * 顯示錯誤或警告信息
	 * 
	 * @param msg
	 *            信息
	 * @since 2012-3-23 上午12:05:47
	 */
	public void showErrMesgbox(String msg) {
		JOptionPane.showMessageDialog(this, msg);
	}

	/**
	 * 各組件行為事件監聽
	 */
	public void actionPerformed(ActionEvent e) {
		String msg_info = "";
		if (e.getSource() == portCombox || e.getSource() == rateCombox
				|| e.getSource() == dataCombox || e.getSource() == stopCombox
				|| e.getSource() == parityCombox) {
			statusLb.setText(initStatus());
		}
		if (e.getSource() == openPortBtn) {
			setComponentsEnabled(false);
			System.err.println("打開");
			openSerialPort();
		}
		if (e.getSource() == closePortBtn) {
			if (serialPort != null) {
				closeSerialPort();
			}
			setComponentsEnabled(true);
		}

		if (e.getSource() == sendMsgBtn) {
			if (serialPort == null) {
				showErrMesgbox("請先打開串行端口!");
				return;
			}
			mesg = sendTf.getText();
			mesg_info_D1 = sendD1.getText();
			mesg_info_D2 = sendD2.getText();
			mesg_info_D3 = sendD3.getText();
			String info_length = mesg + "" + mesg_info_D1 + "" + mesg_info_D2
					+ "" + mesg_info_D3;
			if (StrKit.isBlank(mesg) || StrKit.isBlank(mesg_info_D1)
					|| StrKit.isBlank(mesg_info_D2)
					|| StrKit.isBlank(mesg_info_D3)) {
				showErrMesgbox("4個文本框必須填寫完整!");
				return;
			} else {
				boolean result = info_length.matches("[0-9]+");
				if (result) {
					msg_info = stringToHex16(mesg_info_D1, mesg_info_D2,
							mesg_info_D3, mesg);
				} else {
					showErrMesgbox("輸入內容中存在非法字符,內容只支持數字!");
					return;
				}

				if (msg_info.length() < 12) {
					showErrMesgbox("輸入內容長度不夠默認4個文本框總長度12位!");
					return;
				} else if (msg_info.length() > 12) {
					showErrMesgbox("輸入內容長度超限默認4個文本框總長度12位!");
					return;
				}
			}
			sendDataToSeriaPort(msg_info);
		}

		if (e.getSource() == sendMsgBtn1) {
			String sc_info = "";
			if (serialPort == null) {
				showErrMesgbox("請先打開串行端口!");
				return;
			}

			switch (parityCombox1.getSelectedIndex()) {
			case 0:
				sc_info = "0100000040";
				break;
			case 1:
				sc_info = "030000000B";
				break;
			case 2:
				sc_info = "0400000015";
				break;
			default:
				break;
			}
			mesg1 = sendTf1.getText();

			if (StrKit.isBlank(mesg1)) {
				showErrMesgbox("請填寫地址信息!");
				return;
			} else {
				boolean result = mesg1.matches("[0-9]+");
				if (result) {
					if (Integer.parseInt(mesg1) > 255) {
						showErrMesgbox("地址輸入有誤,1-255之間!");
						return;
					} else {
						msg_info = stringToHex16(mesg1);
					}

				} else {
					showErrMesgbox("輸入內容中存在非法字符,內容只支持數字!");
					return;
				}
			}
			sendDataToSeriaPort(msg_info + "" + sc_info);
		}
	}

	private String stringToHex16(String mesg12) {
		String msg = "";
		if (Integer.toString(Integer.parseInt(mesg12), 16).length() == 1) {
			mesg12 = "0" + Integer.toString(Integer.parseInt(mesg12), 16);
		} else {
			mesg12 = Integer.toString(Integer.parseInt(mesg12), 16);
		}
		msg = mesg12;
		return msg;

	}

	private String stringToHex16(String mesg_info_D1, String mesg_info_D2,
			String mesg_info_D3, String mesg) {
		String msg = "";
		if (Integer.toString(Integer.parseInt(mesg_info_D1), 16).length() == 1) {
			mesg_info_D1 = "0"
					+ Integer.toString(Integer.parseInt(mesg_info_D1), 16);
		} else {
			mesg_info_D1 = Integer.toString(Integer.parseInt(mesg_info_D1), 16);
		}

		if (Integer.toString(Integer.parseInt(mesg_info_D3), 16).length() == 1) {
			mesg_info_D3 = "0"
					+ Integer.toString(Integer.parseInt(mesg_info_D3), 16);
		} else {
			mesg_info_D3 = Integer.toString(Integer.parseInt(mesg_info_D3), 16);
		}
		if (Integer.toString(Integer.parseInt(mesg_info_D2), 16).length() == 1) {
			mesg_info_D2 = "000"
					+ Integer.toString(Integer.parseInt(mesg_info_D2), 16);
		} else if (Integer.toString(Integer.parseInt(mesg_info_D2), 16)
				.length() == 2) {
			mesg_info_D2 = "00"
					+ Integer.toString(Integer.parseInt(mesg_info_D2), 16);
		} else if (Integer.toString(Integer.parseInt(mesg_info_D2), 16)
				.length() == 3) {
			mesg_info_D2 = "0"
					+ Integer.toString(Integer.parseInt(mesg_info_D2), 16);
		} else {
			mesg_info_D2 = Integer.toString(Integer.parseInt(mesg_info_D2), 16);
		}

		if (Integer.toString(Integer.parseInt(mesg), 16).length() == 1) {
			mesg = "000" + Integer.toString(Integer.parseInt(mesg), 16);
		} else if (Integer.toString(Integer.parseInt(mesg), 16).length() == 2) {
			mesg = "00" + Integer.toString(Integer.parseInt(mesg), 16);
		} else if (Integer.toString(Integer.parseInt(mesg), 16).length() == 3) {
			mesg = "0" + Integer.toString(Integer.parseInt(mesg), 16);
		} else {
			mesg = Integer.toString(Integer.parseInt(mesg), 16);
		}
		msg = mesg_info_D1 + "" + mesg_info_D3 + "" + mesg + "" + mesg_info_D2;
		return msg;
	}

	/**
	 * 端口事件監聽
	 */
	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;
			try {
				Thread.sleep(30l);
			} catch (InterruptedException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			try {
				readBuffer = new byte[inputStream.available()];
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			try {
				while (inputStream.available() > 0) {
					inputStream.read(readBuffer);
				}
				System.out.println(byte2hex(readBuffer));
				String msg = byte2hex(readBuffer).trim();
				msg = msg.replaceAll(" ", "");
				String v_info = Float16(msg.substring(10, 14) + ""
						+ msg.substring(6, 10));
				StringBuilder receivedMsg = new StringBuilder();
				receivedMsg.append(receivedMsg).append(
						"回復數據: " + v_info + "V\n");
				readTa.append(receivedMsg.toString());
				reciveCount++;
				statusLb.setText("  發送: " + sendCount
						+ "                                      接收: "
						+ reciveCount);
			} catch (IOException e) {

			}

		}
	}

	/**
	 * 設置各組件的開關狀態
	 * 
	 * @param enabled
	 *            狀態
	 * @since 2012-3-23 上午12:06:24
	 */
	public void setComponentsEnabled(boolean enabled) {
		openPortBtn.setEnabled(enabled);
		openPortBtn.setEnabled(enabled);
		portCombox.setEnabled(enabled);
		rateCombox.setEnabled(enabled);
		dataCombox.setEnabled(enabled);
		stopCombox.setEnabled(enabled);
		parityCombox.setEnabled(enabled);
	}

	/**
	 * 運行主函數
	 * 
	 * @param args
	 * @since 2012-3-23 上午12:06:45
	 */
	public static void main(String[] args) {
		new JavaRs232();
	}

	public String readPort() {
		byte[] readBuffer = new byte[50];

		try {
			while (inputStream.available() > 0) {
				inputStream.read(readBuffer);
			}
			StringBuilder receivedMsg = new StringBuilder("/-- ");
			receivedMsg.append(new String(readBuffer).trim()).append(" --/\n");
			readTa.append(receivedMsg.toString());
			reciveCount++;
			statusLb.setText("  發送: " + sendCount
					+ "                                      接收: "
					+ reciveCount);
		} catch (IOException e) {
			showErrMesgbox(e.getMessage());
		}
		return "";
	}

	private static String byte2hex(byte[] buffer) {
		String h = "";

		for (int i = 0; i < buffer.length; i++) {
			String temp = Integer.toHexString(buffer[i] & 0xFF);
			if (temp.length() == 1) {
				temp = "0" + temp;
			}
			h = h + " " + temp;
		}

		return h;

	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	public static String Float16(String msg) {
		Float value = Float.intBitsToFloat(Integer.valueOf(msg.trim(), 16));
		Float f = 0.15490197f;
		return value + "";
	}
}

CRC16算法:

package com.jetf.mm;


public class CRC16 {
	static final String HEXES = "0123456789ABCDEF";
	byte uchCRCHi = (byte) 0xFF;
	byte uchCRCLo = (byte) 0xFF;
	private static byte[] auchCRCHi = { 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
			(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
			(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
			(byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
			(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0,
			(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
			(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
			(byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
			(byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
			(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
			(byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
			(byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
			(byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,

			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
			(byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
			(byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
			(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
			(byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
			(byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
			(byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
			(byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
			(byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
			(byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
			(byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
			(byte) 0xC1, (byte) 0x81, (byte) 0x40 };
	private static byte[] auchCRCLo = { (byte) 0x00, (byte) 0xC0, (byte) 0xC1,
			(byte) 0x01, (byte) 0xC3, (byte) 0x03, (byte) 0x02, (byte) 0xC2,
			(byte) 0xC6, (byte) 0x06, (byte) 0x07, (byte) 0xC7, (byte) 0x05,
			(byte) 0xC5, (byte) 0xC4, (byte) 0x04, (byte) 0xCC, (byte) 0x0C,
			(byte) 0x0D, (byte) 0xCD, (byte) 0x0F, (byte) 0xCF, (byte) 0xCE,
			(byte) 0x0E, (byte) 0x0A, (byte) 0xCA, (byte) 0xCB, (byte) 0x0B,
			(byte) 0xC9, (byte) 0x09, (byte) 0x08, (byte) 0xC8, (byte) 0xD8,
			(byte) 0x18, (byte) 0x19, (byte) 0xD9, (byte) 0x1B, (byte) 0xDB,
			(byte) 0xDA, (byte) 0x1A, (byte) 0x1E, (byte) 0xDE, (byte) 0xDF,
			(byte) 0x1F, (byte) 0xDD, (byte) 0x1D, (byte) 0x1C, (byte) 0xDC,
			(byte) 0x14, (byte) 0xD4, (byte) 0xD5, (byte) 0x15, (byte) 0xD7,
			(byte) 0x17, (byte) 0x16, (byte) 0xD6, (byte) 0xD2, (byte) 0x12,
			(byte) 0x13, (byte) 0xD3, (byte) 0x11, (byte) 0xD1, (byte) 0xD0,
			(byte) 0x10, (byte) 0xF0, (byte) 0x30, (byte) 0x31, (byte) 0xF1,
			(byte) 0x33, (byte) 0xF3, (byte) 0xF2, (byte) 0x32, (byte) 0x36,
			(byte) 0xF6, (byte) 0xF7, (byte) 0x37, (byte) 0xF5, (byte) 0x35,
			(byte) 0x34, (byte) 0xF4, (byte) 0x3C, (byte) 0xFC, (byte) 0xFD,
			(byte) 0x3D, (byte) 0xFF, (byte) 0x3F, (byte) 0x3E, (byte) 0xFE,
			(byte) 0xFA, (byte) 0x3A, (byte) 0x3B, (byte) 0xFB, (byte) 0x39,
			(byte) 0xF9, (byte) 0xF8, (byte) 0x38, (byte) 0x28, (byte) 0xE8,
			(byte) 0xE9, (byte) 0x29, (byte) 0xEB, (byte) 0x2B, (byte) 0x2A,
			(byte) 0xEA, (byte) 0xEE, (byte) 0x2E, (byte) 0x2F, (byte) 0xEF,
			(byte) 0x2D, (byte) 0xED, (byte) 0xEC, (byte) 0x2C, (byte) 0xE4,
			(byte) 0x24, (byte) 0x25, (byte) 0xE5, (byte) 0x27, (byte) 0xE7,
			(byte) 0xE6, (byte) 0x26, (byte) 0x22, (byte) 0xE2, (byte) 0xE3,
			(byte) 0x23, (byte) 0xE1, (byte) 0x21, (byte) 0x20, (byte) 0xE0,
			(byte) 0xA0, (byte) 0x60, (byte) 0x61, (byte) 0xA1, (byte) 0x63,
			(byte) 0xA3, (byte) 0xA2, (byte) 0x62, (byte) 0x66, (byte) 0xA6,
			(byte) 0xA7, (byte) 0x67, (byte) 0xA5, (byte) 0x65, (byte) 0x64,
			(byte) 0xA4, (byte) 0x6C, (byte) 0xAC, (byte) 0xAD, (byte) 0x6D,

			(byte) 0xAF, (byte) 0x6F, (byte) 0x6E, (byte) 0xAE, (byte) 0xAA,
			(byte) 0x6A, (byte) 0x6B, (byte) 0xAB, (byte) 0x69, (byte) 0xA9,
			(byte) 0xA8, (byte) 0x68, (byte) 0x78, (byte) 0xB8, (byte) 0xB9,
			(byte) 0x79, (byte) 0xBB, (byte) 0x7B, (byte) 0x7A, (byte) 0xBA,
			(byte) 0xBE, (byte) 0x7E, (byte) 0x7F, (byte) 0xBF, (byte) 0x7D,
			(byte) 0xBD, (byte) 0xBC, (byte) 0x7C, (byte) 0xB4, (byte) 0x74,
			(byte) 0x75, (byte) 0xB5, (byte) 0x77, (byte) 0xB7, (byte) 0xB6,
			(byte) 0x76, (byte) 0x72, (byte) 0xB2, (byte) 0xB3, (byte) 0x73,
			(byte) 0xB1, (byte) 0x71, (byte) 0x70, (byte) 0xB0, (byte) 0x50,
			(byte) 0x90, (byte) 0x91, (byte) 0x51, (byte) 0x93, (byte) 0x53,
			(byte) 0x52, (byte) 0x92, (byte) 0x96, (byte) 0x56, (byte) 0x57,
			(byte) 0x97, (byte) 0x55, (byte) 0x95, (byte) 0x94, (byte) 0x54,
			(byte) 0x9C, (byte) 0x5C, (byte) 0x5D, (byte) 0x9D, (byte) 0x5F,
			(byte) 0x9F, (byte) 0x9E, (byte) 0x5E, (byte) 0x5A, (byte) 0x9A,
			(byte) 0x9B, (byte) 0x5B, (byte) 0x99, (byte) 0x59, (byte) 0x58,
			(byte) 0x98, (byte) 0x88, (byte) 0x48, (byte) 0x49, (byte) 0x89,
			(byte) 0x4B, (byte) 0x8B, (byte) 0x8A, (byte) 0x4A, (byte) 0x4E,
			(byte) 0x8E, (byte) 0x8F, (byte) 0x4F, (byte) 0x8D, (byte) 0x4D,
			(byte) 0x4C, (byte) 0x8C, (byte) 0x44, (byte) 0x84, (byte) 0x85,
			(byte) 0x45, (byte) 0x87, (byte) 0x47, (byte) 0x46, (byte) 0x86,
			(byte) 0x82, (byte) 0x42, (byte) 0x43, (byte) 0x83, (byte) 0x41,
			(byte) 0x81, (byte) 0x80, (byte) 0x40 };
	public int value;

	public CRC16() {
		value = 0;
	}

	public void update(byte[] puchMsg, int usDataLen) {
		int uIndex; // int i = 0;
		for (int i = 0; i < usDataLen; i++) {
			uIndex = (uchCRCHi ^ puchMsg[i]) & 0xff;
			uchCRCHi = (byte) (uchCRCLo ^ auchCRCHi[uIndex]);
			uchCRCLo = auchCRCLo[uIndex];
		}
		value = ((((int) uchCRCHi) << 8 | (((int) uchCRCLo) & 0xff))) & 0xffff;
		return;
	}

	public void reset() {
		value = 0;
		uchCRCHi = (byte) 0xff;
		uchCRCLo = (byte) 0xff;
	}

	public int getValue() {
		return value;

	}

	private static byte uniteBytes(byte src0, byte src1) {
		byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
				.byteValue();
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
				.byteValue();
		byte ret = (byte) (_b0 ^ _b1);
		return ret;
	}

	private static byte[] HexString2Buf(String src) {
		int len = src.length();
		byte[] ret = new byte[len / 2 + 2];
		byte[] tmp = src.getBytes();
		for (int i = 0; i < len; i += 2) {
			ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
		}
		return ret;
	}

	public static byte[] getSendBuf(String toSend) {
		byte[] bb = HexString2Buf(toSend);
		CRC16 crc16 = new CRC16();
		crc16.update(bb, bb.length - 2);
		int ri = crc16.getValue();
		bb[bb.length - 1] = (byte) (0xff & ri);
		bb[bb.length - 2] = (byte) ((0xff00 & ri) >> 8);
		return bb;
	}

	public static boolean checkBuf(byte[] bb) {
		CRC16 crc16 = new CRC16();
		crc16.update(bb, bb.length - 2);
		int ri = crc16.getValue();
		if (bb[bb.length - 1] == (byte) (ri & 0xff)
				&& bb[bb.length - 2] == (byte) ((0xff00 & ri) >> 8))
			return true;
		return false;
	}

	public static String getBufHexStr(byte[] raw) {
		if (raw == null) {
			return null;
		}
		final StringBuilder hex = new StringBuilder(2 * raw.length);
		for (final byte b : raw) {
			hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(
					HEXES.charAt((b & 0x0F)));
		}
		return hex.toString().toLowerCase();
	}

	/****
	 * * 得到CRC驗證 } } } } } }
	 * 
	 * @param tt
	 *            * @return
	 */
	public static String getCrc(String tem) { // String tem=""; // for(int
												// i=0;i> 8);
		return bb;
	}

	public static void main(String[] args) { // TODO Auto-generated method stub
												// //0103040a3d3fb739a1----sendB
												// //010304b8523ffeef32----sendB
		String ms = "";
		byte[] sbuf = CRC16.getSendBuf("010400000015");
		System.out.println(CRC16.getBufHexStr(sbuf));
	}

}

Float16算法:

package com.jetf.mm;

public class Float16 {
	@SuppressWarnings("unused")
	public static void main(String[] args) {
		String s = "057e";
		Float value = Float.intBitsToFloat(Integer.valueOf(s.trim(), 16));
		// Double
		System.out.println(Integer.valueOf(s.trim(), 16));
		Float f = 225.92f;
		System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
	}
}



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved