如何在c#中检索发送USSD命令的响应结果

本文关键字:命令 USSD 响应 结果 检索 | 更新日期: 2023-09-27 18:29:36

我使用以下代码发送USSD命令:

SerialPort port = new SerialPort();
port.BaudRate = 921600;
port.PortName = "COM16";
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
port.ReadTimeout = 3000;
port.WriteTimeout = 3000;
port.DataReceived += port_DataReceived;
port.Open();
port.Write("AT+CUSD=1,'"*140*1#'"" + "'r'n");
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
        SerialPort spL = (SerialPort)sender;
        byte[] buf = new byte[spL.BytesToRead];
        spL.Read(buf, 0, buf.Length);
        foreach (Byte b in buf)
        {
            message += b.ToString();
        }
        var result = Encoding.ASCII.GetString(buf);//just return OK
    }

为什么只在结果中检索OK?

在这种情况下,我想检索我的余额,我必须收到这样的答案:"您的余额是100$…",但只检索:"AT+CUSD=1,''"*140*1#''"''r''n''r''n",但当我通过调制解调器自己的应用程序发送此命令时,从操作员处检索正确的响应,这意味着我的发送命令是可以的,但该应用程序接收到所有答案,但我收到一半。

如何在c#中检索发送USSD命令的响应结果

实际上我更新了代码,现在它可以与GSMCOMM库一起使用。我可以检查一下我的平衡,看看反应。我只是在接收响应时将响应附加到一个字符串变量中。

public string SendUssdRequest(string request)
    {
        log.DebugFormat("Sending USSD Request {0}", request);
        string result = "";
        try
        {
            IProtocol protocol = comm.GetProtocol();
            string gottenString = protocol.ExecAndReceiveMultiple("AT+CUSD=1," + request + ",15");
            result = gottenString;
            int i = 0;
            if (!gottenString.Contains("'r'n+CUSD: 2"))
            {
                bool receiving = false;
                do
                {
                    receiving = protocol.Receive(out gottenString);
                    result += gottenString;
                    ++i;
                } while (receiving);
            }
            result = result.Replace("'r'n", "");
            result = result.Replace("+CUSD: 2,", "");
            result = result.Replace(",15", "");
            log.DebugFormat("{1} - USSD Response is:  {0}", result,SenderNumber);
            return result;
        }
        catch(Exception ex) 
        {
            log.Error(ex);
        }
        finally
        {
            comm.ReleaseProtocol();
        }
        return "";
    }
代码末尾的

port.Write("AT+CUSD=1,'"*140*1#'"" + ",15'r");