在python串行scrip中模拟enter键

2024-05-16 08:59:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Telit CC864蜂窝模块做一些简单的事情。该模块通过串行端口由AT命令控制。因此,使用minicom等调制解调器控制软件,我可以输入以下命令序列:

Input: AT
Output: OK
Input: AT#SGACT=1,1
Output: OK
Input: AT#SD=1,0,54321,"30.19.24.10",0,0,1
Output: CONNECTED
Input: AT#SSEND=1
> Hello world!
> 
Output: OK

它所做的是连接到我设置的服务器并发送一个数据包“Hello world!”。一切都在minicom工作。但是,我要做的是将其转换为python脚本。以下是我目前掌握的情况:

import serial
import time

# Modem config
modem_port = serial.Serial()
modem_port.baudrate = 115200
modem_port.port = "/dev/tty.usbserial-00002114B"
modem_port.parity = "N"
modem_port.stopbits = 1
modem_port.xonxoff = 0
modem_port.timeout = 3
modem_port.open()


def send_at_command(command):
    modem_port.write(bytes(command+"\r", encoding='ascii'))

def read_command_response():
    print(modem_port.read(100).decode('ascii').strip())
    print("\n")

if modem_port.isOpen():

    # Check network status
    send_at_command("AT+CREG=1")
    read_command_response()

    # Configure Socket
    send_at_command("AT#SCFG=1,1,0,0,1200,0")
    read_command_response()

    # Obtain IP from network
    send_at_command("AT#SGACT=1,1")
    read_command_response()

    # Connect to AWS server
    send_at_command("AT#SD=1,0,54321,\"30.19.24.10\",0,0,1")
    read_command_response()

    # Send packet to AWS server
    send_at_command("AT#SSEND=1")
    read_command_response()

    send_at_command("This is sent from Python Script.")
    read_command_response()

modem_port.close()

但是,此脚本无法发送数据包。我想原因是因为在minicom中,我必须在Hello world之后按enter!以便发送数据包。我不知道如何在python脚本中模拟它。如有任何建议,将不胜感激。

编辑:

所以我读了更多的模块文档,看起来我需要做的是通过串行端口发送Ctrl-Z char(0x1A hex)。你知道我用python怎么做吗?


Tags: 模块sendhelloworldreadinputoutputport