add network error callback

This commit is contained in:
Terrence
2024-11-20 03:28:52 +08:00
parent 874adc80b8
commit c79d6cf4d8
8 changed files with 26 additions and 3 deletions

View File

@@ -85,6 +85,9 @@ bool MqttProtocol::StartMqttClient() {
ESP_LOGI(TAG, "Connecting to endpoint %s", endpoint_.c_str());
if (!mqtt_->Connect(endpoint_, 8883, client_id_, username_, password_)) {
ESP_LOGE(TAG, "Failed to connect to endpoint");
if (on_network_error_ != nullptr) {
on_network_error_("无法连接服务");
}
return false;
}
@@ -167,7 +170,6 @@ bool MqttProtocol::OpenAudioChannel() {
if (mqtt_ == nullptr || !mqtt_->IsConnected()) {
ESP_LOGI(TAG, "MQTT is not connected, try to connect now");
if (!StartMqttClient()) {
ESP_LOGE(TAG, "Failed to connect to MQTT");
return false;
}
}
@@ -188,6 +190,9 @@ bool MqttProtocol::OpenAudioChannel() {
EventBits_t bits = xEventGroupWaitBits(event_group_handle_, MQTT_PROTOCOL_SERVER_HELLO_EVENT, pdTRUE, pdFALSE, pdMS_TO_TICKS(10000));
if (!(bits & MQTT_PROTOCOL_SERVER_HELLO_EVENT)) {
ESP_LOGE(TAG, "Failed to receive server hello");
if (on_network_error_ != nullptr) {
on_network_error_("等待响应超时");
}
return false;
}

View File

@@ -19,3 +19,7 @@ void Protocol::OnAudioChannelOpened(std::function<void()> callback) {
void Protocol::OnAudioChannelClosed(std::function<void()> callback) {
on_audio_channel_closed_ = callback;
}
void Protocol::OnNetworkError(std::function<void(const std::string& message)> callback) {
on_network_error_ = callback;
}

View File

@@ -25,6 +25,7 @@ public:
void OnIncomingJson(std::function<void(const cJSON* root)> callback);
void OnAudioChannelOpened(std::function<void()> callback);
void OnAudioChannelClosed(std::function<void()> callback);
void OnNetworkError(std::function<void(const std::string& message)> callback);
virtual void SendAudio(const std::string& data) = 0;
virtual void SendText(const std::string& text) = 0;
@@ -39,6 +40,7 @@ protected:
std::function<void(const std::string& data)> on_incoming_audio_;
std::function<void()> on_audio_channel_opened_;
std::function<void()> on_audio_channel_closed_;
std::function<void(const std::string& message)> on_network_error_;
int server_sample_rate_ = 16000;
};

View File

@@ -110,6 +110,9 @@ bool WebsocketProtocol::OpenAudioChannel() {
if (!websocket_->Connect(url.c_str())) {
ESP_LOGE(TAG, "Failed to connect to websocket server");
if (on_network_error_ != nullptr) {
on_network_error_("无法连接服务");
}
return false;
}
@@ -128,6 +131,9 @@ bool WebsocketProtocol::OpenAudioChannel() {
EventBits_t bits = xEventGroupWaitBits(event_group_handle_, WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT, pdTRUE, pdFALSE, pdMS_TO_TICKS(10000));
if (!(bits & WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT)) {
ESP_LOGE(TAG, "Failed to receive server hello");
if (on_network_error_ != nullptr) {
on_network_error_("等待响应超时");
}
return false;
}