如何在 C# 中解析来自 GSM 调制解调器的短信

How to parse SMS from GSM modem in c#

我正在创建 Messenger 网络应用程序。已经做了消息发送方法。我的消息接收方法适用于 SerialDataReceivedEventHandler
我的代码:

 public class InnerComPortSettings
{
    public static SerialPort SerialPort;

    public static void OpenPort()
    {
        SerialPort = new SerialPort("COM3", 115200)
        {
            Parity = Parity.None,
            DataBits = 8,
            StopBits = StopBits.One,
            Handshake = Handshake.None,
            DtrEnable = true,
            RtsEnable = true
        };

        //Thread.Sleep(1000);
        SerialPort.Open();
    }
}

private string _messageString;

    public Task ReceiveSms()
    {
        return Task.Run(() =>
        {
            InnerComPortSettings.SerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            InnerComPortSettings.SerialPort.WriteLine("AT+CMGF?\r");

            Thread.Sleep(5000);
            InnerComPortSettings.SerialPort.WriteLine("AT+CNMI=1,2,0,0,0\r");
            Thread.Sleep(1000);
            InnerComPortSettings.SerialPort.WriteLine("AT+CMGF=0\r");
            Thread.Sleep(1000);

        });

    }

    public void DataReceivedHandler(
        object sender,
        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;         

        _messageString = sp.ReadLine();

        GetPdu();
    }
    }

所以我想要的是仅解析 SMS 信息和消息,然后将其存储到数据库中。

//Response after start
    AT+CMGF=1
    OK
    AT+CNMI=1,2,0,0,0
    OK

//Response after getting message
    +CMT: "+xxxxxxxxxx",,"18/05/30,10:08:08+18"
    Testing

排除第一部分并将第二部分分成两部分的最佳方法是什么?

至于更好的解析,我切换到从调制解调器获取 PDU,使用正则表达式检查 PDU,然后将 PDU 解析成多个部分。
已将 CMGF 更改为 0

AT+CMGF=0
OK
AT+CNMI=1,2,0,0,0
OK

正在检查 PDU 的串口响应

 public void GetPdu()
    {
        Console.WriteLine(_messageString);

        Regex regex = new Regex("^([0-9A-F]+\r)$");
        Match match = regex.Match(_messageString);
        if (match.Success)
        {
            Console.WriteLine("Match: " + match.Value);
            string messagePdu = match.Value;
            ParseMessage(messagePdu);
        }
    }

解码方法 这个方法我用的是这个Source

ublic void ParseMessage(string messagePdu)
    {
        SMSType smsType = SmsBase.GetSMSType(messagePdu);
        switch (smsType)
        {
            case SMSType.SMS:
                Sms sms = new Sms();
                Sms.Fetch(sms, ref messagePdu);

                string messageBody = sms.Message;
                string phoneNumber = sms.PhoneNumber;
                DateTime messageDateTime = DateTime.Parse(sms.ServiceCenterTimeStamp.ToString());
                string state = "Received";
                SaveMessage(messageBody, phoneNumber, messageDateTime, state);

                break;
            case SMSType.StatusReport:
                SmsStatusReport statusReport = new SmsStatusReport();
                SmsStatusReport.Fetch(statusReport, ref messagePdu);
                break;
        }          
    }