/// <summary> /// 获取所有Sim卡中的短信 /// </summary> public void ReceiveAllMessage() { _theSerialPort.SendString("AT+CMGL=4\r"); string theResponse; try { theResponse = _theSerialPort.ReadTo("OK", 20000); } catch (TimeoutException) { ReceivedFailedHandler(); return; } //一条一条解析短信 var readReg = new Regex("(?:CMGL: (?<index>\\d+),\\d+,,\\d+\r\n(?<sms>\\S+)\r\n)"); MatchCollection allMaches = readReg.Matches(theResponse); int successCount = 0; foreach (Match m in allMaches) { int id; string senderNumber; string content; DateTime senderTime; if (!int.TryParse(m.Groups["index"].Value, out id)) { continue; } if (!PduDecoding.DecodingMsg(m.Groups["sms"].Value, out senderNumber, out content, out senderTime)) { DecodingSmsFailHandler(m.Groups["index"].Value, m.Groups["sms"].Value); continue; } var theMessage = new ReceiveMessagesEntity { Id = id, TheNumber = senderNumber, Content = content, ReceivedTime = senderTime, BoradCasted = 0 }; successCount++; //删除Sim卡里面的信息 _theSerialPort.SendString("AT+CMGD=" + theMessage.Id + "\r"); try { _theSerialPort.ReadTo("OK", 10000); theMessage.IsCleanMessage = 1; } catch (TimeoutException) { DeleteMessageFailedHandler(theMessage); } finally { theMessage.TheNumber = theMessage.TheNumber.Replace("+86", ""); ReceiveMessagesBll.Insert(theMessage); } } }
public void ReceiveAllMessage() { //_TheSerialPort.ReadExisting(); //获取所有Sim卡中的短信 _TheSerialPort.SendString("AT+CMGL=4\r"); string theResponse; try { theResponse = _TheSerialPort.ReadTo("OK", 20000); } catch (TimeoutException) { ReceivedFailedHandler(); return; } //一条一条解析短信 Regex readReg = new Regex("(?:CMGL: (?<index>\\d+),\\d+,,\\d+\r\n(?<sms>\\S+)\r\n)"); MatchCollection allMaches = readReg.Matches(theResponse); int successCount = 0; foreach (Match m in allMaches) { int id; string senderNumber; string content; DateTime senderTime; if (!int.TryParse(m.Groups["index"].Value, out id)) { continue; } if (!PduDecoding.DecodingMsg(m.Groups["sms"].Value, out senderNumber, out content, out senderTime)) { DecodingSmsFailHandler(m.Groups["index"].Value, m.Groups["sms"].Value); continue; } ReceiveMessageDataModel theMessage = new ReceiveMessageDataModel(id, senderNumber, content, senderTime); successCount++; //删除Sim卡里面的信息 //AT+CMGL="ALL" _TheSerialPort.SendString("AT+CMGD=" + theMessage.Id + "\r"); try { _TheSerialPort.ReadTo("OK", 10000); theMessage.IsCleanMessage = true; } catch (TimeoutException) { DeleteMessageFailedHandler(theMessage); } finally { theMessage.MoveNumber86(); ObjectSource.GetMessageBox.EnqueueReceiveMessage(theMessage); } } //若是收到信息,引发异步事件 if (successCount > 0 && ReceivedMessage != null) { ReceivedMessage.BeginInvoke(this, new EventArgs(), null, null); } }