1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Coding the wait function from Teraterm in Python

Discussão em 'Python' iniciado por Stack, Setembro 23, 2024.

  1. Stack

    Stack Membro Participativo

    I am working on a project where I want to port some Teraterm scripts into Python. I got something working but it is not really matching what I want: read each lines on the UART until either a timeout occurs or a string, within a defined list, is identified. To be more precise, I would like to port something like the following into python: sendln 'ATI9' wait "OK" "+CME ERROR" (Note that the response from the modem contains several lines that end with an "OK")

    In python I have implemented the following 2 options but I am not really happy with the result: using either a time.sleep or ser.timeout and read_until from pyserial :

    Send AT Command


    def send_at_command(ser, command, timeout): print(f'Sending: {command}') ser.write((command + '\r\n').encode('utf-8')) time.sleep(timeout) # Wait for the response response = ser.read_all().decode('utf-8') print(f'Response: {response}') return response

    same as before with timeout managed by pyserial instead of a sleep


    def send_at_command2(ser, command, timeout): try: `` print(f'Sending: {command}') `` ser.timeout = timeout # Wait for the response `` ser.write((command + '\r\n').encode('utf-8')) `` ser.reset_output_buffer() `` response = ser.read_until('\r').decode('utf-8') `` print(f'Response: {response}') `` #ser.reset_input_buffer() except Exception as e: `` print(f'No response to {command} : {str(e)}') `` print(f'Response {response} : {ser.read_all()}') `` ser.close() `` otii.shutdown() `` connection.close_connection() `` server.terminate() `` sys.exit() return response

    Validate Response


    def validate_response(response, expected_keywords): if any(keyword in response for keyword in expected_keywords): `` #print('Test passed.') `` return True else: `` #print('Test failed.') `` return False

    Test AT command Response


    def Wait_At_Command_Response(ser, command, timeout, expected_keywords): response = send_at_command2(ser,command, timeout) #response = send_at_command(ser,command, timeout) return validate_response(response, expected_keywords)

    Then I call the following in my main function: Wait_At_Command_Response(ser,'ATI9',2,['+CME ERROR', 'OK'])

    Those 2 options seem to take a very long time to process the response from the AT command. Moreover I often get messages such as "'utf-8' codec can't decode byte 0xXX in position 0: invalid start byte"

    Thanks

    See description for details

    Continue reading...

Compartilhe esta Página