简体   繁体   English

如何从端口列表中仅获取用户界面Com端口?

[英]How to get only User interface Com port from list of ports?

I am developing a C#.net app in which I have communication with a USB 3G modems Com port for sending and receiving messages. 我正在开发一个C#.net应用程序,我在其中与USB 3G调制解调器Com端口进行通信,用于发送和接收消息。

Below is my code that I am currently using for getting a list of ports: 下面是我目前用于获取端口列表的代码:

string[] ports = SerialPort.GetPortNames();

Now I want to get only UI port from list of port, for example if 3G modem has two ports say for COM4 and COM6 in which first is Application interface port and another is UI port. 现在我想从端口列表中仅获取UI端口,例如,如果3G调制解调器有两个端口,例如COM4和COM6,其中第一个是应用程序接口端口,另一个是UI端口。

How can I programmatically get the UI port? 如何以编程方式获取UI端口?

A serial port doesn't know what is connected on the other side. 串口不知道另一端连接的是什么。 You need to try to open each one and send something like "AT\\r\\n" and expect "OK" to check on which one your modem is connected. 您需要尝试打开每个并发送类似"AT\\r\\n"并期望"OK"以检查调制解调器连接的是哪一个。

EDIT: 编辑:

    using System;
    using System.IO.Ports;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text;


    private static bool IsModem(string PortName)
    {

      SerialPort port= null;
       try
       { 
         port = new SerialPort(PortName,9600); //9600 baud is supported by most modems
         port.ReadTimeout = 200;
         port.Open();
         port.Write("AT\r\n");

         //some modems will return "OK\r\n"
         //some modems will return "\r\nOK\r\n"
         //some will echo the AT first
         //so
         for(int i=0;i<4;i++) //read a maximum of 4 lines in case some other device is posting garbage
         {
              string line = port.ReadLine();
              if(line.IndexOf("OK")!=-1)
              {
                 return true;
              }
         }
        return false;


       }
       catch(Exception ex)
       {
         // You should implement more specific catch blocks so that you would know 
         // what the problem was, ie port may be in use when you are trying
         // to test it so you should let the user know that as he can correct that fault

          return false;
       }
       finally
       {
         if(port!=null)
         {
            port.Close();
         }     
       }



    }

    public static string[] FindModems()
    {
      List<string> modems = new List<string>();
      string[] ports = SerialPort.GetPortNames();

       for(int i =0;i<ports.Length;i++)
       {
         if(IsModem(ports[i]))
         {
           modems.Add(ports[i]);
         }
        }
        return modems.ToArray();
    }

Something like this should work, I didn't test it ( can't test it ). 这样的东西应该工作,我没有测试它(不能测试它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM