/// <summary> /// 以文本模式发送发送短信 /// </summary> /// <param name="mobileNum">发送的短信目标号码</param> /// <param name="msg">短信内容文本</param> /// <param name="encoding">短信编码方式</param> /// <returns></returns> public void SendTextMessage(string mobileNum, string msg, Encoding encoding) { lock (mt) { free = 0; ClearBuffer(); string instruction = string.Format("AT^HCMGS=\"{0}\"\r", mobileNum); SendCmd(instruction); Thread.Sleep(200); string line = SerialPort.ReadExisting(); UnsolicitedDeal(line); if (RegexPrompt.Match(line).Success) { Log("收\t" + line.Replace("\r\n", "")); msg += "\u001A"; byte[] data = encoding.GetBytes(msg); SerialPort.Write(data, 0, data.Length); Log("发\t" + msg); for (int i = 0; i < 20; i++) { string str = ReadLine(); if (RegexOK.Match(str).Success) { break; } else { UnsolicitedDeal(str); } } } else { Log("收\t" + line); SerialPort.Write("\u001B"); if (RegexOK.Match(line).Success || regexMessageSendFailed.Match(line).Success || RegexError1.Match(line).Success) { throw new ModemErrorException(instruction + " 执行错误"); } Match match = RegexError2.Match(line); if (match.Success) { throw new ModemErrorException(match.Result("${errinfo}"), instruction + " 执行错误"); } return; } } }
/// <summary> /// 读取短信 /// </summary> /// <param name="index">短信所在存储空间的索引</param> /// <returns>读取的短信</returns> public Message ReadTextMessage(int index) { lock (mt) { free = 0; ClearBuffer(); string instruction = string.Format("AT^HCMGR={0}\r", index); SendCmd(instruction); Regex regex = new Regex("^\\^HCMGR:\\s*(?<callerID>\\d+),(?<year>\\d+),(?<month>\\d+),(?<day>\\d+)," + "(?<hour>\\d+),(?<minute>\\d+),(?<second>\\d+),(?<lang>\\d+),(?<format>\\d+),(?<length>\\d+)," + "(?<prt>\\d+),(?<prv>\\d+),(?<type>\\d+),(?<stat>\\d+)"); Match match; string line; for (; ;) { line = ReadLine(); if (RegexError1.Match(line).Success) { throw new ModemErrorException(instruction + " 执行错误"); } if ((match = RegexError2.Match(line)).Success) { throw new ModemErrorException(match.Result("${errinfo}"), instruction + " 执行错误"); } if ((match = regex.Match(line)).Success) { break; } else { UnsolicitedDeal(line); } } if ((MessageFormat)int.Parse(match.Result("${format}")) == MessageFormat.UNICODE) { SerialPort.Encoding = Encoding.BigEndianUnicode; line = SerialPort.ReadTo("\u001A"); SerialPort.Encoding = Encoding.ASCII; } else { line = SerialPort.ReadTo("\u001A"); } Log("收\t" + line); for (; ;) { string str = ReadLine(); if (RegexOK.Match(str).Success) { break; } else { UnsolicitedDeal(str); } } return(new Message(index, (MessageState)int.Parse(match.Result("${stat}")), match.Result("${callerID}"), string.Format("{0},{1},{2},{3},{4},{5}", match.Result("${year}"), match.Result("${month}"), match.Result("${day}"), match.Result("${hour}"), match.Result("${minute}"), match.Result("${second}")), line)); } }