手机短信的发送主要借助于VB的Mscomm控件实现,关于Mscomm控件,前面的技术介绍部分有详细介绍。短信的发送是由AT+CMGS指令完成的,采用PDU模式发送,函数代码如下:
Const prex = "0891"
Const midx = "11000D91"
Const sufx = "000800"
Public Function Sendsms(csca As String, num As String, msg As String) As _Boolean
Dim pdu, psmsc, pnum, pmsg As String
Dim leng As String
Dim length As Integer
length = Len(msg)
length = 2 * length
leng = Hex(length)
If length < 16 Then leng = "0" & leng
psmsc = Trim(telc(csca))
pnum = Trim(telc(num))
pmsg = Trim(ascg(msg))
pdu = prex & psmsc & midx & pnum & sufx & leng & pmsg
sleep(1)
mobcomm.Output = "AT+CMGF=0" + vbCr
mobcomm.Output = "AT+CMGS=" & Str(15 + length) + vbCr
mobcomm.Output = pdu & Chr$(26)
sleep(1)
Sendsms = True
End Function
因为手机同一时间只能处理一件事情,因此这个函数只负责发送短信,关于短信发送成功与否以及阅读短信的部分集中在一起处理。判断手机短信发送成功与否主要由AT+CMGS命令执行以后的返回码来决定(可参见前文的AT指令介绍部分)。
为了防止手机因过于繁忙而出错,这里采取了一定的方法让手机有充分的时间处理发送和接收及删除等操作。Sleep()函数正是为此而设计的,在发送及删除操作后都会让程序暂停一秒,这样就不至于使得手机过于繁忙。
Unicode码解码函数
相比于手机短信的发送而言,手机短信的接收主要的工作正好与之相反。手机短信的发送需要将待发送的短信内容转换为Unicode码,而短信的接收则需要将接收到的Unicode码转换成中文字符。下面的函数将实现解码功能。同手机短信发送的编码函数一样,这里也应用了一个VB内置的函数AscW()函数来将Unicode码转换为中文:
Public Function ascg(smsg As String) As String
Dim si, sb As Integer
Dim stmp As Integer
Dim stemp As String
sb = Len(smsg)
ascg = ""
For si = 1 To sb
stmp = AscW(Mid(smsg, si, 1))
If Abs(stmp) < 127 Then
stemp = "00" & Hex(stmp)
Else
stemp = Hex(stmp)
End If
ascg = ascg & stemp
Next si
ascg = Trim(ascg)
End Function
2 手机短信接收函数
相对于短信的发送函数而言,短信的接收相当简单,只需要以下的三行代码就完成了。但是它使用的技术却决不比短信的发送少,这里主要用到了Mscomm控件的Output属性和AT+CMGR指令。
Public Sub readsms(rnum As String)
mobcomm.Output = "AT+CMGF=1" + vbCr
mobcomm.Output = "AT+CMGR=" & rnum + vbCr
End Sub