JAVA串口通讯程序

淡淡的烟草味﹌ 2022-08-21 06:45 264阅读 0赞
  1. package com.jetf.serialport;
  2. import gnu.io.CommPortIdentifier;
  3. import gnu.io.NoSuchPortException;
  4. import gnu.io.PortInUseException;
  5. import gnu.io.SerialPort;
  6. import gnu.io.SerialPortEvent;
  7. import gnu.io.SerialPortEventListener;
  8. import gnu.io.UnsupportedCommOperationException;
  9. import java.awt.BorderLayout;
  10. import java.awt.Button;
  11. import java.awt.Color;
  12. import java.awt.Font;
  13. import java.awt.GridLayout;
  14. import java.awt.Image;
  15. import java.awt.TextArea;
  16. import java.awt.TextField;
  17. import java.awt.event.ActionEvent;
  18. import java.awt.event.ActionListener;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.OutputStream;
  22. import java.util.ArrayList;
  23. import java.util.Enumeration;
  24. import java.util.List;
  25. import java.util.TooManyListenersException;
  26. import javax.imageio.ImageIO;
  27. import javax.swing.JComboBox;
  28. import javax.swing.JFrame;
  29. import javax.swing.JLabel;
  30. import javax.swing.JOptionPane;
  31. import javax.swing.JPanel;
  32. import javax.swing.SwingConstants;
  33. import javax.swing.border.EmptyBorder;
  34. import com.jetf.mm.CRC16;
  35. import com.jfinal.kit.StrKit;
  36. public class JavaRs232 extends JFrame implements ActionListener,
  37. SerialPortEventListener {
  38. /**
  39. * JDK Serial Version UID
  40. */
  41. private static final long serialVersionUID = -7270865686330790103L;
  42. protected int WIN_WIDTH = 500;
  43. protected int WIN_HEIGHT = 420;
  44. private JComboBox portCombox, rateCombox, dataCombox, stopCombox,
  45. parityCombox, parityCombox1;
  46. private Button openPortBtn, closePortBtn, sendMsgBtn, sendMsgBtn1;
  47. private TextField sendTf;
  48. private TextField sendD1;
  49. private TextField sendD2;
  50. private TextField sendD3;
  51. private TextField sendTf1;
  52. private TextArea readTa;
  53. private JLabel statusLb;
  54. private String portname, rate, data, stop, parity;
  55. protected CommPortIdentifier portId;
  56. protected Enumeration<?> ports;
  57. protected List<String> portList;
  58. protected SerialPort serialPort;
  59. protected OutputStream outputStream = null;
  60. protected InputStream inputStream = null;
  61. protected String mesg;
  62. protected String mesg1;
  63. protected String mesg_info_D1;
  64. protected String mesg_info_D2;
  65. protected String mesg_info_D3;
  66. protected String[] mesgs;
  67. protected int sendCount, reciveCount;
  68. /**
  69. * 默认构造函数
  70. */
  71. public JavaRs232() {
  72. super("Java串口通信测试程序");
  73. setSize(WIN_WIDTH, WIN_HEIGHT);
  74. setLocationRelativeTo(null);
  75. Image icon = null;
  76. try {
  77. icon = ImageIO.read(JavaRs232.class
  78. .getResourceAsStream("rs232.png"));
  79. } catch (IOException e) {
  80. showErrMesgbox(e.getMessage());
  81. }
  82. setIconImage(icon);
  83. setResizable(false);
  84. scanPorts();
  85. initComponents();
  86. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  87. setVisible(true);
  88. }
  89. /**
  90. * 初始化各UI组件
  91. *
  92. * @since 2012-3-22 下午11:56:39
  93. */
  94. public void initComponents() {
  95. // 共用常量
  96. Font lbFont = new Font("微软雅黑", Font.TRUETYPE_FONT, 14);
  97. // 创建左边面板
  98. JPanel northPane = new JPanel();
  99. northPane.setLayout(new GridLayout(1, 1));
  100. // 设置左边面板各组件
  101. JPanel leftPane = new JPanel();
  102. leftPane.setOpaque(false);
  103. leftPane.setLayout(new GridLayout(3, 2));
  104. JLabel portnameLb = new JLabel("串口号:");
  105. portnameLb.setFont(lbFont);
  106. portnameLb.setHorizontalAlignment(SwingConstants.RIGHT);
  107. portCombox = new JComboBox((String[]) portList.toArray(new String[0]));
  108. portCombox.addActionListener(this);
  109. JLabel databitsLb = new JLabel("数据位:");
  110. databitsLb.setFont(lbFont);
  111. databitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
  112. // 设置中间面板各组件
  113. dataCombox = new JComboBox(new Integer[] { 5, 6, 7, 8 });
  114. dataCombox.setSelectedIndex(3);
  115. dataCombox.addActionListener(this);
  116. JLabel parityLb = new JLabel("校验位:");
  117. parityLb.setFont(lbFont);
  118. parityLb.setHorizontalAlignment(SwingConstants.RIGHT);
  119. parityCombox = new JComboBox(new String[] { "NONE", "ODD", "EVEN",
  120. "MARK", "SPACE" });
  121. parityCombox.addActionListener(this);
  122. JLabel parityLb1 = new JLabel("01写:");
  123. parityLb1.setFont(lbFont);
  124. parityLb1.setLayout(new GridLayout(1, 1));
  125. parityLb1.setHorizontalAlignment(SwingConstants.RIGHT);
  126. // 设置中间面板各组件
  127. sendD1 = new TextField(5);
  128. JLabel parityLb2 = new JLabel("03读:");
  129. parityLb2.setFont(lbFont);
  130. parityLb2.setLayout(new GridLayout(1, 1));
  131. parityLb2.setHorizontalAlignment(SwingConstants.RIGHT);
  132. // 设置中间面板各组件
  133. sendD3 = new TextField(5);
  134. JLabel parityLb3 = new JLabel("0002:");
  135. parityLb3.setFont(lbFont);
  136. parityLb3.setLayout(new GridLayout(1, 1));
  137. parityLb3.setHorizontalAlignment(SwingConstants.RIGHT);
  138. // 设置中间面板各组件
  139. sendD2 = new TextField(5);
  140. // 添加组件至面板
  141. leftPane.add(portnameLb);
  142. leftPane.add(portCombox);
  143. leftPane.add(databitsLb);
  144. leftPane.add(dataCombox);
  145. leftPane.add(parityLb);
  146. leftPane.add(parityCombox);
  147. leftPane.add(parityLb1);
  148. leftPane.add(sendD1);
  149. leftPane.add(parityLb2);
  150. leftPane.add(sendD3);
  151. leftPane.add(parityLb3);
  152. leftPane.add(sendD2);
  153. // 创建右边面板
  154. JPanel rightPane = new JPanel();
  155. rightPane.setLayout(new GridLayout(3, 2));
  156. // 设置右边面板各组件
  157. JLabel baudrateLb = new JLabel("波特率:");
  158. baudrateLb.setFont(lbFont);
  159. baudrateLb.setHorizontalAlignment(SwingConstants.RIGHT);
  160. rateCombox = new JComboBox(new Integer[] { 2400, 4800, 9600, 14400,
  161. 19200, 38400, 56000 });
  162. rateCombox.setSelectedIndex(2);
  163. rateCombox.addActionListener(this);
  164. JLabel stopbitsLb = new JLabel("停止位:");
  165. stopbitsLb.setFont(lbFont);
  166. stopbitsLb.setHorizontalAlignment(SwingConstants.RIGHT);
  167. stopCombox = new JComboBox(new String[] { "1", "2", "1.5" });
  168. stopCombox.addActionListener(this);
  169. // JLabel stopbitsLb4 = new JLabel("DDDD:");
  170. // stopbitsLb4.setFont(lbFont);
  171. // stopbitsLb4.setHorizontalAlignment(SwingConstants.RIGHT);
  172. // sendTf = new TextField(5);
  173. openPortBtn = new Button("start");
  174. openPortBtn.addActionListener(this);
  175. closePortBtn = new Button("coles");
  176. closePortBtn.addActionListener(this);
  177. // 添加组件至面板
  178. rightPane.add(baudrateLb);
  179. rightPane.add(rateCombox);
  180. rightPane.add(stopbitsLb);
  181. rightPane.add(stopCombox);
  182. // rightPane.add(stopbitsLb4);
  183. // rightPane.add(sendTf);
  184. rightPane.add(openPortBtn);
  185. rightPane.add(closePortBtn);
  186. // 将左右面板组合添加到北边的面板
  187. northPane.add(leftPane);
  188. northPane.add(rightPane);
  189. JLabel stopbitsLbdd = new JLabel("地址端口:");
  190. stopbitsLbdd.setFont(lbFont);
  191. stopbitsLbdd.setHorizontalAlignment(SwingConstants.RIGHT);
  192. // 创建中间面板
  193. JPanel centerPane = new JPanel();
  194. // 设置中间面板各组件
  195. sendTf = new TextField(30);
  196. readTa = new TextArea(8, 50);
  197. readTa.setEditable(false);
  198. readTa.setBackground(new Color(225, 242, 250));
  199. centerPane.add(sendTf);
  200. sendMsgBtn = new Button("send ");
  201. sendMsgBtn.addActionListener(this);
  202. JLabel stopbitsLbdd1 = new JLabel("地址:");
  203. stopbitsLbdd1.setFont(lbFont);
  204. stopbitsLbdd1.setHorizontalAlignment(SwingConstants.RIGHT);
  205. sendTf1 = new TextField(20);
  206. sendMsgBtn1 = new Button("send2 ");
  207. sendMsgBtn1.addActionListener(this);
  208. JLabel parityLb4 = new JLabel("命令:");
  209. parityLb4.setFont(lbFont);
  210. parityLb4.setHorizontalAlignment(SwingConstants.RIGHT);
  211. parityCombox1 = new JComboBox(new String[] { "上传开关量", "上传SOE整定值",
  212. "标志信息模拟量" });
  213. parityCombox1.addActionListener(this);
  214. // 添加组件至面板
  215. centerPane.add(stopbitsLbdd);
  216. centerPane.add(sendTf);
  217. centerPane.add(sendMsgBtn);
  218. centerPane.add(readTa);
  219. centerPane.add(parityLb4);
  220. centerPane.add(parityCombox1);
  221. centerPane.add(stopbitsLbdd1);
  222. centerPane.add(sendTf1);
  223. centerPane.add(sendMsgBtn1);
  224. // 设置南边组件
  225. statusLb = new JLabel();
  226. statusLb.setText(initStatus());
  227. statusLb.setOpaque(true);
  228. // 获取主窗体的容器,并将以上三面板以北、中、南的布局整合
  229. JPanel contentPane = (JPanel) getContentPane();
  230. contentPane.setLayout(new BorderLayout());
  231. contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
  232. contentPane.setOpaque(false);
  233. contentPane.add(northPane, BorderLayout.NORTH);
  234. contentPane.add(centerPane, BorderLayout.CENTER);
  235. contentPane.add(statusLb, BorderLayout.SOUTH);
  236. }
  237. /**
  238. * 初始化状态标签显示文本
  239. *
  240. * @return String
  241. * @since 2012-3-23 上午12:01:53
  242. */
  243. public String initStatus() {
  244. portname = portCombox.getSelectedItem().toString();
  245. rate = rateCombox.getSelectedItem().toString();
  246. data = dataCombox.getSelectedItem().toString();
  247. stop = stopCombox.getSelectedItem().toString();
  248. parity = parityCombox.getSelectedItem().toString();
  249. StringBuffer str = new StringBuffer("当前串口号:");
  250. str.append(portname).append(" 波特率:");
  251. str.append(rate).append(" 数据位:");
  252. str.append(data).append(" 停止位:");
  253. str.append(stop).append(" 校验位:");
  254. str.append(parity);
  255. return str.toString();
  256. }
  257. /**
  258. * 扫描本机的所有COM端口
  259. *
  260. * @since 2012-3-23 上午12:02:42
  261. */
  262. public void scanPorts() {
  263. portList = new ArrayList<String>();
  264. Enumeration<?> en = CommPortIdentifier.getPortIdentifiers();
  265. CommPortIdentifier portId;
  266. while (en.hasMoreElements()) {
  267. portId = (CommPortIdentifier) en.nextElement();
  268. if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
  269. String name = portId.getName();
  270. if (!portList.contains(name)) {
  271. portList.add(name);
  272. }
  273. }
  274. }
  275. if (null == portList || portList.isEmpty()) {
  276. showErrMesgbox("未找到可用的串行端口号,程序无法启动!");
  277. System.exit(0);
  278. }
  279. }
  280. /**
  281. * 打开串行端口
  282. *
  283. * @since 2012-3-23 上午12:03:07
  284. */
  285. public void openSerialPort() {
  286. // 获取要打开的端口
  287. try {
  288. portId = CommPortIdentifier.getPortIdentifier(portname);
  289. } catch (NoSuchPortException e) {
  290. showErrMesgbox("抱歉,没有找到" + portname + "串行端口号!");
  291. setComponentsEnabled(true);
  292. return;
  293. }
  294. // 打开端口
  295. try {
  296. serialPort = (SerialPort) portId.open("JavaRs232", 3927);
  297. statusLb.setText(portname + "串口已经打开!");
  298. } catch (PortInUseException e) {
  299. showErrMesgbox(portname + "端口已被占用,请检查!");
  300. setComponentsEnabled(true);
  301. return;
  302. }
  303. // 打开端口的IO流管道
  304. try {
  305. outputStream = serialPort.getOutputStream();
  306. inputStream = serialPort.getInputStream();
  307. } catch (IOException e) {
  308. showErrMesgbox(e.getMessage());
  309. }
  310. // 给端口添加监听器
  311. try {
  312. serialPort.addEventListener(this);
  313. } catch (TooManyListenersException e) {
  314. showErrMesgbox(e.getMessage());
  315. }
  316. serialPort.notifyOnDataAvailable(true);
  317. // 设置端口参数
  318. try {
  319. int rate = Integer.parseInt(this.rate);
  320. int data = Integer.parseInt(this.data);
  321. int stop = stopCombox.getSelectedIndex() + 1;
  322. int parity = parityCombox.getSelectedIndex();
  323. System.out.println("rate:" + rate);
  324. System.out.println("data:" + data);
  325. System.out.println("stop:" + stop);
  326. System.out.println("parity:" + parity);
  327. serialPort.setSerialPortParams(rate, data, stop, parity);
  328. } catch (UnsupportedCommOperationException e) {
  329. showErrMesgbox(e.getMessage());
  330. }
  331. }
  332. /**
  333. * 给串行端口发送数据
  334. *
  335. * @since 2012-3-23 上午12:05:00
  336. */
  337. public void sendDataToSeriaPort(String mesg_info) {
  338. byte[] sbuf = null;
  339. String s_info = "";
  340. sbuf = CRC16.getSendBuf(mesg_info);
  341. s_info = CRC16.getBufHexStr(sbuf);
  342. try {
  343. sendCount++;
  344. outputStream.write(hexStringToBytes(s_info));
  345. outputStream.flush();
  346. StringBuilder receivedMsg = new StringBuilder();
  347. receivedMsg.append(receivedMsg)
  348. .append("发送数据: " + mesg_info + " \n");
  349. readTa.append(receivedMsg.toString());
  350. } catch (IOException e) {
  351. showErrMesgbox(e.getMessage());
  352. System.out.println(mesg_info);
  353. }
  354. statusLb.setText(" 发送: " + sendCount
  355. + " 接收: " + reciveCount);
  356. }
  357. /**
  358. * 关闭串行端口
  359. *
  360. * @since 2012-3-23 上午12:05:28
  361. */
  362. public void closeSerialPort() {
  363. try {
  364. if (outputStream != null)
  365. outputStream.close();
  366. if (serialPort != null)
  367. serialPort.close();
  368. serialPort = null;
  369. statusLb.setText(portname + "串口已经关闭!");
  370. sendCount = 0;
  371. reciveCount = 0;
  372. sendTf.setText("");
  373. sendTf1.setText("");
  374. sendD1.setText("");
  375. sendD2.setText("");
  376. sendD3.setText("");
  377. readTa.setText("");
  378. } catch (Exception e) {
  379. showErrMesgbox(e.getMessage());
  380. }
  381. }
  382. /**
  383. * 显示错误或警告信息
  384. *
  385. * @param msg
  386. * 信息
  387. * @since 2012-3-23 上午12:05:47
  388. */
  389. public void showErrMesgbox(String msg) {
  390. JOptionPane.showMessageDialog(this, msg);
  391. }
  392. /**
  393. * 各组件行为事件监听
  394. */
  395. public void actionPerformed(ActionEvent e) {
  396. String msg_info = "";
  397. if (e.getSource() == portCombox || e.getSource() == rateCombox
  398. || e.getSource() == dataCombox || e.getSource() == stopCombox
  399. || e.getSource() == parityCombox) {
  400. statusLb.setText(initStatus());
  401. }
  402. if (e.getSource() == openPortBtn) {
  403. setComponentsEnabled(false);
  404. System.err.println("打开");
  405. openSerialPort();
  406. }
  407. if (e.getSource() == closePortBtn) {
  408. if (serialPort != null) {
  409. closeSerialPort();
  410. }
  411. setComponentsEnabled(true);
  412. }
  413. if (e.getSource() == sendMsgBtn) {
  414. if (serialPort == null) {
  415. showErrMesgbox("请先打开串行端口!");
  416. return;
  417. }
  418. mesg = sendTf.getText();
  419. mesg_info_D1 = sendD1.getText();
  420. mesg_info_D2 = sendD2.getText();
  421. mesg_info_D3 = sendD3.getText();
  422. String info_length = mesg + "" + mesg_info_D1 + "" + mesg_info_D2
  423. + "" + mesg_info_D3;
  424. if (StrKit.isBlank(mesg) || StrKit.isBlank(mesg_info_D1)
  425. || StrKit.isBlank(mesg_info_D2)
  426. || StrKit.isBlank(mesg_info_D3)) {
  427. showErrMesgbox("4个文本框必须填写完整!");
  428. return;
  429. } else {
  430. boolean result = info_length.matches("[0-9]+");
  431. if (result) {
  432. msg_info = stringToHex16(mesg_info_D1, mesg_info_D2,
  433. mesg_info_D3, mesg);
  434. } else {
  435. showErrMesgbox("输入内容中存在非法字符,内容只支持数字!");
  436. return;
  437. }
  438. if (msg_info.length() < 12) {
  439. showErrMesgbox("输入内容长度不够默认4个文本框总长度12位!");
  440. return;
  441. } else if (msg_info.length() > 12) {
  442. showErrMesgbox("输入内容长度超限默认4个文本框总长度12位!");
  443. return;
  444. }
  445. }
  446. sendDataToSeriaPort(msg_info);
  447. }
  448. if (e.getSource() == sendMsgBtn1) {
  449. String sc_info = "";
  450. if (serialPort == null) {
  451. showErrMesgbox("请先打开串行端口!");
  452. return;
  453. }
  454. switch (parityCombox1.getSelectedIndex()) {
  455. case 0:
  456. sc_info = "0100000040";
  457. break;
  458. case 1:
  459. sc_info = "030000000B";
  460. break;
  461. case 2:
  462. sc_info = "0400000015";
  463. break;
  464. default:
  465. break;
  466. }
  467. mesg1 = sendTf1.getText();
  468. if (StrKit.isBlank(mesg1)) {
  469. showErrMesgbox("请填写地址信息!");
  470. return;
  471. } else {
  472. boolean result = mesg1.matches("[0-9]+");
  473. if (result) {
  474. if (Integer.parseInt(mesg1) > 255) {
  475. showErrMesgbox("地址输入有误,1-255之间!");
  476. return;
  477. } else {
  478. msg_info = stringToHex16(mesg1);
  479. }
  480. } else {
  481. showErrMesgbox("输入内容中存在非法字符,内容只支持数字!");
  482. return;
  483. }
  484. }
  485. sendDataToSeriaPort(msg_info + "" + sc_info);
  486. }
  487. }
  488. private String stringToHex16(String mesg12) {
  489. String msg = "";
  490. if (Integer.toString(Integer.parseInt(mesg12), 16).length() == 1) {
  491. mesg12 = "0" + Integer.toString(Integer.parseInt(mesg12), 16);
  492. } else {
  493. mesg12 = Integer.toString(Integer.parseInt(mesg12), 16);
  494. }
  495. msg = mesg12;
  496. return msg;
  497. }
  498. private String stringToHex16(String mesg_info_D1, String mesg_info_D2,
  499. String mesg_info_D3, String mesg) {
  500. String msg = "";
  501. if (Integer.toString(Integer.parseInt(mesg_info_D1), 16).length() == 1) {
  502. mesg_info_D1 = "0"
  503. + Integer.toString(Integer.parseInt(mesg_info_D1), 16);
  504. } else {
  505. mesg_info_D1 = Integer.toString(Integer.parseInt(mesg_info_D1), 16);
  506. }
  507. if (Integer.toString(Integer.parseInt(mesg_info_D3), 16).length() == 1) {
  508. mesg_info_D3 = "0"
  509. + Integer.toString(Integer.parseInt(mesg_info_D3), 16);
  510. } else {
  511. mesg_info_D3 = Integer.toString(Integer.parseInt(mesg_info_D3), 16);
  512. }
  513. if (Integer.toString(Integer.parseInt(mesg_info_D2), 16).length() == 1) {
  514. mesg_info_D2 = "000"
  515. + Integer.toString(Integer.parseInt(mesg_info_D2), 16);
  516. } else if (Integer.toString(Integer.parseInt(mesg_info_D2), 16)
  517. .length() == 2) {
  518. mesg_info_D2 = "00"
  519. + Integer.toString(Integer.parseInt(mesg_info_D2), 16);
  520. } else if (Integer.toString(Integer.parseInt(mesg_info_D2), 16)
  521. .length() == 3) {
  522. mesg_info_D2 = "0"
  523. + Integer.toString(Integer.parseInt(mesg_info_D2), 16);
  524. } else {
  525. mesg_info_D2 = Integer.toString(Integer.parseInt(mesg_info_D2), 16);
  526. }
  527. if (Integer.toString(Integer.parseInt(mesg), 16).length() == 1) {
  528. mesg = "000" + Integer.toString(Integer.parseInt(mesg), 16);
  529. } else if (Integer.toString(Integer.parseInt(mesg), 16).length() == 2) {
  530. mesg = "00" + Integer.toString(Integer.parseInt(mesg), 16);
  531. } else if (Integer.toString(Integer.parseInt(mesg), 16).length() == 3) {
  532. mesg = "0" + Integer.toString(Integer.parseInt(mesg), 16);
  533. } else {
  534. mesg = Integer.toString(Integer.parseInt(mesg), 16);
  535. }
  536. msg = mesg_info_D1 + "" + mesg_info_D3 + "" + mesg + "" + mesg_info_D2;
  537. return msg;
  538. }
  539. /**
  540. * 端口事件监听
  541. */
  542. public void serialEvent(SerialPortEvent event) {
  543. switch (event.getEventType()) {
  544. case SerialPortEvent.BI:
  545. case SerialPortEvent.OE:
  546. case SerialPortEvent.FE:
  547. case SerialPortEvent.PE:
  548. case SerialPortEvent.CD:
  549. case SerialPortEvent.CTS:
  550. case SerialPortEvent.DSR:
  551. case SerialPortEvent.RI:
  552. case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
  553. break;
  554. case SerialPortEvent.DATA_AVAILABLE:
  555. byte[] readBuffer = null;
  556. try {
  557. Thread.sleep(30l);
  558. } catch (InterruptedException e2) {
  559. // TODO Auto-generated catch block
  560. e2.printStackTrace();
  561. }
  562. try {
  563. readBuffer = new byte[inputStream.available()];
  564. } catch (IOException e1) {
  565. // TODO Auto-generated catch block
  566. e1.printStackTrace();
  567. }
  568. try {
  569. while (inputStream.available() > 0) {
  570. inputStream.read(readBuffer);
  571. }
  572. System.out.println(byte2hex(readBuffer));
  573. String msg = byte2hex(readBuffer).trim();
  574. msg = msg.replaceAll(" ", "");
  575. String v_info = Float16(msg.substring(10, 14) + ""
  576. + msg.substring(6, 10));
  577. StringBuilder receivedMsg = new StringBuilder();
  578. receivedMsg.append(receivedMsg).append(
  579. "回复数据: " + v_info + "V\n");
  580. readTa.append(receivedMsg.toString());
  581. reciveCount++;
  582. statusLb.setText(" 发送: " + sendCount
  583. + " 接收: "
  584. + reciveCount);
  585. } catch (IOException e) {
  586. }
  587. }
  588. }
  589. /**
  590. * 设置各组件的开关状态
  591. *
  592. * @param enabled
  593. * 状态
  594. * @since 2012-3-23 上午12:06:24
  595. */
  596. public void setComponentsEnabled(boolean enabled) {
  597. openPortBtn.setEnabled(enabled);
  598. openPortBtn.setEnabled(enabled);
  599. portCombox.setEnabled(enabled);
  600. rateCombox.setEnabled(enabled);
  601. dataCombox.setEnabled(enabled);
  602. stopCombox.setEnabled(enabled);
  603. parityCombox.setEnabled(enabled);
  604. }
  605. /**
  606. * 运行主函数
  607. *
  608. * @param args
  609. * @since 2012-3-23 上午12:06:45
  610. */
  611. public static void main(String[] args) {
  612. new JavaRs232();
  613. }
  614. public String readPort() {
  615. byte[] readBuffer = new byte[50];
  616. try {
  617. while (inputStream.available() > 0) {
  618. inputStream.read(readBuffer);
  619. }
  620. StringBuilder receivedMsg = new StringBuilder("/-- ");
  621. receivedMsg.append(new String(readBuffer).trim()).append(" --/\n");
  622. readTa.append(receivedMsg.toString());
  623. reciveCount++;
  624. statusLb.setText(" 发送: " + sendCount
  625. + " 接收: "
  626. + reciveCount);
  627. } catch (IOException e) {
  628. showErrMesgbox(e.getMessage());
  629. }
  630. return "";
  631. }
  632. private static String byte2hex(byte[] buffer) {
  633. String h = "";
  634. for (int i = 0; i < buffer.length; i++) {
  635. String temp = Integer.toHexString(buffer[i] & 0xFF);
  636. if (temp.length() == 1) {
  637. temp = "0" + temp;
  638. }
  639. h = h + " " + temp;
  640. }
  641. return h;
  642. }
  643. public static byte[] hexStringToBytes(String hexString) {
  644. if (hexString == null || hexString.equals("")) {
  645. return null;
  646. }
  647. hexString = hexString.toUpperCase();
  648. int length = hexString.length() / 2;
  649. char[] hexChars = hexString.toCharArray();
  650. byte[] d = new byte[length];
  651. for (int i = 0; i < length; i++) {
  652. int pos = i * 2;
  653. d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
  654. }
  655. return d;
  656. }
  657. private static byte charToByte(char c) {
  658. return (byte) "0123456789ABCDEF".indexOf(c);
  659. }
  660. public static String Float16(String msg) {
  661. Float value = Float.intBitsToFloat(Integer.valueOf(msg.trim(), 16));
  662. Float f = 0.15490197f;
  663. return value + "";
  664. }
  665. }

CRC16算法:

  1. package com.jetf.mm;
  2. public class CRC16 {
  3. static final String HEXES = "0123456789ABCDEF";
  4. byte uchCRCHi = (byte) 0xFF;
  5. byte uchCRCLo = (byte) 0xFF;
  6. private static byte[] auchCRCHi = { 0x00, (byte) 0xC1, (byte) 0x81,
  7. (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  8. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
  9. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
  10. (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  11. (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
  12. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
  13. (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
  14. (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  15. (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  16. (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
  17. (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0,
  18. (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  19. (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  20. (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
  21. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
  22. (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  23. (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  24. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
  25. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
  26. (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
  27. (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  28. (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
  29. (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
  30. (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  31. (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  32. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
  33. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
  34. (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
  35. (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
  36. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
  37. (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
  38. (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  39. (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  40. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
  41. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
  42. (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  43. (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
  44. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
  45. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
  46. (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
  47. (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
  48. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
  49. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
  50. (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
  51. (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  52. (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
  53. (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
  54. (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
  55. (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
  56. (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
  57. (byte) 0xC1, (byte) 0x81, (byte) 0x40 };
  58. private static byte[] auchCRCLo = { (byte) 0x00, (byte) 0xC0, (byte) 0xC1,
  59. (byte) 0x01, (byte) 0xC3, (byte) 0x03, (byte) 0x02, (byte) 0xC2,
  60. (byte) 0xC6, (byte) 0x06, (byte) 0x07, (byte) 0xC7, (byte) 0x05,
  61. (byte) 0xC5, (byte) 0xC4, (byte) 0x04, (byte) 0xCC, (byte) 0x0C,
  62. (byte) 0x0D, (byte) 0xCD, (byte) 0x0F, (byte) 0xCF, (byte) 0xCE,
  63. (byte) 0x0E, (byte) 0x0A, (byte) 0xCA, (byte) 0xCB, (byte) 0x0B,
  64. (byte) 0xC9, (byte) 0x09, (byte) 0x08, (byte) 0xC8, (byte) 0xD8,
  65. (byte) 0x18, (byte) 0x19, (byte) 0xD9, (byte) 0x1B, (byte) 0xDB,
  66. (byte) 0xDA, (byte) 0x1A, (byte) 0x1E, (byte) 0xDE, (byte) 0xDF,
  67. (byte) 0x1F, (byte) 0xDD, (byte) 0x1D, (byte) 0x1C, (byte) 0xDC,
  68. (byte) 0x14, (byte) 0xD4, (byte) 0xD5, (byte) 0x15, (byte) 0xD7,
  69. (byte) 0x17, (byte) 0x16, (byte) 0xD6, (byte) 0xD2, (byte) 0x12,
  70. (byte) 0x13, (byte) 0xD3, (byte) 0x11, (byte) 0xD1, (byte) 0xD0,
  71. (byte) 0x10, (byte) 0xF0, (byte) 0x30, (byte) 0x31, (byte) 0xF1,
  72. (byte) 0x33, (byte) 0xF3, (byte) 0xF2, (byte) 0x32, (byte) 0x36,
  73. (byte) 0xF6, (byte) 0xF7, (byte) 0x37, (byte) 0xF5, (byte) 0x35,
  74. (byte) 0x34, (byte) 0xF4, (byte) 0x3C, (byte) 0xFC, (byte) 0xFD,
  75. (byte) 0x3D, (byte) 0xFF, (byte) 0x3F, (byte) 0x3E, (byte) 0xFE,
  76. (byte) 0xFA, (byte) 0x3A, (byte) 0x3B, (byte) 0xFB, (byte) 0x39,
  77. (byte) 0xF9, (byte) 0xF8, (byte) 0x38, (byte) 0x28, (byte) 0xE8,
  78. (byte) 0xE9, (byte) 0x29, (byte) 0xEB, (byte) 0x2B, (byte) 0x2A,
  79. (byte) 0xEA, (byte) 0xEE, (byte) 0x2E, (byte) 0x2F, (byte) 0xEF,
  80. (byte) 0x2D, (byte) 0xED, (byte) 0xEC, (byte) 0x2C, (byte) 0xE4,
  81. (byte) 0x24, (byte) 0x25, (byte) 0xE5, (byte) 0x27, (byte) 0xE7,
  82. (byte) 0xE6, (byte) 0x26, (byte) 0x22, (byte) 0xE2, (byte) 0xE3,
  83. (byte) 0x23, (byte) 0xE1, (byte) 0x21, (byte) 0x20, (byte) 0xE0,
  84. (byte) 0xA0, (byte) 0x60, (byte) 0x61, (byte) 0xA1, (byte) 0x63,
  85. (byte) 0xA3, (byte) 0xA2, (byte) 0x62, (byte) 0x66, (byte) 0xA6,
  86. (byte) 0xA7, (byte) 0x67, (byte) 0xA5, (byte) 0x65, (byte) 0x64,
  87. (byte) 0xA4, (byte) 0x6C, (byte) 0xAC, (byte) 0xAD, (byte) 0x6D,
  88. (byte) 0xAF, (byte) 0x6F, (byte) 0x6E, (byte) 0xAE, (byte) 0xAA,
  89. (byte) 0x6A, (byte) 0x6B, (byte) 0xAB, (byte) 0x69, (byte) 0xA9,
  90. (byte) 0xA8, (byte) 0x68, (byte) 0x78, (byte) 0xB8, (byte) 0xB9,
  91. (byte) 0x79, (byte) 0xBB, (byte) 0x7B, (byte) 0x7A, (byte) 0xBA,
  92. (byte) 0xBE, (byte) 0x7E, (byte) 0x7F, (byte) 0xBF, (byte) 0x7D,
  93. (byte) 0xBD, (byte) 0xBC, (byte) 0x7C, (byte) 0xB4, (byte) 0x74,
  94. (byte) 0x75, (byte) 0xB5, (byte) 0x77, (byte) 0xB7, (byte) 0xB6,
  95. (byte) 0x76, (byte) 0x72, (byte) 0xB2, (byte) 0xB3, (byte) 0x73,
  96. (byte) 0xB1, (byte) 0x71, (byte) 0x70, (byte) 0xB0, (byte) 0x50,
  97. (byte) 0x90, (byte) 0x91, (byte) 0x51, (byte) 0x93, (byte) 0x53,
  98. (byte) 0x52, (byte) 0x92, (byte) 0x96, (byte) 0x56, (byte) 0x57,
  99. (byte) 0x97, (byte) 0x55, (byte) 0x95, (byte) 0x94, (byte) 0x54,
  100. (byte) 0x9C, (byte) 0x5C, (byte) 0x5D, (byte) 0x9D, (byte) 0x5F,
  101. (byte) 0x9F, (byte) 0x9E, (byte) 0x5E, (byte) 0x5A, (byte) 0x9A,
  102. (byte) 0x9B, (byte) 0x5B, (byte) 0x99, (byte) 0x59, (byte) 0x58,
  103. (byte) 0x98, (byte) 0x88, (byte) 0x48, (byte) 0x49, (byte) 0x89,
  104. (byte) 0x4B, (byte) 0x8B, (byte) 0x8A, (byte) 0x4A, (byte) 0x4E,
  105. (byte) 0x8E, (byte) 0x8F, (byte) 0x4F, (byte) 0x8D, (byte) 0x4D,
  106. (byte) 0x4C, (byte) 0x8C, (byte) 0x44, (byte) 0x84, (byte) 0x85,
  107. (byte) 0x45, (byte) 0x87, (byte) 0x47, (byte) 0x46, (byte) 0x86,
  108. (byte) 0x82, (byte) 0x42, (byte) 0x43, (byte) 0x83, (byte) 0x41,
  109. (byte) 0x81, (byte) 0x80, (byte) 0x40 };
  110. public int value;
  111. public CRC16() {
  112. value = 0;
  113. }
  114. public void update(byte[] puchMsg, int usDataLen) {
  115. int uIndex; // int i = 0;
  116. for (int i = 0; i < usDataLen; i++) {
  117. uIndex = (uchCRCHi ^ puchMsg[i]) & 0xff;
  118. uchCRCHi = (byte) (uchCRCLo ^ auchCRCHi[uIndex]);
  119. uchCRCLo = auchCRCLo[uIndex];
  120. }
  121. value = ((((int) uchCRCHi) << 8 | (((int) uchCRCLo) & 0xff))) & 0xffff;
  122. return;
  123. }
  124. public void reset() {
  125. value = 0;
  126. uchCRCHi = (byte) 0xff;
  127. uchCRCLo = (byte) 0xff;
  128. }
  129. public int getValue() {
  130. return value;
  131. }
  132. private static byte uniteBytes(byte src0, byte src1) {
  133. byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
  134. .byteValue();
  135. _b0 = (byte) (_b0 << 4);
  136. byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
  137. .byteValue();
  138. byte ret = (byte) (_b0 ^ _b1);
  139. return ret;
  140. }
  141. private static byte[] HexString2Buf(String src) {
  142. int len = src.length();
  143. byte[] ret = new byte[len / 2 + 2];
  144. byte[] tmp = src.getBytes();
  145. for (int i = 0; i < len; i += 2) {
  146. ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
  147. }
  148. return ret;
  149. }
  150. public static byte[] getSendBuf(String toSend) {
  151. byte[] bb = HexString2Buf(toSend);
  152. CRC16 crc16 = new CRC16();
  153. crc16.update(bb, bb.length - 2);
  154. int ri = crc16.getValue();
  155. bb[bb.length - 1] = (byte) (0xff & ri);
  156. bb[bb.length - 2] = (byte) ((0xff00 & ri) >> 8);
  157. return bb;
  158. }
  159. public static boolean checkBuf(byte[] bb) {
  160. CRC16 crc16 = new CRC16();
  161. crc16.update(bb, bb.length - 2);
  162. int ri = crc16.getValue();
  163. if (bb[bb.length - 1] == (byte) (ri & 0xff)
  164. && bb[bb.length - 2] == (byte) ((0xff00 & ri) >> 8))
  165. return true;
  166. return false;
  167. }
  168. public static String getBufHexStr(byte[] raw) {
  169. if (raw == null) {
  170. return null;
  171. }
  172. final StringBuilder hex = new StringBuilder(2 * raw.length);
  173. for (final byte b : raw) {
  174. hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(
  175. HEXES.charAt((b & 0x0F)));
  176. }
  177. return hex.toString().toLowerCase();
  178. }
  179. /****
  180. * * 得到CRC验证 } } } } } }
  181. *
  182. * @param tt
  183. * * @return
  184. */
  185. public static String getCrc(String tem) { // String tem=""; // for(int
  186. // i=0;i<tt.length;i++){ //
  187. // tem+=tt[i]; //
  188. // System.out.println("这是传入的值"+tt[i]);
  189. // // }
  190. byte[] sbuf = CRC16.getSendBuf(tem);
  191. System.out.println("这是得到的crc" + CRC16.getBufHexStr(sbuf));
  192. return CRC16.getBufHexStr(sbuf).substring(12, 16).toLowerCase();
  193. }
  194. /** 得到要发送的数据 * @param args */
  195. public static String getSendData(String[] tt) {
  196. String tem = "";
  197. for (int i = 0; i < tt.length; i++) {
  198. tem += tt[i];
  199. }
  200. byte[] sbuf = CRC16.getSendBuf(tem);
  201. return CRC16.getBufHexStr(sbuf);
  202. }
  203. public static byte[] getSendBuf2(String[] tt) {
  204. String tem = "";
  205. for (int i = 0; i < tt.length; i++) {
  206. tem += tt[i];
  207. }
  208. byte[] bb = HexString2Buf(tem);
  209. CRC16 crc16 = new CRC16();
  210. crc16.update(bb, bb.length - 2);
  211. int ri = crc16.getValue();
  212. bb[bb.length - 1] = (byte) (0xff & ri);
  213. bb[bb.length - 2] = (byte) ((0xff00 & ri) >> 8);
  214. return bb;
  215. }
  216. public static void main(String[] args) { // TODO Auto-generated method stub
  217. // //0103040a3d3fb739a1----sendB
  218. // //010304b8523ffeef32----sendB
  219. String ms = "";
  220. byte[] sbuf = CRC16.getSendBuf("010400000015");
  221. System.out.println(CRC16.getBufHexStr(sbuf));
  222. }
  223. }

Float16算法:

  1. package com.jetf.mm;
  2. public class Float16 {
  3. @SuppressWarnings("unused")
  4. public static void main(String[] args) {
  5. String s = "057e";
  6. Float value = Float.intBitsToFloat(Integer.valueOf(s.trim(), 16));
  7. // Double
  8. System.out.println(Integer.valueOf(s.trim(), 16));
  9. Float f = 225.92f;
  10. System.out.println(Integer.toHexString(Float.floatToIntBits(f)));
  11. }
  12. }

发表评论

表情:
评论列表 (有 0 条评论,264人围观)

还没有评论,来说两句吧...

相关阅读

    相关 串口通讯介绍

    串口通讯的物理连接和传输协议,是学习单片机串口编程的基础。 本文参照《深入浅出玩转51单片机》和《零死角玩转STM32》书籍,对通讯以及串口一些基本概念做了详解。 1. 串

    相关 java串口通讯实例

    现在一般的电脑都没有串口端口的了,所以还是用虚拟的串口来做测试吧。 我们用 VSPD(Virtual Serial Port Driver) 这个软件建立两个虚拟串口,COM

    相关 串口通讯之 CRC校验

    一、CRC16简介       循环冗余码CRC检验技术广泛应用于测控及通信领域。CRC计算可以靠专用的硬件来实现,但是对于低成本的微控制器系统,在没有硬件支持下实现CRC