You should never, never, ever use sleep as a substitute for waiting for the Final result code from the modem. Just as you would not write a http client that completely ignores all responses from the http server, you should not send AT commands to a modem and completely ignore the responses it sends back. You must read and parse everything the modem sends back to you. Nothing else will work reliably.
My suggestion is that you start by fetching a copy of the V.250 standard and read at least all of chapter 5. This standard is the bible for AT command handling and will teach you an enormous amount regarding AT command handling. Like for instance that using WriteLine
and/or Environment.NewLine
is wrong; AT command lines should be terminated with
alone and nothing else.
Just to emphasis how important that document is: Even after working with implementing AT command in mobile phones in Ericsson for over a decade I and my colleagues still consulted that standard regularly.
In fact stop reading this answer here now, download that document, read all of chapter 5 before returning to read the rest.
For sending commands where you do not particularly care about the response1, the only reliably approach is to do something similar to
serialport.Open();
...
// start sending AT+CMGF=1
serialport.Write("AT+CMGF=1
");
do {
line = readLine(serialport);
} while (! is_final_result_code(line))
// Sending of AT+CMGF=1 command finished (successfully or not)
...
serialport.Close();
where the readLine
function reads one and one byte from the serial port until it has received a complete line terminated with
and then returns that line.
You can look at the code for atinout for an example for the is_final_result_code
function (you can also compare to isFinalResponseError
and isFinalResponseSuccess
2 in ST-Ericsson's U300 RIL).
The AT+CMGS command must be handled differently. You must wait for the "
> "
response from the modem before sending the payload, see the first part of this answer for details.
1 Although you most likely should care about if the command was executed successfully or not. See this answer for a realistic way to send a command line and parse the response lines.
2 Note that CONNECT
is not a final result code, it is an intermediate result code, so the name isFinalResponseSuccess is strictly speaking not 100% correct.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…