java rxtx读取端口列表_RXTX串口协议,端口properties文件设置,获取

packagecom.dartfar.rfid.server;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.UnsupportedEncodingException;importjava.math.BigInteger;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;importjava.sql.Statement;importjava.text.DateFormat;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.Enumeration;importjava.util.List;importjava.util.Map;importjava.util.Properties;importjava.util.ResourceBundle;importjava.util.TooManyListenersException;importjavax.annotation.Resource;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.struts2.interceptor.ServletRequestAware;importorg.apache.struts2.interceptor.ServletResponseAware;importorg.apache.struts2.interceptor.SessionAware;importorg.springframework.web.context.request.RequestContextHolder;importorg.springframework.web.context.request.ServletRequestAttributes;importcom.dafu.action.testRXTX;importcom.dafu.model.game.ChengJi;importcom.dafu.service.game.GameService;importcom.dafu.vo.ChengJiVo;importgnu.io.CommPort;importgnu.io.CommPortIdentifier;importgnu.io.NoSuchPortException;importgnu.io.PortInUseException;importgnu.io.SerialPort;importgnu.io.SerialPortEvent;importgnu.io.SerialPortEventListener;importgnu.io.UnsupportedCommOperationException;importnet.sf.json.JSONObject;/*** 处理自动出入库线程*/

public class AutoOutInStoreHandler implementsRunnable, SessionAware, ServletResponseAware, ServletRequestAware

{public static String aa = "";/*** session对象*/

private Mapsession;/*** request对象*/

privateHttpServletRequest request;/*** response对象*/

privateHttpServletResponse response;privateGameService gameservice;//全局定义端口

public staticSerialPort serialPort;privateString startTime;

@SuppressWarnings("static-access")public voidrun() {//获得系统端口列表

getSystemPort();

ResourceBundle resource= ResourceBundle.getBundle("port");//test为属性文件名,放在包com.mmq下,如果是放在src下,直接用test即可

String port= resource.getString("endPort");//System.out.println(">>>>>>>>>><<<<<<<<<<

serialPort = openSerialPort(port, 57600);//启动一个线程每2s向串口发送数据,发送1000次hello

new Thread(newRunnable()

{

@Overridepublic voidrun()

{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, newSerialPortEventListener()

{

@Overridepublic voidserialEvent(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(newDate()));//bytes转回十六进制

StringBuilder hex = newStringBuilder();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 list=gameservice.getList();//

//System.out.println(list.size()+"<<<<<<<<<<<<<<<<<

//System.out.println(">>>>>>>>"+startTime+"0000000000000");//

String endTime=new SimpleDateFormat("mm:ss.SSS").format(newDate());//

//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(newDate()));//打开驱动,存入数据,关闭

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 ListgetSystemPort()

{

List systemPorts = new ArrayList<>();//获得系统可用的端口

Enumeration portList =CommPortIdentifier.getPortIdentifiers();while(portList.hasMoreElements())

{

String portName= portList.nextElement().getName();//获得端口的名字

systemPorts.add(portName);

}

System.out.println("系统可用端口列表:" +systemPorts);returnsystemPorts;

}// /*** 开启串口

*

*@paramserialPortName 串口名称

*@parambaudRate 波特率

*@return串口对象*/

public static SerialPort openSerialPort(String serialPortName, intbaudRate)

{try{//通过端口名称得到端口

CommPortIdentifier portIdentifier =CommPortIdentifier.getPortIdentifier(serialPortName);//打开端口,(自定义名字,打开超时时间)

CommPort commPort = portIdentifier.open(serialPortName, 2222);//判断是不是串口

if (commPort instanceofSerialPort)

{

SerialPort serialPort=(SerialPort)commPort;//设置串口参数(波特率,数据位8,停止位1,校验位无)

serialPort.setSerialPortParams(baudRate,

SerialPort.DATABITS_8,

SerialPort.STOPBITS_1,

SerialPort.PARITY_NONE);

System.out.println("开启串口成功,串口名称:" +serialPortName);returnserialPort;

}else{//是其他类型的端口

throw newNoSuchPortException();

}

}catch(NoSuchPortException e)

{

e.printStackTrace();

}catch(PortInUseException e)

{

e.printStackTrace();

}catch(UnsupportedCommOperationException e)

{

e.printStackTrace();

}return null;

}// /*** 关闭串口

*

*@paramserialPort 要关闭的串口对象*/

public static voidcloseSerialPort()

{if (serialPort != null)

{

serialPort.close();

System.out.println("关闭了串口:" +serialPort.getName());

serialPort= null;

}

}// /*** 向串口发送数据

*

*@paramserialPort 串口对象

*@paramdata 发送的数据*/

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();

}

}

}// /*** 从串口读取数据

*

*@paramserialPort 要读取的串口

*@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();

}

}returnbytes;

}// /*** 给串口设置监听

*

*@paramserialPort

*@paramlistener*/

public static voidsetListenerToSerialPort(SerialPort serialPort, SerialPortEventListener listener)

{try{//给串口添加事件监听

serialPort.addEventListener(listener);

}catch(TooManyListenersException e)

{

e.printStackTrace();

}

serialPort.notifyOnDataAvailable(true);//串口有数据监听

serialPort.notifyOnBreakInterrupt(true);//中断事件监听

}

@Overridepublic voidsetServletResponse(HttpServletResponse response)

{this.response =response;

}

@Overridepublic void setSession(Mapsession)

{this.session =session;

}

@Overridepublic voidsetServletRequest(HttpServletRequest request)

{this.request =request;

}

@Resourcepublic voidsetGameservice(GameService gameservice)

{this.gameservice =gameservice;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值