Correct way to send AT commands to Telit 862GPS using Python

Hey Everyone,

Quick question really, I can send AT commands to the Telit 862GPS via Python no problems. I’m just starting out though and I want to code it robustly. I can’t find a good example online, here’s my attempt:

# Setup Booleans!
True, False = 1, 0

def at_command(command, win="OK", fail="ERROR", delay=10):
  # Send the command
  MDM.send(command + '\r', 5)
  # Wait for the response
  for i in range(delay):
    # Listen to serial port for click
    res = MDM.receive(1)
    # See what happened
    if res.find(win) > -1:
      return False, res
    if res.find(fail) > -1:
      return True, res
  # Timed out :(
  return True, "Timed out"

What do you think?

Cheers, Dave.

Hi Dave,

Looks like you need to leave a little extra time to receive the response. Here is what I usually do:

MDM.send('AT#GPRS?\r', 0)
res = MDM.receive(25)
MOD.sleep(1)

Let me know if it helps!

James

Should the sleep not be between the send and the receive?

If you are using a fixed sleep between all sends and receives to pace the communication flow, you can greatly slow things down if you have lots of calls to make. I find that in many cases a busy loop works well. It will sit and wait for num bytes till such time as the timeout period has elapsed (where it returns null). Something like this:

# Get num bytes from port with a timeout. Return null if no bytes 
def getLine(port, num, timeout):
	"""Doc String
	"""
	j = 0
	s = ""

	while 1:

		if (port.inWaiting() >= num):

			# Get the bytes
			s = port.read(num)

		else:
			time.sleep(0.01)
			j = j+0.01
			if (j > timeout):
				break

	return s

I’ve been playing with the Telit for a while now, here’s my final AT sending function that has so far done everything I needed:

#
# Performs AT command, returning result or False
#
def at_command(command, delay=20, win="OK", fail="ERROR"):
  # Send the command
  MDM.send(command + '\r', 5)
  # Create a buffer
  buffer = ''
  # Wait for the response
  for i in range(delay):
    # Listen to serial port for click
    buffer = buffer + MDM.receive(1)
    # See what happened
    if buffer.find(win) > -1:
      return buffer
    if buffer.find(fail) > -1:
      return False
  # Timed out :(
  return False

Cheers, Dave.