Python code to decode SMS PDU
Internet, I was recently working on a project that required decoding incoming SMS messages from a T39 unlocked GSM phone over bluetooth. This was non-trivial. But for you, henceforth, it shall be trivial. For more information, see this place.
Copyright (c) 2009 Eric Gradman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
import serial
import time
from cStringIO import StringIO
from math import ceil
from binascii import unhexlify, hexlify
from itertools import *
class T39(object):
def __init__(self, file="/dev/tty.T39-SerialPort1-1"):
self.file = file
self.ser = serial.Serial(file, 115200)
self.pdu = PDU()
for s in ('ATZ', 'AT+CPMS="ME","ME","ME"', 'AT+CNMI=3,3,2,0,0'):
self.ser.write("%s\r" % s)
while True:
d=self.ser.readline()
print d
if d.startswith("OK"):
break
def fetch(self):
s = self.ser.readline()
return self.pdu.decode(s)
class PDU(object):
def decode(self, s):
s = unhexlify(s)
d = StringIO(s)
# parse SMSC information
p = {}
p['smsc_len'] = d.read(1)
p['type_of_address'] = d.read(1)
p['sc_num'] = self.unsemi(d.read(ord(p['smsc_len'])-1))
p['msg_type'] = d.read(1)
p['address_len'] = d.read(1)
p['type_of_address'] = d.read(1)
p['sender_num'] = self.unsemi(d.read(int(ceil(ord(p['address_len'])/2.0))))
p['pid'] = d.read(1)
p['dcs'] = d.read(1)
p['ts'] = d.read(7)
p['udl'] = d.read(1)
p['user_data'] = d.read(ord(p['udl']))
p['user_data'] = self.decode_user_data(p['user_data'])
return p
def decode_user_data(self, s):
"""PDU user data is stored in a strange 7-bit packed format"""
bytes = map(ord, s)
strips = cycle(range(1,9))
out = ""
c = 0 # carry
clen = 0 # carry length in bits
while len(bytes):
strip = strips.next()
if strip == 8:
byte = 0
ms = 0
ls = 0
else:
byte = bytes.pop(0)
# take strip bytes off the top
ms = byte >> (8-strip)
ls = byte & (0xff >> strip)
#print "%d byte %x ms %x ls %x" % (strip, byte, ms, ls)
# append the previous
byte = ((ls << clen) | c) & 0xff
out += chr(byte)
c = ms
clen = strip % 8
if strip == 7: out += chr(ls) # changed 6/11/09 to incorporate Carl's suggestion in comments
return out
def unsemi(self, s):
"""turn PDU semi-octets into a string"""
l = list(hexlify(s))
out = ""
while len(l):
out += l.pop(1)
out += l.pop(0)
return out
Carl Audet
June 11, 2009
Thank you very much, this was really helpful, especially given how rusty was my python-fu (now I remmber why I like it so much). You should verify your def decode_user_data function though, it leaves the last characters out for strings that have a multiple of 8 as a length.
I’ve added that line before the return statement:
if strip == 7: out += chr(ls)
(ok, not that elegant, but that fixes it)
You probably are also aware that the module as it is doesn’t handle characters that don’t have a 1:1 mapping from unicode / GSM encoding ( fixed it with a simple dict lookup).
Whoever designed that PDU user data protocol deserves to be repeatedly slapped in the face…
Thanks again for sharing.
Cheers.
Pretty Trivial
August 17, 2009
Come on, that is pretty trivial. All you need is the info on the first hit from gooling “sms pdu” and it tells you how to do it. I was about to make this then I googled “python pdu sms” and you beat me to it. Thanks for saving 20 minutes!
Pretty Trivial
August 17, 2009
I wrote my own one without looking at yours in the end, my decode was pretty different too! You can’t decode properly without using message length. It will work most of the time but the 7-bit GSM encoding of default alphabet uses 0×00 for the @ symbol, plus you can use your own encodings on it too if you like which may also use 0×00. Try making a string that is 8 bytes long and making the last character \x00. Every time \x00 falls on the end of a string in an octet that is a multiple of 7 then it is lost. The only way to know it is there is to use the message length.
Mike
August 31, 2009
Hi Pretty Trivial,
Can you post your code as well ?
It will save me quite some time.
Thanks a lot!
Colm O'Shea
December 18, 2009
The following table will map GSM character codes to their latin1 equivalent:
gsm_to_latin1 = [64, 163, 36, 165, 232, 233, 249, 236, 242, 199, 10, 216, 248, 13, 197, 229, 16, 95, 32, 32, 32, 32, 32, 32, 32, 32, 32, 27, 198, 230, 223, 201, 32, 33, 34, 35, 164, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 161, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 196, 214, 209, 220, 167, 191, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 228, 246, 241, 252, 224, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 94, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 123, 125, 32, 32, 32, 32, 32, 92, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 91, 126, 93, 32, 124, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32]
Then change the following line of decode_user_data:
out += chr(byte)
to:
out += chr(gsm_to_latin1[byte])