Successfully send sms with python

Michael Torrie torriem at gmail.com
Wed Sep 23 06:25:31 CEST 2015


On 09/22/2015 05:19 AM, Timon Rhynix wrote:
> When run it, the "message sent!" is printed but no message is sent/delivered.
> Please assist on what I am missing. Thank you

Is this "message sent!" from your code or is it a message you get back
on the serial port from the gsm modem? Oh nevermind I see that it comes
from your own code.

Just an observation, but your code looks quite Java-like. Seems to me
that wrapping this up in a class is not necessary, since the goal is to
provide an interface to send a text message, I'd just use a plain
function, stored in its own module so it can also store things like the
name of the serial port, timeout values, etc. There's no need to make
the caller save any state.

Consider something like this with no error checking when using the
serial port, no context managers for the serial device:
file sms.py:
----------------------
import serial
import time

serial_port = 'COM13'
timeout = 5
baud = 460800

def send_message(recipient, message):
    ser = serial.Serial(serial_port, baud, timeout=timeout)
    time.sleep(1)
    self.ser.write('ATZ\r')
    time.sleep(1)
    self.ser.write('AT+CMGF=1\r')
    time.sleep(1)
    self.ser.write('''AT+CMGS="''' + self.recipient + '''"\r\n''')
    time.sleep(1)
    self.ser.write(self.content + "\r\n")
    time.sleep(1)
    self.ser.write(chr(26))
    time.sleep(1)
    print "message sent!"

    ser.close()
------------------------

Someone can just do:

import sms
sms.serial_port = "/dev/ttyUSB2"
sms.send_message("5555555","Hi there")

Call it good.  Unlike Java, Python does not require everything to be
wrapped up in a class.  Particularly if what you really want is a
singleton.  In many respects you can treat a python module (a python
file) as a singleton.  You can use its namespace to store some state or
basic config information, and define the functions you want others to
use.  Private helper functions can start with an underscore, telling
others not to use them.



More information about the Python-list mailing list