Last active
March 20, 2025 14:10
-
-
Save esmarr58/4dabd948349555bab16cc072bf86cb8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void MainWindow::sendHeartbeat() { | |
QJsonObject heartbeatMessage; | |
heartbeatMessage["type"] = "heartbeat"; | |
heartbeatMessage["timestamp"] = QDateTime::currentSecsSinceEpoch(); // Unix timestamp | |
QJsonDocument doc(heartbeatMessage); | |
QString jsonString = doc.toJson(QJsonDocument::Compact); | |
if (m_connected) { | |
m_webSocket->sendTextMessage(jsonString); | |
qDebug() << "Enviando heartbeat: " << jsonString; | |
} | |
} | |
void MainWindow::onConnected() { | |
qDebug() << "WebSocket connected!"; | |
m_connected = true; // Actualizar el estado de la conexión | |
} | |
void MainWindow::onTextMessageReceived(const QString &message) { | |
qDebug() << "Mensaje recibido:" << message; | |
// Procesar el mensaje JSON | |
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8()); | |
if (!doc.isNull() && doc.isObject()) { | |
QJsonObject jsonObj = doc.object(); | |
if (jsonObj.contains("type") && jsonObj["type"] == "adc_reading") { | |
double adcValue = jsonObj["adc_value"].toDouble(); | |
qint64 currentTime = QDateTime::currentSecsSinceEpoch(); | |
} | |
} | |
} | |
void MainWindow::onDisconnected() { | |
qDebug() << "WebSocket disconnected!"; | |
ui->textEdit->append("Desconectado del WebSocket"); | |
m_connected = false; // Actualizar el estado de la conexión | |
} | |
void MainWindow::onError(QAbstractSocket::SocketError errores) { | |
QString errorMsg; | |
switch (errores) { | |
case QAbstractSocket::HostNotFoundError: | |
errorMsg = "Host no encontrado."; | |
break; | |
case QAbstractSocket::ConnectionRefusedError: | |
errorMsg = "Conexión rechazada."; | |
break; | |
case QAbstractSocket::RemoteHostClosedError: | |
errorMsg = "El host remoto cerró la conexión."; | |
break; | |
default: | |
errorMsg = "Error desconocido."; | |
break; | |
} | |
qDebug() << "Error de WebSocket: " << errorMsg; | |
ui->textEdit->append("Error de WebSocket: " + errorMsg); | |
} | |
void MainWindow::connectWebSocket(const QUrl &url) { | |
if (!m_connected) { | |
m_webSocket->open(url); | |
qDebug() << "Conectando a WebSocket en" << url; | |
ui->textEdit->append("Conectando a WebSocket en: " + url.toString()); | |
} else { | |
qDebug() << "WebSocket ya está conectado"; | |
ui->textEdit->append("WebSocket ya está conectado"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment