zsh_root
2025-01-06 7857a444de69124e9f7fb45f98b0ae818b107f23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package tools.ChuanKou;
 
 
import gnu.io.*;
import tools.ShowMessage;
 
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class SerialPortManager {
    static Enumeration<CommPortIdentifier> portList;
    static CommPortIdentifier portId;
 
    
    /**
     * 列出本地连接的所有串口名称集合
     * @param args
     */
    @SuppressWarnings("unchecked")//告诉编译器忽略 unchecked 警告信息,如使用List,ArrayList等未进行参数化产生的警告信息。
    public static List<String> get_all_port(){
        List<String> all_port=new ArrayList<String>();
        portList = CommPortIdentifier.getPortIdentifiers();
        while(portList.hasMoreElements()){
            portId = (CommPortIdentifier)portList.nextElement();
            if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
                all_port.add(portId.getName());
            }
        }
        return all_port;        
    }
    
    /**打开串口
     * @param chuankou 串口号
     * @param botelv 波特率*/
    public static SerialPort open_chuankou(String chuankou,int botelv) {
        SerialPort serialPort=null;
        try {
        serialPort =SerialPortUtil.openSerialPort(chuankou,botelv);
        } catch (NoSuchPortException e) {
            // TODO 自动生成的 catch 块
            ShowMessage.zidingyi(chuankou+"不存在!");
        } catch (PortInUseException e) {
            // TODO 自动生成的 catch 块
            ShowMessage.zidingyi(chuankou+"已被占用!");
        } catch (UnsupportedCommOperationException e) {
            // TODO 自动生成的 catch 块
            ShowMessage.zidingyi(chuankou+"不支持操作!");
        }
        return serialPort;
        
    }
}