如何使用 AT 命令发送/接收短信? [英] How to Send/Receive SMS using AT commands?

查看:45
本文介绍了如何使用 AT 命令发送/接收短信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能帮我在 Python 中使用 AT 命令发送和接收短信?

以防万一,我使用的是 Fedora 8.

哪种手机更适合使用 Linux(诺基亚、索尼爱立信、三星……)?是否所有手机都支持使用 AT 命令发送和接收短信?

解决方案

以下是一些示例代码,可以帮助您入门(在 Python 3000 中):

导入时间导入序列收件人 = "+1234567890"message = "你好,世界!"phone = serial.Serial("/dev/ttyACM0", 460800, timeout=5)尝试:时间.睡眠(0.5)phone.write(b'ATZ
')时间.睡眠(0.5)phone.write(b'AT+CMGF=1
')时间.睡眠(0.5)phone.write(b'AT+CMGS="' + receiver.encode() + b'"
')时间.睡眠(0.5)phone.write(message.encode() + b"
")时间.睡眠(0.5)电话.写(字节([26]))时间.睡眠(0.5)最后:电话.关闭()

您还需要做两件事:

  • 以适当的格式对消息进行编码(主要是GSM 03.38,还有unicode.org 上的一个方便的翻译表).如果你真的不关心 ASCII 以外的任何字符,你可以检查每个字符是否在 string.printable 中.

  • 检查消息的长度(我不确定是否与编码有关,但有时是 140 个字符,有时是 160 个字符).

您可以使用 phone.readall() 来检查错误,但最好在将消息发送到手机之前确保消息正常.另请注意,睡眠似乎是必要的.

大多数手机都会理解这一点.为了让我的旧诺基亚 C5 打开串行连接,我必须从插入 USB 电缆时弹出的菜单中选择PC 套件".这应该同样适用于蓝牙.

代码使用 PySerial 包,可用于 python 2 和 3.>

另见:

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?

解决方案

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:

这篇关于如何使用 AT 命令发送/接收短信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆