Sunday, June 21, 2009

Encoding & Decoding SMS Format for Nokia 6235 CDMA device

There is little informations about how to send SMS on CDMA device. Finally, I found AT Command document on Nokiad 6325 CDMA mobile phone. So I made small python scripts for encoding and decoding sms format based on the AT Document. Here is the scripts:

import sys
import os


def intToHex(i):
"""docstring for intToHex"""
return hex(i).replace('x','').upper()
def strToHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0'+hv
lst.append(hv)

return reduce(lambda x,y:x+y, lst)

#convert hex repr to string
def hexToStr(s):
return s and chr(atoi(s[:2], base=16)) + toStr(s[2:]) or ''


def hexStrToInt(s1,s2):
"""docstring for hextToInt"""
return int('0x%s%s' % (s1,s2),16)

#encode into sms format for nokia 6235
#Use this function with sending sms (AT+CMGS)
#input:
# - msisdn = destination mobile #
# - sms = message
def sms_encode_nokia_cdma(msisdn,sms):

len_msisdn=len(msisdn)
len_sms=len(sms)

hex_len_msisdn=intToHex(len_msisdn)
hex_len_sms=intToHex(len_sms)
format_hex = []
print 'len',hex_len_msisdn,hex_len_sms
format_hex.append(hex_len_msisdn)
for i in msisdn:
format_hex.append(strToHex(i))
format_hex.append('02')
format_hex.append(hex_len_sms)
for i in sms:
format_hex.append(strToHex(i))
print format_hex

return ''.join(format_hex)

#decode into sms format for nokia 6235
#Use this function with reading sms (AT+CMGL)
# output: dictionary
# - msisdn = source mobile phone #
# - timestamp = timestamp format: yymmddhhiiss
# - msg = message
def sms_decode_nokia_cdma(s):
"""docstring for decode_sms"""
s=s.replace('\t','').replace('\n','').strip()
print 'start decoding:%s' % s
if not s:
return None
sms={}
j=0
send_num_len=hexStrToInt(s[j],s[j+1])
#print 'sender_num_len',send_num_len
j=j+2
i=0
msisdn_a=[]
while i
#print 'i:',i,j,'=',s[j]
msisdn_a.append(s[j])
j=j+1
i=i+1
#print 'msisdn',''.join(msisdn_a)
sms['msisdn']=''.join(msisdn_a)
i=0
timestamp_a=[]
while i<6:
#print 't:',i,j,'=',s[j],s[j+1]
timestamp_a.append(s[j])
timestamp_a.append(s[j+1])
j=j+2
i=i+1
#print 'timestamp:',''.join(timestamp_a)
sms['timestamp']=''.join(timestamp_a)
print 'encoding:',s[j],s[j+1]
j=j+2
#print 'data len1:',s[j],s[j+1],'=',hexStrToInt(s[j],s[j+1])
len_data1=hexStrToInt(s[j],s[j+1])
j=j+2
#print 'data len2:',s[j],s[j+1],'=',hexStrToInt(s[j],s[j+1])
len_data2=hexStrToInt(s[j],s[j+1])
j=j+2
len_data=int('%s%s' % (len_data1,len_data2))
print 'len data:',len_data
d=s[j:len(s)]
# i=0
# print 'start parsing data:',j,s[j]
# while i
# print 'adding:',s[j]
# d.append(s[j])
# j=j+1
# i=i+1
#print 'data:',''.join(d)
sms['msg']=''.join(d)
#print sms
return sms



1 comment: