Check balance using USSD Command in C#

风格不统一 提交于 2019-12-13 04:38:31

问题


I update for this question and know it worked correctly..

I try to check balance in my mavecom modem but I got no response in my textbox. It stays empty.

Here my code :

private SerialPort _port;

private void simpleButton1_Click(object sender, EventArgs e)
    {
        _port = new SerialPort();
        _port.PortName = cbPort.Text;
        _port.BaudRate = 115200;
        _port.Parity = Parity.None;
        _port.DataBits = 8;
        _port.StopBits = StopBits.One;
        _port.Handshake = Handshake.RequestToSend;

        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        port.Open();

        port.Write("AT+CUSD=1,\"" + txtUSSD.Text + "\",15" + "\r");
    }

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            // read the response.
            var response = ((SerialPort)sender).ReadLine();

            // Need to update the txtProvider on the UI thread .
            //showing result in txtOutput based on txtProvider USSD Command
            this.Invoke(new Action(() => txtOutput.Text = response)); 
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

This is solved and can be use to check the balance....


回答1:


Good start, you are properly terminating AT command lines with \r (not using WriteLine or any other such incorrect approaches that unfortunately are common beginner problems). However the format of the command is defined in 27.007 to be

AT+CUSD=[<n>[,<str>[,<dcs>]]]
...
Defined values
...
<str>: string type USSD-string ...

and string parameters shall always be enclosed with double quotes (V.250 chapter 5.4.2.2 String constants: String constants shall be bounded at the beginning and end by the double-quote character).

So without knowing the textProvider object in detail I am quite confident that your code should be

port.Write("AT+CUSD=1,\"" + txtProvider.Text + "\",15" + "\r");

but note that if txtProvider.Text contains any " characters they must be escaped (not as \" by the way, check 5.4.2.2).


However even with the above fixed you need to seriously rework your reception handling. You MUST read and parse every single line of response from the modem until you get a Final result code back (most commonly OK or ERROR, but there are several others). Any other way cannot work reliably. See this answer for pseudo code structure of how to do it properly.

And as commented, you are closing the port too early.



来源:https://stackoverflow.com/questions/31677028/check-balance-using-ussd-command-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!