using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
namespace SYGSM
{
class GsmClass
{
/// <summary>
/// GetMessage函数用于读取SIM卡中的短信
/// </summary>
/// <param name="wz">短信位置</param>
public static string[] GetMessage(string comn,int wz,bool delyn)
{
//定义短信端口操作类
SerialPort serialPort = new SerialPort("COM" + comn.ToString(), 9600, Parity.None, 8, StopBits.One);
serialPort.WriteTimeout = 2000;
try
{
//设置读缓冲区大小
serialPort.ReadBufferSize = 900000;
if (serialPort.IsOpen == false)
serialPort.Open();
//向串口发出命令,清空以前的操作
serialPort.WriteLine("ATZ/r");
//延时1秒等待,串口操作完成
Thread.Sleep(1000);
//发出读取指定位置的短信的命令
serialPort.ReadExisting();
serialPort.WriteLine("AT+CMGR=" + wz.ToString() + "/r");
//延时1秒等待,串口操作完成
Thread.Sleep(2000);
//取得返回值(包含短信内容的字符串)
string x3 = serialPort.ReadExisting();
//向串口发出命令,删除已经被读取的短信
if (delyn)
{
//延时2秒等待,串口操作完成
Thread.Sleep(200);
serialPort.WriteLine("AT+CMGD=" + wz.ToString() + "/r/n");
}
Thread.Sleep(200);
//关闭端口
serialPort.Close();
//分析字符串,得到短信内容中的需要的数据
string[] tmps = x3.Split('/n');
string mess = "";
for (int j = 3; j < tmps.Length -3 ; j++)
{
mess +=(mess==""?"":"/n/r")+tmps[j];
}
//tmps[2]短信信息
tmps[2] = tmps[2].Substring(tmps[2].IndexOf(':') + 1).Trim();
string[] dxxxlist = GetSplitEx(tmps[2], ',', '"');
if (dxxxlist.Length < 4) return new string[3] { "", "", "" };
List<string> ls = new List<string>();
ls.Add(dxxxlist[1]);
ls.Add(dxxxlist[3]);
ls.Add(mess);
return ls.ToArray();
}
catch (Exception e1)
{
Console.WriteLine(e1.Message);
return new string[3]{"","",""};
}
finally
{
//保证操作完成以后关闭端口,避免占用
if (serialPort.IsOpen)
serialPort.Close();
}
}
public static string[] GetSplitEx(string str,char splitchar,char signchar)
{
List<string> ls = new List<string>();
if (str==null||str.Length==0) return new string[1]{""};
while (true)
{
int startwz = 0; //开始找找分隔符位置
bool splityn = false;//是否找到分隔符
bool signyn = false; //是否以格式符开始
int wz = 0;//分隔符位置
string dxxx = "";//本次内容
signyn = (str.IndexOf(signchar)==0);//是否以格式符开始
startwz = (signyn ? (str.IndexOf(signchar, 1) < 0 ? 0 : str.IndexOf(signchar, 1)) : 0);
splityn = (str.IndexOf(splitchar, startwz) >= 0);
wz = (splityn?str.IndexOf(splitchar, startwz):str.Length);
dxxx = str.Substring(0, wz);
ls.Add(((signyn && dxxx[dxxx.Length - 1] == signchar) ? dxxx.Substring(1, dxxx.Length - 2) : dxxx));
//Console.WriteLine(ls[ls.Count - 1]);
if (!splityn) break;
str = str.Substring(wz + 1);
}
return ls.ToArray();
}
static void Main(string[] args)
{
//
string[] mess = GsmClass.GetMessage("3", 1, false);
Console.WriteLine("发 送 者:" + mess[0]);
Console.WriteLine("发送时间:" + mess[1]);
Console.WriteLine("短信内容:" + mess[2]);
Console.ReadLine();
}
}
}