RXTX串口协议,端口properties文件设置,获取
配置
Windows ---------------------------------------------------- Choose your binary build - x64 or x86 (based on which version of the JVM you are installing to) NOTE: You MUST match your architecture. You can't install the i386 version on a 64-bit version of the JDK and vice-versa. For a JDK installation: Copy RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext Copy rxtxSerial.dll ---> <JAVA_HOME>\jre\bin Copy rxtxParallel.dll ---> <JAVA_HOME>\jre\bin Linux ---------------------------------------------------- Choose your binary build - x86_64 or i386 (based on which version of the JVM you are installing to) NOTE: You MUST match your architecture. You can't install the i386 version on a 64-bit version of the JDK and vice-versa. For a JDK installation on architecture=i386 Copy RXTXcomm.jar ---> <JAVA_HOME>/jre/lib/ext Copy librxtxSerial.so ---> <JAVA_HOME>/jre/lib/i386/ Copy librxtxParallel.so ---> <JAVA_HOME>/jre/lib/i386/ NOTE: For a JDK installation on architecture=x86_64, just change the i386 to x86_64 above.
线程
package com.dartfar.rfid.server; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ResourceBundle; import java.util.TooManyListenersException; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.dafu.action.testRXTX; import com.dafu.model.game.ChengJi; import com.dafu.service.game.GameService; import com.dafu.vo.ChengJiVo; import gnu.io.CommPort; 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 net.sf.json.JSONObject; /** * 处理自动出入库线程 */ public class AutoOutInStoreHandler implements Runnable, SessionAware, ServletResponseAware, ServletRequestAware { public static String aa = ""; /** * session对象 */ private Map<String, Object> session; /** * request对象 */ private HttpServletRequest request; /** * response对象 */ private HttpServletResponse response; private GameService gameservice; //全局定义端口 public static SerialPort serialPort; private String startTime; @SuppressWarnings("static-access") public void run() { // 获得系统端口列表 getSystemPort(); ResourceBundle resource = ResourceBundle.getBundle("port");//test为属性文件名,放在包com.mmq下,如果是放在src下,直接用test即可 String port = resource.getString("endPort"); // System.out.println(">>>>>>>>>><<<<<<<<<<<"+port); // 开启端口COM6,波特率57600. serialPort = openSerialPort(port, 57600); // 启动一个线程每2s向串口发送数据,发送1000次hello new Thread(new Runnable() { @Override public void run() { int i = 1; while (i < 1000) { String s = "hello"; byte[] bytes = s.getBytes(); testRXTX.sendData(serialPort, bytes);// 发送数据 i++; try { Thread.sleep(2000); if(serialPort == null) break; } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); // 设置串口的listener testRXTX.setListenerToSerialPort(serialPort, new SerialPortEventListener() { @Override public void serialEvent(SerialPortEvent arg0) { if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {// 数据通知 byte[] bytes = testRXTX.readData(serialPort); System.out.println("收到的数据长度:" + bytes.length); try { System.out.println("收到的数据:" + new String(bytes, "utf-8") + "===,==" +new SimpleDateFormat("mm分ss秒SSS毫秒").format(new Date())); //bytes转回十六进制 StringBuilder hex = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; boolean flag = false; if (b < 0) flag = true; int absB = Math.abs(b); if (flag) absB = absB | 0x80; //System.out.println(absB & 0xFF); String tmp = Integer.toHexString(absB & 0xFF); if (tmp.length() == 1) { //转化的十六进制不足两位,需要补0 hex.append("0"); } hex.append(tmp.toLowerCase()); } startTime=AutoOrderStoreHandler.getStartTime(); System.out.println("<><><><><><><><><><><><><><>"+startTime); //String codestr=new BigInteger(hex.toString(), 16).toString(); // System.out.println(">>>>>>>>>>"+hex.toString()+"==========="+codestr); // List<ChengJi> list=gameservice.getList(); // // System.out.println(list.size()+"<<<<<<<<<<<<<<<<<<"); //String beginTime=startTime; // // System.out.println(">>>>>>>>"+startTime+"0000000000000"); // String endTime=new SimpleDateFormat("mm:ss.SSS").format(new Date()); // // System.out.println(">>>>>>>>"+endTime+"<<<<<<<<<<"); // SimpleDateFormat dfs = new SimpleDateFormat("mm:ss.SSS"); long between = 0; try { java.util.Date begin = dfs.parse(startTime); java.util.Date end = dfs.parse(endTime); between = (end.getTime() - begin.getTime());// 得到两者的毫秒数 } catch (Exception ex) { ex.printStackTrace(); } long day = between / (24 * 60 * 60 * 1000); long hour = (between / (60 * 60 * 1000) - day * 24); long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60); long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000); // System.out.println(hour + ":" + min + ":" + s + "." + ms); // String chengjiTime= min + ":" + s + "." + ms; System.out.println("收到的数据:" + hex.toString() + "===,==" +new SimpleDateFormat("mm:ss.SSS").format(new Date())); //打开驱动,存入数据,关闭 Connection con = null; PreparedStatement pstm = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://47.105.242.156:3306/partner?characterEncoding=utf-8"; String user = "root"; String password = "Abc123!_"; con = DriverManager.getConnection(url, user, password); String sql = "insert into chengji(code,time) value(?,?)"; pstm = con.prepareStatement(sql); pstm.setString(1, hex.toString()); pstm.setString(2, chengjiTime); // if (list!=null&&list.size()>0) //{ //return; //}else{ int row = pstm.executeUpdate(); System.out.println("新增数据为:" + row + "条"); // } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally{ if(con != null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pstm != null){ try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } } } // } catch (UnsupportedEncodingException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }); } /** * 获得系统可用的端口名称列表 * * @return 可用端口名称列表 */ @SuppressWarnings("unchecked") public static List<String> getSystemPort() { List<String> systemPorts = new ArrayList<>(); // 获得系统可用的端口 Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { String portName = portList.nextElement().getName();// 获得端口的名字 systemPorts.add(portName); } System.out.println("系统可用端口列表:" + systemPorts); return systemPorts; } // /** * 开启串口 * * @param serialPortName 串口名称 * @param baudRate 波特率 * @return 串口对象 */ public static SerialPort openSerialPort(String serialPortName, int baudRate) { try { // 通过端口名称得到端口 CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName); // 打开端口,(自定义名字,打开超时时间) CommPort commPort = portIdentifier.open(serialPortName, 2222); // 判断是不是串口 if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort)commPort; // 设置串口参数(波特率,数据位8,停止位1,校验位无) serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); System.out.println("开启串口成功,串口名称:" + serialPortName); return serialPort; } else { // 是其他类型的端口 throw new NoSuchPortException(); } } catch (NoSuchPortException e) { e.printStackTrace(); } catch (PortInUseException e) { e.printStackTrace(); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); } return null; } // /** * 关闭串口 * * @param serialPort 要关闭的串口对象 */ public static void closeSerialPort() { if (serialPort != null) { serialPort.close(); System.out.println("关闭了串口:" + serialPort.getName()); serialPort = null; } } // /** * 向串口发送数据 * * @param serialPort 串口对象 * @param data 发送的数据 */ public static void sendData(SerialPort serialPort, byte[] data) { OutputStream os = null; try { os = serialPort.getOutputStream();// 获得串口的输出流 os.write(data); os.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (os != null) { os.close(); os = null; } } catch (IOException e) { e.printStackTrace(); } } } // /** * 从串口读取数据 * * @param serialPort 要读取的串口 * @return 读取的数据 */ public static byte[] readData(SerialPort serialPort) { InputStream is = null; byte[] bytes = null; try { is = serialPort.getInputStream();// 获得串口的输入流 int bufflenth = is.available();// 获得数据长度 while (bufflenth != 0) { bytes = new byte[bufflenth];// 初始化byte数组 is.read(bytes); bufflenth = is.available(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); is = null; } } catch (IOException e) { e.printStackTrace(); } } return bytes; } // /** * 给串口设置监听 * * @param serialPort * @param listener */ public static void setListenerToSerialPort(SerialPort serialPort, SerialPortEventListener listener) { try { // 给串口添加事件监听 serialPort.addEventListener(listener); } catch (TooManyListenersException e) { e.printStackTrace(); } serialPort.notifyOnDataAvailable(true);// 串口有数据监听 serialPort.notifyOnBreakInterrupt(true);// 中断事件监听 } @Override public void setServletResponse(HttpServletResponse response) { this.response = response; } @Override public void setSession(Map<String, Object> session) { this.session = session; } @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } @Resource public void setGameservice(GameService gameservice) { this.gameservice = gameservice; } }
调去线程
public String Start() { AutoOutInStoreHandler runner1 = new AutoOutInStoreHandler(); Thread thread1 = new Thread(runner1); thread1.start(); }
properties文件定义
startToendPort=COM7
endPort=COM6
//获取properties文件定义选择的端口号
ResourceBundle resource = ResourceBundle.getBundle("port");//port为属性文件名,放在包com.mmq下,如果是放在src下,直接用test即可 String port = resource.getString("startToendPort");