Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

python - How to Send/Receive SMS using AT commands?

Can anyone help me to send and receive SMS using AT commands in Python?

In case it matters, I'm using Fedora 8.

Which phone will be better with Linux (Nokia, Sony Ericson, Samsung,.....)? Will all phones support sending and receiving SMS using AT commands?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's some example code that should get you started (in Python 3000):

import time
import serial

recipient = "+1234567890"
message = "Hello, World!"

phone = serial.Serial("/dev/ttyACM0",  460800, timeout=5)
try:
    time.sleep(0.5)
    phone.write(b'ATZ
')
    time.sleep(0.5)
    phone.write(b'AT+CMGF=1
')
    time.sleep(0.5)
    phone.write(b'AT+CMGS="' + recipient.encode() + b'"
')
    time.sleep(0.5)
    phone.write(message.encode() + b"
")
    time.sleep(0.5)
    phone.write(bytes([26]))
    time.sleep(0.5)
finally:
    phone.close()

You need to do two additional things:

  • Encode the message in the appropriate format (mostly GSM 03.38, there's a handy translation table at unicode.org). If you really don't care about any characters other than ASCII, you can just check if every character is in string.printable.

  • Check the length of the message (I'm not sure if it's to do with the encoding, but it's sometimes 140 characters, sometimes 160).

You can use phone.readall() to check for errors, but it's best to make sure your message is OK before you send it off to the phone. Note also that the sleeps seem to be necessary.

Most phones will understand this. In order to get my old Nokia C5 to open up the serial connection, I had to select "PC Suite" from the menu that pops up when you insert the USB cable. This should work equally well over Bluetooth.

The code uses the PySerial package, available for python 2 and 3.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...