#include "baseChannel.h" #include #include #include BaseChannel::BaseChannel(const ChannelConfig& config, QObject* parent) : QObject(parent) , m_config(config) , m_reconnectTimer(new QTimer(this)) { m_reconnectTimer->setSingleShot(true); QObject::connect(m_reconnectTimer,&QTimer::timeout, this, &BaseChannel::onReconnectTimeout); qDebug() << "BaseChannel created:" << m_config.channelId; } BaseChannel::~BaseChannel() { stopReconnectTimer(); qDebug() << "BaseChannel destroyed:" << m_config.channelId; } void BaseChannel::setAutoReconnect(bool enable) { m_autoReconnect = enable; if (!enable) { stopReconnectTimer(); } } void BaseChannel::startReconnectTimer() { if (m_autoReconnect && m_reconnectCount < m_config.maxRetries) { int delay = m_config.reconnectInterval * (1 << m_reconnectCount); // 指数退避 m_reconnectTimer->start(qMin(delay, 30000)); // 最大30秒 m_reconnectCount++; } } void BaseChannel::stopReconnectTimer() { m_reconnectTimer->stop(); m_reconnectCount = 0; } void BaseChannel::reconnect() { if (m_autoReconnect) { disconnect(); QTimer::singleShot(100, this, [this]() { connect(); }); } } void BaseChannel::onReconnectTimeout() { if (m_autoReconnect) { qDebug() << "Reconnecting channel" << m_config.channelId << "attempt" << m_reconnectCount << "/" << m_config.maxRetries; connect(); } } QByteArray BaseChannel::generateMessageId() const { QString id = QString("%1_%2") .arg(m_config.channelId) .arg(QDateTime::currentMSecsSinceEpoch()); return QCryptographicHash::hash(id.toUtf8(), QCryptographicHash::Md5).toHex(); } qint64 BaseChannel::currentTimestamp() const { return QDateTime::currentMSecsSinceEpoch(); }