T-vK / ESP32-BLE-Keyboard

Bluetooth LE Keyboard library for the ESP32 (Arduino IDE compatible)
2.27k stars 378 forks source link

up to 10 Sec delays... #296

Open baerrs opened 2 months ago

baerrs commented 2 months ago

I'm trying to get this to work with OMOTE Remote Control.
I've simplified the code and duplicated this timing issue to help troubleshoot.
The code does work, but the latency makes it unfunctional.

Issue: When I receive an MQTT message, I get (up to) a 10-second delay on the OnMessage execution. If I remove the BleKeyboard, the latency is not noticeable. I understand that I have a lot of Serial.print commands; they are just there to help me see what's going on.

I'm currently using PlatformIO, ESP32S3 (M5StampS3) Enabling NimBLE has yet to improve performance.

#include <WiFi.h>
#include <AsyncMqttClient.h>
#include <BleKeyboard.h>  //*****When removed, latency is minimal

BleKeyboard bleKeyboard;  //*****When removed, latency is minimal.

const char *ssid = "MY_SSID"; // Enter your Wi-Fi name
const char *password = "MY_PASWORD";  // Enter Wi-Fi password
const char *mqtt_broker = "192.168.1.110";
const char *topic = "esp32_keyboard_firetv/cmnd/SELECT";
const int mqtt_port = 1883;

WiFiClient espClient;
AsyncMqttClient mqttClient;

WiFiClient wifiConnectHandler;
WiFiClient wifiDisconnectHandler;

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
  uint16_t packetIdSub = mqttClient.subscribe("esp32_keyboard_firetv/cmnd/SELECT", 2);
  Serial.print("Subscribing at QoS 2, packetId: ");
  Serial.println(packetIdSub);
}

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  Serial.println("Publish received.");
  Serial.print("  topic: ");
  Serial.println(topic);
  bleKeyboard.write(KEY_MEDIA_PLAY_PAUSE);
}

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("===============Starting Project!====================");
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(ssid, password);
  WiFi.waitForConnectResult();
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  Serial.println("Connecting to MQTT...");
  mqttClient.setServer(mqtt_broker, mqtt_port);
  mqttClient.setCredentials("", "");
  mqttClient.connect();
  mqttClient.onConnect(onMqttConnect);
  mqttClient.onMessage(onMqttMessage);
  Serial.println("Starting BLE work!");
  bleKeyboard.begin();    //***** When removed, latency is minimal
}

void loop() {
}