yz10
yz10

Reputation: 731

Simulate enter key in python serial script

I'm currently trying to do something simple with a Telit CC864 Cellular module. The module is controlled with AT-Commands through serial ports. So with a modem control software such as minicom, I can input the following sequence of commands:

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

What this does is it connects to a server I have set up and sends a packet "Hello world!". Everything is working in minicom. However, what I am trying to do is convert this to a python script. Here's what I have so far:

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()

However, this script fails to send the packet. I'm thinking that the reason is because in minicom, I have to press enter after Hello world! in order to send the packet. I'm at a loss at how to simulate this in the python script. Any suggestions would be much appreciated.

EDIT:

So I was reading the module documentation some more, and it seems that what I need to do is send Ctrl-Z char (0x1A hex) through the serial port. Do you know how I would do this in python?

Upvotes: 1

Views: 10738

Answers (1)

Steve Barnes
Steve Barnes

Reputation: 28405

Note that the documentation indicated that the execute command was ctrl-z so this answer has been edited to remove references to \n and \r

EDIT:

Based on your comments, try

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

Upvotes: 2

Related Questions