程序中的sp是SerialPort类型的对象,在System.IO.Ports命名空间下
//手机号码转换为pdu模式
private string telc(string MobileNum)
{
int tl;
string ltem, rtem, ttem;
int ti;
ttem = "";
tl = MobileNum.Trim().Length;
if (tl != 11 && tl != 13)
{
MessageBox.Show("wrong number:" + MobileNum);
return "";
}
if (tl == 11) // 11位转换为13位
{
tl += 2;
MobileNum = "86" + MobileNum;
}
for (ti = 0; ti < tl; ti += 2)
{
ltem = MobileNum.Substring(ti, 1);
if (ti == tl - 1)
{
rtem = "F";
}
else
{
rtem = MobileNum.Substring(ti + 1, 1);
}
ttem += rtem + ltem; //每两位颠倒
}
return ttem;
}
//Unicode解码函数
private string ascg(string smsg)
{
string res="";
string ls;
string rs;
byte[] resByte = System.Text.UnicodeEncoding.Unicode.GetBytes(smsg);
for (int i = 0; i < resByte.Length ; i+=2)
{
ls = resByte[i].ToString("X2");
rs = resByte[i + 1].ToString("X2");
res = res + rs + ls; //注意这里高低位颠倒
}
return res.Trim();
}
private void SendSMS(string csca,string num, string msg)
{
string prex = "0891";
string midx = "11000D91";
string sufx = "000800";
string pdu, psmsc, pnum, pmsg;
string leng;
int length;
if (!sp.IsOpen)
{
sp.Open();
}
length = (msg.Length) * 2;
leng = length.ToString("X");
if (length < 16)
{
leng = "0" + leng;
}
psmsc = telc(csca).Trim();
pnum = telc(num).Trim();
pmsg = ascg(msg.Trim());
pdu = prex + psmsc + midx + pnum + sufx + leng + pmsg;//注意编码组合方式
sp.WriteLine("AT+CMGF=0/r");
sp.WriteLine("AT+CMGS=" + (15 + length).ToString() + "/r");
byte[] end = { 0x1a };
sp.WriteLine(pdu + System.Text.ASCIIEncoding.ASCII.GetString(end));
}