Reading data from USB port on ESP32 using libusb-win32 filter results in 4-byte array instead of the expected message

89 Views Asked by At

I am attempting to read data from a USB port on an ESP32 device while running on Windows 11. To achieve this, I am using a libusb-win32 filter to filter the port. The ESP32 is configured to send messages in the format [time] Hello, World!.

However, when I read the data from the USB port, I am consistently getting a 4-byte array instead of the expected message. For example, the data I receive looks like this: array('B', [68, 255, 255, 168]). This array of bytes does not match the format of the message sent by the ESP32.

I would appreciate any insights into why I might be experiencing this issue and suggestions on how to properly read and interpret the messages sent by the ESP32.

Thank you!

Codes:

Esp32 code

#include <Arduino.h>

String receivedMessage = "";

void setup() {
  Serial.begin(115200);
  Serial.println("Serial USB UART");
  Serial.flush();
}

void loop() {

  // Отправляем сообщение на USB порт
  Serial.print("[");
  Serial.print(millis());
  Serial.print("] Hello, world!\n");

  // Serial.println("4");

  // Задержка в 0.5 секунды
  delay(100);

  // Считываем приходящие сообщения
  while (Serial.available() > 0) {
    char receivedChar = Serial.read();
    if (receivedChar == '\n') {
      // Приходящее сообщение завершено, обработаем его
      Serial.print("[");
      Serial.print(millis());
      Serial.print("] Received: ");
      Serial.println(receivedMessage);
      receivedMessage = ""; // Сбросим строку для следующего сообщения
    } else {
      // Добавляем символ к приходящему сообщению
      receivedMessage += receivedChar;
    }
  }
}

Pyusb code:

import usb.core
import usb.util

idVendor = 0x1a86
idProduct = 0x7523

# Найти USB-устройство по idVendor и idProduct
device = usb.core.find(idVendor=idVendor, idProduct=idProduct)

if device is None:
    raise ValueError("Устройство не найдено")

# Установить конфигурацию устройства
device.set_configuration()

# Найти интерфейс и эндпоинт для чтения
interface = 0
endpoint = 0x81  # IN endpoint

# Запуск бесконечного цикла для чтения сообщений
while True:
    try:
        # Чтение данных с эндпоинта
        data = device.read(endpoint, 64, timeout=1000)  # Читаем до 64 байт с таймаутом 1 сек
        
        # decoded_data = data.tobytes().decode('utf-8')

        # Обработка прочитанных данных
        print(f"Прочитано {len(data)} байт: {data}")

    except usb.core.USBError as e:
        if e.errno == 110:  # Timeout
            pass
        else:
            print(f"Ошибка при чтении данных: {e}")
            break
0

There are 0 best solutions below