theUkrainian
theUkrainian

Reputation: 1

The COM port is connected with pySerial but doesn't return data

I'm trying to use the pySerial library to access an FPV controller through the COM port. I have this code:

port = '/dev/cu.usbmodem0x80000001'
baudrate = 115200

import serial
import time

def read_vtxtable():
    try:
        ser = serial.Serial(port, baudrate, timeout=5, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
        time.sleep(2)
    except serial.SerialException as e:
        print(f"Cant open this port {port}: {e}")
        return []

    # Trying to initialize process and make controller alive
    ser.write('status\n'.encode())
    time.sleep(0.05)

    # Asking controller about vtx data
    ser.write('vtxtable\n'.encode())
    time.sleep(0.05)

    response = ""
    start_time = time.time()
    while time.time() - start_time < 5:
        if ser.in_waiting > 0:
            response += ser.read(ser.in_waiting).decode()
        time.sleep(0.05)

    ser.close()
    return response

vtxtable_data = read_vtxtable()

print(vtxtable_data)

When I try this code, the connection appears to be successful, but when I request some data, the response is empty.

Interestingly, after I run some commands in the BetaFlight CLI, and disconnect to release port access, my own code starts working. However, if I unplug the USB and plug it back in again, the code stops working again.

Could it be that the code fails to "wake up" the controller, such that it ignores the commands? It seems like the BetaFlight CLI is able to do this, if so.

How can I get a non-empty response from the connection?

This is the response I get when I run the code, BEFORE I run BetaFlight and run some commands there:

This is the response I get when I run the code AFTER I run betaflight and run some command there:

UPDATED Below I have given the main idea of ​​what I changed in the code

Code

....
cli_prompt = "Entering CLI Mode, type 'exit' to return, or 'help'"
timeout_time = time.time() + timeout
while time.time() < timeout_time:
    write('#')

    if ser.in_waiting > 0:
        buffer += ser.read(ser.in_waiting).decode()
        if cli_prompt in buffer:
            print("# Found wakeup phrase:", cli_prompt)
            return True
        else:
            print("# No response..")

            write('status')
            time.sleep(0.1)

            output = get_info()
            if len(output) > 0:
                print("# The board is alive")
                override_wakeup_detection = True
                return True
            else:
                write('#')

    time.sleep(0.1)

Output.

% python3 get_data.py
# Using first usbmodem found: /dev/cu.usbmodem0x80000001
# No response..
# No response..
# No response..
# The board is alive
[
'vtxtable',
 'vtxtable bands 8',
 'vtxtable channels 8',
 'vtxtable ...
]

Upvotes: 0

Views: 71

Answers (0)

Related Questions