【问题标题】:SMS sending in Python 2.6 through a data cable connection通过数据线连接在 Python 2.6 中发送 SMS
【发布时间】:2012-04-11 05:27:48
【问题描述】:

我正在使用 Python 2.6,我想在我的手机(即诺基亚 E-72)通过数据线连接到 PC 时向手机发送短信。

手机通过串口连接,代码也提示正确的端口,代码没有错误,但仍然没有发送消息。

我的代码如下:

import serial
import time
phone = serial.Serial()
phone.baudrate = 38400
phone.bytesize = 8
phone.stopbits = 1
phone.xonxoff = 0
phone.rtscts = 0
phone.timeout = 0
phone.port = 4 #try different ports here, if this doesn't work.
phone.parity=serial.PARITY_NONE
phone.open()
print phone.portstr
recipient = "+923219409998"
message = "We did it!"
try:
    time.sleep(0.5)
    phone.write(b'ATZ\r')
    time.sleep(0.5)
    phone.write(b'AT+CMGF=1\r')
    time.sleep(0.5)
    phone.write(b'AT+CMGS="' + recipient.encode() + b'"\r')
    time.sleep(0.5)
    phone.write(message.encode() + b"\r")
    time.sleep(0.5)
    phone.write(bytes([26]))
    time.sleep(0.5)
    phone.readall()
finally:
    phone.close()

【问题讨论】:

  • 请在任何人帮助您找到问题之前修复代码格式。
  • 不确定手机是否允许,顺便说一句,您确定它是串行连接吗?
  • 是的,它是一个串行连接。你能告诉我你为什么问这个吗?
  • phone.write(bytes([26])) 做了什么,为什么?另外,你确定你的\r是正确的吗?
  • phone.write(bytes([26])) 将消息写入串行端口,是的 \r 是 AT 命令的一部分,该命令将消息设置为移动 SMS 的格式。跨度>

标签: python sms serial-port


【解决方案1】:

您是否尝试将连接参数作为参数提供给Serial(),而不是稍后添加它们?正常情况下,会立即打开连接,我不确定迟到的open() 是否有效...

所以

  1. 试试类似的东西

    phone = serial.Serial(
        baudrate=38400,
        bytesize=8,
        stopbits=1,
        xonxoff=0,
        rtscts=0,
        timeout=0,
        port=4, #try different ports here, if this doesn't work.
        parity=serial.PARITY_NONE,
    )
    print phone.portstr
    

    否则将使用默认参数建立连接,这可能不是您想要的。

    如果还是不行,

  2. 尝试用真实端口设备字符串("COM5""/dev/ttyS5")更改端口号,也许

  3. 甚至解析电话的答案。为此,您应该在连接参数中定义超时和/或将读取限制为phone.inWaiting() 返回的字节数。


此外(但这只是风格问题),取决于您使用的 Python 版本,使用起来可能更整洁

import contextlib
with contextlib.closing(phone):
    <do stuff with phone>

而不是

try:
    <do stuff with phone>
finally:
    phone.close()

它在语义上完全一样,但看起来更好(恕我直言)。

【讨论】:

  • @user1325702 在哪个编号步骤之后它不起作用?其他的结果是什么?
  • 程序没有给出错误,它显示了手机连接的端口号(这是正确的)。最后手机关闭但不发送短信。
  • 很好。因此,请检查我指出的其他问题(解析或至少显示电话的答案,并检查您的行尾是否正确,正如我已经写过的那样。)
  • 我们尝试通过从串行端口读取并将所有字符连接到缓冲区中来解析手机响应,但控制台上没有任何内容。也许是因为手机没有任何响应作为响应。
猜你喜欢
  • 2010-11-29
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多