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.

  

 

線程html

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文件定義java

startToendPort=COM7

endPort=COM6

//獲取properties文件定義選擇的端口號mysql

    
        ResourceBundle resource = ResourceBundle.getBundle("port");//port爲屬性文件名,放在包com.mmq下,若是是放在src下,直接用test便可
        
        
        String port = resource.getString("startToendPort");
相關文章
相關標籤/搜索