1
\$\begingroup\$

I'm using a Telit GE864-GPS modem, which runs a dialect of Python 1.5.2. The Python module has access to the modem using a buffered UART, which may still be receiving when reading starts. The following code makes sure the entire response is read, and return either the response body or '0' on timeout.

def receiveReponse ( ):

    # MOD.secCounter() provides the current time in seconds
    timeout = MOD.secCounter() + 10

    str = ""
    length = ""
    newlinepos = 0

    while ( MOD.secCounter() < timeout ):

        newlinepos = str.find("\n\r")

        if ( (newlinepos != -1) and not length ):

            newlinepos = newlinepos + 2
            pos = str.find("Content-Length:") + 15

            while ( str[pos] != '\n' ):
                length = "%s%s" % (length, str[pos])
                pos = pos + 1

            length = int(length) + newlinepos

        else:
            MOD.sleep(5)

            # MDM receive reads the current UART buffer
            str = str + MDM.receive(1)

        if ( length and len(str) >= length ):
            return str[newlinepos:(newlinepos+length)]

    return 0

The entire procedure seems rather overcomplicated. Am I missing some obvious simplifications?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This

        while ( str[pos] != '\n' ):
            length = "%s%s" % (length, str[pos])
            pos = pos + 1

could be just

        length = string.split(str[pos:], '\n')[0]
\$\endgroup\$
2
  • \$\begingroup\$ Did string objects have a split method in 1.5.2? I think this wasn't added until 1.6. Before that you had to import string and then call string.split. \$\endgroup\$ Apr 17, 2015 at 12:53
  • \$\begingroup\$ @GarethRees You are right; edited. \$\endgroup\$ Apr 21, 2015 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.