问题
I am working on an application that sends SMS through GSM Modem, and i use AT Commands for that. When i debug my application, Then sms is sent to reciever, but when i run the application sms is not sent to Reciever. My code is below and my gsm Modem is D-Link DWM-156. is there any wrong here in my code? thanks.
if (SPort.IsOpen) {
int i = 0;
while (i < msgs.Count)
{
SPort.DiscardInBuffer();
System.Threading.Thread.Sleep(1000);
var res = SPort.ReadExisting();
SPort.DiscardOutBuffer();
System.Threading.Thread.Sleep(1000);
SPort.Write("AT\r");
System.Threading.Thread.Sleep(1000);
while ((res = SPort.ReadExisting()).Contains("ERROR")) ;
resultResponse += "1" + res + "---";
SPort.Write("AT+CMGF=0\r");
System.Threading.Thread.Sleep(100);
while ((res = SPort.ReadExisting()).Contains("ERROR")) ;
resultResponse += "2" + res + "---";
SPort.Write("AT+CSCS=\"HEX\"\r");//char set
System.Threading.Thread.Sleep(100);
while ((res = SPort.ReadExisting()).Contains("ERROR")) ;
resultResponse += "3" + res + "---";
SPort.Write("AT+CSMP=17,71,0,17\r");
System.Threading.Thread.Sleep(100);
while ((res = SPort.ReadExisting()).Contains("ERROR")) ;
resultResponse += "4" + res + "---";
string hexString = msgs[i];
SPort.Write(string.Format("AT+CMGS={0}\r", (hexString.Length - 16) / 2));
System.Threading.Thread.Sleep(100);
while ((res = SPort.ReadExisting()).Contains("ERROR")) ;
resultResponse += "5" + res + "---";
SPort.Write(string.Format("{0}{1}\n", hexString, Convert.ToChar(26)));
System.Threading.Thread.Sleep(100);
while ((res = SPort.ReadExisting()).Contains("ERROR")) ;
resultResponse += "6" + res + "---";
System.Threading.Thread.Sleep(1500);
response += res;
i++;
}
}
回答1:
is there any wrong here in my code?
Yes, you need to rework your response handling a little bit, but you are actually close (and way better that the unfortunately not uncommon send-sleep pattern that I initially thought you were using when I saw a call to Sleep). And you are correctly using \r
to terminate AT command lines, so good start.
After sending an AT command you should continuously read (over and over again) response lines from the modem until you get a Final result code (using
Contains("ERROR")
is not good enough). See this answer for the code flow structure and reference to a function for determining if a line is a final result code.
You can keep the 100ms delay between sending the command line and starting to read the response; I have in fact added 200ms to my atinout program recently (locally, not released yet).
And for the AT+CMGS
command, you must wait until you have received the "\r\n> "
string before sending any payload data (also covered in the answer linked above).
来源:https://stackoverflow.com/questions/34250317/time-delay-between-at-commands-for-sending-sms