开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
开源项目 > 程序开发 > 常用工具包 &&
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
develop
分支 (20)
标签 (36)
master
feat/ws-ping-pong
feat/ws-gzip
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.14.9
v1.14.8
v1.14.6
v1.14.5
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
develop
分支 (20)
标签 (36)
master
feat/ws-ping-pong
feat/ws-gzip
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.14.9
v1.14.8
v1.14.6
v1.14.5
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
develop
分支 (20)
标签 (36)
master
feat/ws-ping-pong
feat/ws-gzip
develop
opt/websocket
feat/http-client
feature/tls-crypto-https
fix/jsonrpc
feat/mqtt-reconnect
tidy/doc
wlabs-develop
fix/terminal-mem-leak
feat/use-config-enable-epoll
feature-Broker
opt-loop-wdog
feature-DBus
feature-epoll
feature-update-readme
feature-Dns
feature-TcpSSL
v1.14.9
v1.14.8
v1.14.6
v1.14.5
v1.15.5
v1.15.4
v1.14.4
v1.13.10
v1.13.2
v1.12.28
v1.12.25
v1.12.22
v1.12.20
v1.12.10
v1.12.0
v1.11.14
v1.11.12
v1.11.11
v1.11.5
v1.11.4
cpp-tbox
/
modules
/
mqtt
/
client.cpp
cpp-tbox
/
modules
/
mqtt
/
client.cpp
client.cpp 21.31 KB
一键复制 编辑 原始数据 按行查看 历史
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
/*
* .============.
* // M A K E / \
* // C++ DEV / \
* // E A S Y / \/ \
* ++ ----------. \/\ .
* \\ \ \ /\ /
* \\ \ \ /
* \\ \ \ /
* -============'
*
* Copyright (c) 2018 Hevake and contributors, all rights reserved.
*
* This file is part of cpp-tbox (https://github.com/cpp-main/cpp-tbox)
* Use of this source code is governed by MIT license that can be found
* in the LICENSE file in the root of the source tree. All contributing
* project authors may be found in the CONTRIBUTORS.md file in the root
* of the source tree.
*/
#include "client.h"
#include <thread>
#include <tbox/base/log.h>
#include <tbox/base/assert.h>
#include <tbox/base/lifetime_tag.hpp>
#include <tbox/base/wrapped_recorder.h>
#include <tbox/event/timer_event.h>
#include <tbox/event/fd_event.h>
#include <mosquitto.h>
namespace tbox {
namespace mqtt {
using namespace std;
using namespace event;
struct Client::Data {
Loop *wp_loop = nullptr;
Config config;
Callbacks callbacks;
mosquitto *sp_mosq = nullptr; //!< mosquitto 对象
TimerEvent *sp_timer_ev = nullptr;
FdEvent *sp_sock_read_ev = nullptr;
FdEvent *sp_sock_write_ev = nullptr;
State state = State::kNone;
int cb_level = 0; //! 回调层级
int reconnect_wait_remain_sec = 0; //! 重连等待剩余时长
std::thread *sp_thread = nullptr;
LifetimeTag alive_tag; //!< 对像存活标签
/// Q1: 为什么需要定义它?
///
/// 因为在下面使用了runInLoop()函数注册了延后执行的回调函数。在该函数中将this指针捕获了。
/// 在它真正执行的时候如果 this 指针所指向的对象就已经被 delete 了,那么如果我们还继续
/// 访问那么就一定会触发访问失效的内存地址,行为不可预知。
///
/// 怎么解决呢?
/// 方法一:在对象析构的时候,撤消之前通过 runInLoop() 注册的回调函数;
/// 方法二:在回调函数真正执行的时候,判定一下 this 所指的对象是否有效。
///
/// 这里,我们采用了方法二。
/// 那怎么实现在后期能知晓 this 指针是否有效呢?
/// 通用的方案是:将 this 指针用 std::shared_ptr 进行管理。传入回调函数中的是它的 weak_ptr
/// 这样,在使用 this 指针的时候就能得知它是否有效了。
///
/// 这么做有一个缺点:这个对象必须继续于 enable_this_shared_ptr 类,而且实例化它的时候必须
/// 使用 std::make_shared<T>() 才有效。这样种会给使用者造成一定的负担。
/// 除此之外,还有没有别的方法?于是,我想到了 alive_tag。
/// 由于对象的成员的生命期与对象自身是一致的,判定一个对象是否有效,可以通过判定它的某个成
/// 员生命期是否有效即可。内部附带一个任意类型的智能指针。于是,我在这里定义了一个 alive_tag
/// 的智能指针。它的类型可以是任意的,这里就选定了bool。
/// 无所谓它的类型,反正我们也不会往里写内容。
/// 在 runInLoop() 注册回调函数的时候,就通过 alive_tag 生成对应的 std::weak_ptr 并传入。
/// 在回调函数执行之前,检查一下这个 std::weak_ptr 是否过期就可以得知 this 指针是否有效。
/// 进而避免继续访问到无效 this 指向的内容。
int connect_fail_count = 0; //!< 单次连接失败
static int _instance_count;
};
int Client::Data::_instance_count = 0;
Client::Client(Loop *wp_loop) :
d_(new Data)
{
TBOX_ASSERT(d_ != nullptr);
d_->wp_loop = wp_loop;
if (Data::_instance_count == 0)
mosquitto_lib_init();
++Data::_instance_count;
d_->sp_mosq = mosquitto_new(nullptr, true, this);
d_->sp_timer_ev = wp_loop->newTimerEvent("mqtt::Client::sp_timer_ev");
d_->sp_timer_ev->initialize(chrono::seconds(1), Event::Mode::kPersist);
d_->sp_timer_ev->setCallback(std::bind(&Client::onTimerTick, this));
d_->sp_sock_read_ev = wp_loop->newFdEvent("mqtt::Client::sp_sock_read_ev");
d_->sp_sock_read_ev->setCallback(std::bind(&Client::onSocketRead, this));
d_->sp_sock_write_ev = wp_loop->newFdEvent("mqtt::Client::sp_sock_write_ev");
d_->sp_sock_write_ev->setCallback(std::bind(&Client::onSocketWrite, this));
}
Client::~Client()
{
TBOX_ASSERT(d_->cb_level == 0);
cleanup();
delete d_->sp_sock_write_ev;
delete d_->sp_sock_read_ev;
delete d_->sp_timer_ev;
mosquitto_destroy(d_->sp_mosq);
delete d_;
if (Data::_instance_count > 0) {
--Data::_instance_count;
if (Data::_instance_count == 0)
mosquitto_lib_cleanup();
}
}
bool Client::Config::isValid() const
{
//! 检查base
if (base.broker.domain.empty()) {
LogWarn("broker domain invalid");
return false;
}
if (base.broker.port == 0) {
LogWarn("broker port == 0");
return false;
}
if (base.keepalive < 0) {
LogWarn("keeplive < 0");
return false;
}
//! 检查tls
if (tls.enabled) {
if (tls.is_require_peer_cert) {
//! 要验对方的证书,就必须得有CA。要么指定了文件,要么指定了路径
if (tls.ca_file.empty() && tls.ca_path.empty()) {
LogWarn("both CA file and path is empty");
return false;
}
}
if (!tls.cert_file.empty() && tls.key_file.empty()) {
//! 如果指定了自己证书,但没有给出私钥,也是错的
LogWarn("key_file is empty");
return false;
}
}
//! 检查will
if (will.enabled) {
if (will.topic.empty()) {
LogWarn("will topic is empty");
return false;
}
}
return true;
}
bool Client::initialize(const Config &config, const Callbacks &callbacks)
{
if (d_->state != State::kNone) {
LogWarn("cleanup first");
return false;
}
if (!config.isValid())
return false;
d_->config = config;
d_->callbacks = callbacks;
updateStateTo(State::kInited);
return true;
}
void Client::cleanup()
{
if (d_->state <= State::kNone)
return;
stop();
d_->config = Config();
d_->callbacks = Callbacks();
updateStateTo(State::kNone);
}
bool Client::start()
{
if (d_->state != State::kInited &&
d_->state != State::kEnd) {
LogWarn("state is not kInited or kEnd");
return false;
}
RECORD_SCOPE();
//! 基础设置
const char *client_id = nullptr;
if (!d_->config.base.client_id.empty())
client_id = d_->config.base.client_id.c_str();
int ret = mosquitto_reinitialise(d_->sp_mosq, client_id, true, this);
if (ret == MOSQ_ERR_SUCCESS) {
mosquitto_connect_callback_set(d_->sp_mosq, OnConnectWrapper);
mosquitto_disconnect_callback_set(d_->sp_mosq, OnDisconnectWrapper);
mosquitto_message_callback_set(d_->sp_mosq, OnMessageWrapper);
mosquitto_publish_callback_set(d_->sp_mosq, OnPublishWrapper);
mosquitto_subscribe_callback_set(d_->sp_mosq, OnSubscribeWrapper);
mosquitto_unsubscribe_callback_set(d_->sp_mosq, OnUnsubscribeWrapper);
mosquitto_log_callback_set(d_->sp_mosq, OnLogWrapper);
} else {
LogWarn("mosquitto_reinitialise() fail, ret:%s, %s", ret, mosquitto_strerror(ret));
return false;
}
//! TLS 设置
if (d_->config.tls.enabled) {
const char *ca_file = nullptr;
const char *ca_path = nullptr;
const char *cert_file = nullptr;
const char *key_file = nullptr;
if (!d_->config.tls.ca_file.empty())
ca_file = d_->config.tls.ca_file.c_str();
if (!d_->config.tls.ca_path.empty())
ca_path = d_->config.tls.ca_path.c_str();
if (!d_->config.tls.cert_file.empty()) {
cert_file = d_->config.tls.cert_file.c_str();
key_file = d_->config.tls.key_file.c_str();
}
//! TODO: 没有完善 pw_callback 功能,将来需要再实现,暂时填nullptr
mosquitto_tls_set(d_->sp_mosq, ca_file, ca_path, cert_file, key_file, nullptr);
const char *ssl_version = nullptr;
const char *ciphers = nullptr; //! TODO: 暂不设置
if (!d_->config.tls.ssl_version.empty())
ssl_version = d_->config.tls.ssl_version.c_str();
mosquitto_tls_opts_set(d_->sp_mosq, d_->config.tls.is_require_peer_cert, ssl_version, ciphers);
mosquitto_tls_insecure_set(d_->sp_mosq, d_->config.tls.is_insecure);
}
//! Will 设置
if (d_->config.will.enabled) {
mosquitto_will_set(d_->sp_mosq,
d_->config.will.topic.c_str(),
d_->config.will.payload.size(),
d_->config.will.payload.data(),
d_->config.will.qos,
d_->config.will.retain);
}
const char *username = nullptr;
const char *passwd = nullptr;
if (!d_->config.base.username.empty())
username = d_->config.base.username.c_str();
if (!d_->config.base.passwd.empty())
passwd = d_->config.base.passwd.c_str();
if (username != nullptr)
mosquitto_username_pw_set(d_->sp_mosq, username, passwd);
updateStateTo(State::kConnecting);
CHECK_DELETE_RESET_OBJ(d_->sp_thread);
auto is_alive = d_->alive_tag.get(); //! 原理见Q1
d_->connect_fail_count = 0;
//! 由于 mosquitto_connect() 是阻塞函数,为了避免阻塞其它事件,特交给子线程去做
d_->sp_thread = new thread(
[this, is_alive] {
RECORD_SCOPE();
int ret = mosquitto_connect_async(d_->sp_mosq,
d_->config.base.broker.domain.c_str(),
d_->config.base.broker.port,
d_->config.base.keepalive);
d_->wp_loop->runInLoop(
[this, is_alive, ret] {
RECORD_SCOPE();
if (!is_alive) { //!< 判定this指针是否有效
LogWarn("object not alive");
return;
}
onTcpConnectDone(ret);
enableTimer();
},
"mqtt::Client::start, connect done"
);
}
);
return true;
}
void Client::stop()
{
if (d_->state <= State::kInited ||
d_->state == State::kEnd)
return;
RECORD_SCOPE();
if (d_->state == State::kTcpConnected ||
d_->state == State::kMqttConnected) {
//! 如果已成功连接,则立即断开
mosquitto_disconnect(d_->sp_mosq); //! 请求断开,后续工作在 onDisconnected() 中处理
} else {
//! 如果正在连接,则停止连接线程
if (d_->sp_thread != nullptr) {
d_->sp_thread->join();
CHECK_DELETE_RESET_OBJ(d_->sp_thread);
}
}
disableTimer();
updateStateTo(State::kInited);
return;
}
int Client::subscribe(const std::string &topic, int *p_mid, int qos)
{
if (d_->state != State::kMqttConnected) {
LogWarn("mqtt is not connected");
return false;
}
RECORD_SCOPE();
int mid = 0;
int ret = mosquitto_subscribe(d_->sp_mosq, &mid, topic.c_str(), qos);
if (p_mid != nullptr)
*p_mid = mid;
enableSocketWriteIfNeed();
return ret == MOSQ_ERR_SUCCESS;
}
int Client::unsubscribe(const std::string &topic, int *p_mid)
{
if (d_->state != State::kMqttConnected) {
LogWarn("mqtt is not connected");
return false;
}
RECORD_SCOPE();
int mid = 0;
int ret = mosquitto_unsubscribe(d_->sp_mosq, &mid, topic.c_str());
if (p_mid != nullptr)
*p_mid = mid;
enableSocketWriteIfNeed();
return ret == MOSQ_ERR_SUCCESS;
}
int Client::publish(const std::string &topic, const void *payload_ptr, size_t payload_size,
int qos, bool retain, int *p_mid)
{
if (d_->state != State::kMqttConnected) {
LogWarn("mqtt is not connected");
return false;
}
RECORD_SCOPE();
int mid = 0;
int ret = mosquitto_publish(d_->sp_mosq, &mid, topic.c_str(),
payload_size, payload_ptr,
qos, retain);
if (p_mid != nullptr)
*p_mid = mid;
enableSocketWriteIfNeed();
return ret == MOSQ_ERR_SUCCESS;
}
Client::State Client::getState() const
{
return d_->state;
}
void Client::onTimerTick()
{
if (d_->state == State::kTcpConnected ||
d_->state == State::kMqttConnected) {
mosquitto_loop_misc(d_->sp_mosq);
if (mosquitto_socket(d_->sp_mosq) > 0)
enableSocketWriteIfNeed();
} else if (d_->state == State::kConnecting) {
if (d_->sp_thread == nullptr) {
auto is_alive = d_->alive_tag.get(); //! 原理见Q1
d_->sp_thread = new thread(
[this, is_alive] {
RECORD_SCOPE();
int ret = mosquitto_reconnect_async(d_->sp_mosq);
d_->wp_loop->runInLoop(
[this, is_alive, ret] {
RECORD_SCOPE();
if (!is_alive) { //!< 判定this指针是否有效
LogWarn("object not alive");
return;
}
onTcpConnectDone(ret);
},
"mqtt::Client::onTimerTick, reconnect done"
);
}
);
}
} else if (d_->state == State::kReconnWaiting) {
auto &remain_sec = d_->reconnect_wait_remain_sec;
if (remain_sec > 0) {
--remain_sec;
if (remain_sec == 0) {
updateStateTo(State::kConnecting);
LogDbg("wait timeout, reconnect now");
}
}
} else if (d_->state == State::kEnd) {
disableTimer();
}
}
void Client::onSocketRead()
{
mosquitto_loop_read(d_->sp_mosq, 1);
enableSocketWriteIfNeed();
}
void Client::onSocketWrite()
{
mosquitto_loop_write(d_->sp_mosq, 1);
enableSocketWriteIfNeed();
}
void Client::OnConnectWrapper(struct mosquitto *, void *userdata, int rc)
{
Client *p_this = static_cast<Client*>(userdata);
p_this->onConnected(rc);
}
void Client::OnDisconnectWrapper(struct mosquitto *, void *userdata, int rc)
{
Client *p_this = static_cast<Client*>(userdata);
p_this->onDisconnected(rc);
}
void Client::OnPublishWrapper(struct mosquitto *, void *userdata, int mid)
{
Client *p_this = static_cast<Client*>(userdata);
p_this->onPublish(mid);
}
void Client::OnMessageWrapper(struct mosquitto *, void *userdata, const struct mosquitto_message *msg)
{
Client *p_this = static_cast<Client*>(userdata);
p_this->onMessage(msg);
}
void Client::OnSubscribeWrapper(struct mosquitto *, void *userdata, int mid, int qos_count, const int *granted_qos)
{
Client *p_this = static_cast<Client*>(userdata);
p_this->onSubscribe(mid, qos_count, granted_qos);
}
void Client::OnUnsubscribeWrapper(struct mosquitto *, void *userdata, int mid)
{
Client *p_this = static_cast<Client*>(userdata);
p_this->onUnsubscribe(mid);
}
void Client::OnLogWrapper(struct mosquitto *, void *userdata, int level, const char *str)
{
Client *p_this = static_cast<Client*>(userdata);
p_this->onLog(level, str);
}
void Client::onConnected(int rc)
{
if (rc != 0) {
LogWarn("connect fail, rc:%d, %s", rc, mosquitto_strerror(rc));
return;
}
LogInfo("connected");
RECORD_SCOPE();
if (d_->state != State::kMqttConnected) {
updateStateTo(State::kMqttConnected);
++d_->cb_level;
if (d_->callbacks.connected)
d_->callbacks.connected();
--d_->cb_level;
}
}
void Client::onDisconnected(int rc)
{
RECORD_SCOPE();
LogNotice("disconnected, rc:%d, %s", rc, mosquitto_strerror(rc));
handleDisconnectEvent();
}
void Client::onPublish(int mid)
{
LogInfo("mid:%d", mid);
RECORD_SCOPE();
++d_->cb_level;
if (d_->callbacks.message_pub)
d_->callbacks.message_pub(mid);
--d_->cb_level;
}
void Client::onSubscribe(int mid, int qos, const int *granted_qos)
{
LogInfo("mid:%d, qos:%d", mid, qos);
RECORD_SCOPE();
++d_->cb_level;
if (d_->callbacks.subscribed)
d_->callbacks.subscribed(mid, qos, granted_qos);
--d_->cb_level;
}
void Client::onUnsubscribe(int mid)
{
LogInfo("mid:%d", mid);
RECORD_SCOPE();
++d_->cb_level;
if (d_->callbacks.unsubscribed)
d_->callbacks.unsubscribed(mid);
--d_->cb_level;
}
void Client::onMessage(const struct mosquitto_message *msg)
{
if (msg == nullptr)
return;
LogInfo("mid:%d, topic:%s", msg->mid, msg->topic);
RECORD_SCOPE();
++d_->cb_level;
if (d_->callbacks.message_recv)
d_->callbacks.message_recv(msg->mid,
msg->topic,
msg->payload,
msg->payloadlen,
msg->qos,
msg->retain);
--d_->cb_level;
}
void Client::onLog(int level, const char *str)
{
auto new_level = TBOX_LOG_LEVEL_DEBUG;
switch (level & 0x1F) {
case MOSQ_LOG_ERR:
new_level = TBOX_LOG_LEVEL_ERROR;
break;
case MOSQ_LOG_WARNING:
new_level = TBOX_LOG_LEVEL_WARN;
break;
case MOSQ_LOG_NOTICE:
new_level = TBOX_LOG_LEVEL_NOTICE;
break;
default:; //! regard MOSQ_LOG_INFO as TBOX_LOG_LEVEL_DEBUG
}
LogPrintfFunc("mosq", nullptr, nullptr, 0, new_level, 0, str);
}
void Client::onTcpConnectDone(int ret)
{
RECORD_SCOPE();
if (d_->sp_thread == nullptr) {
LogWarn("sp_thread == nullptr");
return;
}
d_->sp_thread->join();
CHECK_DELETE_RESET_OBJ(d_->sp_thread);
if (ret == MOSQ_ERR_SUCCESS) {
d_->connect_fail_count = 0;
LogDbg("connect success");
enableSocketRead();
enableSocketWriteIfNeed();
updateStateTo(State::kTcpConnected);
} else {
++d_->connect_fail_count;
LogNotice("connect fail, rc:%d, %s, fail_count:%d",
ret, mosquitto_strerror(ret), d_->connect_fail_count);
tryReconnect();
++d_->cb_level;
if (d_->callbacks.connect_fail)
d_->callbacks.connect_fail();
--d_->cb_level;
}
}
void Client::enableSocketRead()
{
if (mosquitto_socket(d_->sp_mosq) < 0)
return;
if (d_->sp_sock_read_ev->isEnabled())
return;
d_->sp_sock_read_ev->initialize(mosquitto_socket(d_->sp_mosq), FdEvent::kReadEvent, Event::Mode::kPersist);
d_->sp_sock_read_ev->enable();
}
void Client::enableSocketWrite()
{
if (mosquitto_socket(d_->sp_mosq) < 0)
return;
if (d_->sp_sock_write_ev->isEnabled())
return;
d_->sp_sock_write_ev->initialize(mosquitto_socket(d_->sp_mosq), FdEvent::kWriteEvent, Event::Mode::kOneshot);
d_->sp_sock_write_ev->enable();
}
void Client::enableSocketWriteIfNeed()
{
if (mosquitto_want_write(d_->sp_mosq))
enableSocketWrite();
}
void Client::enableTimer()
{
d_->sp_timer_ev->enable();
}
void Client::disableSocketRead()
{
d_->sp_sock_read_ev->disable();
}
void Client::disableSocketWrite()
{
d_->sp_sock_write_ev->disable();
}
void Client::disableTimer()
{
d_->sp_timer_ev->disable();
}
void Client::tryReconnect()
{
//! 如果开启了自动重连
if (d_->config.auto_reconnect_enable) {
auto wait_remain_sec = d_->config.auto_reconnect_wait_sec;
//! 如果设置了 auto_reconnect_wait_sec_gen_func 函数
//! 就则使用 auto_reconnect_wait_sec_gen_func 函数生成 wait_remain_sec
if (d_->config.auto_reconnect_wait_sec_gen_func)
wait_remain_sec = d_->config.auto_reconnect_wait_sec_gen_func(d_->connect_fail_count);
if (wait_remain_sec > 0) {
LogDbg("reconnect after %d sec", wait_remain_sec);
updateStateTo(State::kReconnWaiting);
} else {
LogDbg("reconnect now");
updateStateTo(State::kConnecting);
}
d_->reconnect_wait_remain_sec = wait_remain_sec;
} else { //! 如果不需要自动重连
LogDbg("no need reconnect, end");
updateStateTo(State::kEnd);
}
}
void Client::handleDisconnectEvent()
{
disableSocketRead();
disableSocketWrite();
if (d_->state == State::kTcpConnected ||
d_->state == State::kMqttConnected) {
auto is_mqtt_disconnected = d_->state == State::kMqttConnected;
//! 一定要先判定,因为 tryReconnect() 会改 d_->state
tryReconnect();
++d_->cb_level;
if (is_mqtt_disconnected) {
if (d_->callbacks.disconnected)
d_->callbacks.disconnected();
} else {
if (d_->callbacks.connect_fail)
d_->callbacks.connect_fail();
}
--d_->cb_level;
}
}
void Client::updateStateTo(State new_state)
{
d_->state = new_state;
LogDbg("new_state: %d", d_->state);
++d_->cb_level;
if (d_->callbacks.state_changed)
d_->callbacks.state_changed(new_state);
--d_->cb_level;
}
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

cpp-tbox是一个Linux C++,MIT开源许可的,基于 Reactor 模式的开发框架与组件库。它主要针对智能硬件、机器人、网络服务等开发领域。 它提供了一套易于开发、稳定可靠的框架,有:通信库(TCP/UDP/串口)、HTTP、线程池、定时器池、协程、日志、命令终端、状态机、行为树等非常实用的开发组件,以及完备实用的主框架,能为广大开发者节省大量开发与调试时间。
取消

发行版

暂无发行版

开源评估指数源自 OSS-Compass 评估体系,评估体系围绕以下三个维度对项目展开评估:

1. 开源生态

  • 生产力:来评估开源项目输出软件制品和开源价值的能力。
  • 创新力:用于评估开源软件及其生态系统的多样化程度。
  • 稳健性:用于评估开源项目面对多变的发展环境,抵御内外干扰并自我恢复的能力。

2. 协作、人、软件

  • 协作:代表了开源开发行为中协作的程度和深度。
  • 人:观察开源项目核心人员在开源项目中的影响力,并通过第三方视角考察用户和开发者对开源项目的评价。
  • 软件:从开源项目对外输出的制品评估其价值最终落脚点。也是开源评估最"古老"的主流方向之一"开源软件" 的具体表现。

3. 评估模型

    基于"开源生态"与"协作、人、软件"的维度,找到与该目标直接或间接相关的可量化指标,对开源项目健康与生态进行量化评估,最终形成开源评估指数。

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/cpp-master/cpp-tbox.git
git@gitee.com:cpp-master/cpp-tbox.git
cpp-master
cpp-tbox
cpp-tbox
develop
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /