Browse Source

1. 添加websocketservice,并完善连接、认证、心跳、重连、协议通知

2. 添加httpservice,并完善login、updateStatus请求
3. 添加MainWidget与Websocket和Http的信号绑定
master
zhangsan 4 years ago
parent
commit
cdd2b8a458
  1. 17
      QCPShow.pro
  2. 12
      QCPShow.pro.user
  3. 166
      httpservice.cpp
  4. 25
      httpservice.h
  5. 28
      main.cpp
  6. 112
      mainconfig.cpp
  7. 35
      mainconfig.h
  8. 33
      mainwidget.cpp
  9. 8
      mainwidget.h
  10. 8
      patientemergencyinfo.cpp
  11. 22
      patientemergencyinfo.h
  12. 9
      resttest
  13. 131
      websocketservice.cpp
  14. 38
      websocketservice.h

17
QCPShow.pro

@ -5,7 +5,7 @@
#-------------------------------------------------
QT += core gui
QT += serialport network
QT += serialport network websockets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
@ -31,7 +31,11 @@ SOURCES += main.cpp\
ccwidgets/cqspinbox.cpp \
ccwidgets/cqtextedit.cpp \
ccwidgets/cqwidgetspinbox.cpp \
util/commonutil.cpp
util/commonutil.cpp \
httpservice.cpp \
mainconfig.cpp \
websocketservice.cpp \
patientemergencyinfo.cpp
HEADERS += mainwidget.h \
serial/serialport.h \
@ -39,7 +43,11 @@ HEADERS += mainwidget.h \
ccwidgets/cqspinbox.h \
ccwidgets/cqtextedit.h \
ccwidgets/cqwidgetspinbox.h \
util/commonutil.h
util/commonutil.h \
httpservice.h \
mainconfig.h \
websocketservice.h \
patientemergencyinfo.h
FORMS += mainwidget.ui
@ -48,4 +56,5 @@ RESOURCES += \
DISTFILES += \
.gitignore \
ReadMe.md
ReadMe.md \
resttest

12
QCPShow.pro.user

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 4.2.1, 2021-10-18T14:21:25. -->
<!-- Written by QtCreator 4.2.1, 2021-10-19T07:53:12. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
@ -284,15 +284,15 @@
</valuelist>
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">QcpShow</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4RunConfiguration:E:/Qt/QtSpace/QcpShow/QcpShow.pro</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">QCPShow</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">QCPShow2</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4RunConfiguration:E:/Qt/QtSpace/QCPShow/QCPShow.pro</value>
<value type="bool" key="QmakeProjectManager.QmakeRunConfiguration.UseLibrarySearchPath">true</value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.CommandLineArguments"></value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.ProFile">QcpShow.pro</value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.ProFile">QCPShow.pro</value>
<value type="bool" key="Qt4ProjectManager.Qt4RunConfiguration.UseDyldImageSuffix">false</value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.UserWorkingDirectory"></value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.UserWorkingDirectory.default"></value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.UserWorkingDirectory.default">E:/Qt/QtSpace/build-QcpShow-Desktop_Qt_5_8_0_MinGW_32bit-Debug</value>
<value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</value>
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>

166
httpservice.cpp

@ -0,0 +1,166 @@
#include "httpservice.h"
#include "mainconfig.h"
HttpService::HttpService(QObject *parent) : QObject(parent)
{
mManager = new QNetworkAccessManager;
}
QByteArray HttpService::get(QUrl url,quint32 timeoutInMs)
{
qDebug() << url;
//设置超时
QTimer timer;
timer.setInterval(timeoutInMs);
timer.setSingleShot(true);
//构造并发送请求
QNetworkRequest request;
request.setUrl(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
request.setRawHeader("Authorization",QByteArray("Bearer ").append(MainConfig::token));
QNetworkReply *reply = mManager->get(request);
//超时绑定
QEventLoop loop;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
//处理响应
if (!timer.isActive()) {// 超时
disconnect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
reply->abort();
reply->deleteLater();
qDebug() << "Timeout";
return "";
}
QByteArray result = "";
//未超时
timer.stop();
if (reply->error() != QNetworkReply::NoError) {
// 错误处理
qDebug() << "Error String : " << reply->errorString();
} else {
QVariant variant = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
int nStatusCode = variant.toInt();
// 根据状态码做进一步数据处理
//QByteArray bytes = pReply->readAll();
qDebug() << "Status Code : " << nStatusCode;
if(nStatusCode == 200){
result = reply->readAll();
}
}
return result;
}
QByteArray HttpService::postJson(QUrl url,const QByteArray &json, quint32 timeoutInMs)
{
qDebug() << url << "\n" << json;
//设置超时
QTimer timer;
timer.setInterval(timeoutInMs);
timer.setSingleShot(true);
//构造并发送请求
QNetworkRequest request;
request.setUrl(url);
request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));
request.setRawHeader("Authorization",QByteArray("Bearer ").append(MainConfig::token));
QNetworkReply *reply = mManager->post(request,json);
//超时绑定
QEventLoop loop;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
timer.start();
loop.exec();
//处理响应
if (!timer.isActive()) {// 超时
disconnect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
reply->abort();
reply->deleteLater();
qDebug() << "Timeout";
return "";
}
QByteArray result = "";
//未超时
timer.stop();
if (reply->error() != QNetworkReply::NoError) {
// 错误处理
qDebug() << "Error String : " << reply->errorString();
} else {
QVariant variant = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
int nStatusCode = variant.toInt();
// 根据状态码做进一步数据处理
//QByteArray bytes = pReply->readAll();
qDebug() << "Status Code : " << nStatusCode;
if(nStatusCode == 200){
result = reply->readAll();
}
}
return result;
}
void HttpService::login(QString username, QString password)
{
//构造参数
QString rawJson = "{\"client\":1,\"data\":{\"credential\":\"%2\",\"identifier\":\"%1\"},\"scene\":0,\"type\":3}";
QString json = rawJson.arg(username).arg(password);
//发送请求
QByteArray result = postJson(MainConfig::loginUrl,json.toUtf8());
qDebug() << result;
//解析响应
QJsonParseError jerror;
QJsonDocument jdoc;
QJsonObject jobj;
jdoc = QJsonDocument::fromJson(result, &jerror);
if (jerror.error != QJsonParseError::NoError || !jdoc.isObject() || !jdoc.object().contains("code"))
{
qDebug() << QString::fromUtf8("登录请求发送失败");
return;
}
jobj = jdoc.object();
int resCode = jobj.take("code").toInt();
if(resCode == 200){
MainConfig::token = jobj.take("data").toObject().take("token").toString();
qDebug() << MainConfig::token;
}else{
qDebug() << "登录失败:" << resCode;
}
}
void HttpService::updateStatus(QString firstAidId, QString status)
{
//构造参数
QString rawJson = "{\"param\":{\"firstAidId\":\"%1\",\"status\":\"%2\"}}";
QString json = rawJson.arg(firstAidId).arg(status);
//发送请求
QByteArray result = postJson(MainConfig::serviceStatusChangedUrl,json.toUtf8());
qDebug() << result;
//解析响应
QJsonParseError jerror;
QJsonDocument jdoc;
QJsonObject jobj;
jdoc = QJsonDocument::fromJson(result, &jerror);
if (jerror.error != QJsonParseError::NoError || !jdoc.isObject() || !jdoc.object().contains("code"))
{
qDebug() << QString::fromUtf8("请求失败");
return;
}
jobj = jdoc.object();
int resCode = jobj.take("code").toInt();
if(resCode == 200){
qDebug() << "updateStatus请求成功";
}else{
qDebug() << "updateStatus失败:" << resCode;
}
}

25
httpservice.h

@ -0,0 +1,25 @@
#ifndef HTTPSERVICE_H
#define HTTPSERVICE_H
#include <QObject>
#include <QtNetwork>
class HttpService : public QObject
{
Q_OBJECT
public:
explicit HttpService(QObject *parent = 0);
QByteArray get(QUrl url, quint32 timeoutInMs = 5000);
QByteArray postJson(QUrl url,const QByteArray &json, quint32 timeoutInMs = 5000);
// void sendIdcardInfo();
private:
QNetworkAccessManager *mManager;
signals:
public slots:
void login(QString username,QString password);
void updateStatus(QString firstAidId,QString status);
};
#endif // HTTPSERVICE_H

28
main.cpp

@ -1,10 +1,38 @@
#include "mainwidget.h"
#include <QApplication>
#include "mainconfig.h"
#include "httpservice.h"
#include "websocketservice.h"
#include "patientemergencyinfo.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//初始化配置文件
MainConfig::initConfig();
//初始化httpservice,并自动登录
HttpService httpService;
httpService.login(MainConfig::username,MainConfig::password);
//初始化websocket,并自动连接服务器
WebsocketService websocketService;
websocketService.connectToServer(MainConfig::wsUrl);
//创建主窗体
MainWidget w;
//绑定信号与槽
QObject::connect(&websocketService,&WebsocketService::wsConnectedStatusChanged,
&w,MainWidget::onWsConnectedStatusChanged);
QObject::connect(&websocketService,&WebsocketService::newPatientMergencyInfo,
&w,MainWidget::onNewPatientMergencyInfo);
QObject::connect(&websocketService,&WebsocketService::patientMergencyStatusChanged,
&w,MainWidget::onPatientMergencyStatusChanged);
QObject::connect(&w,&MainWidget::statusChanged,&httpService,&HttpService::updateStatus);
w.show();
return a.exec();

112
mainconfig.cpp

@ -0,0 +1,112 @@
#include "mainconfig.h"
#include <QSettings>
#include <QtCore>
#define D_CONFIG_FILE_PATH "./setting.ini"
QString MainConfig::token = "";
QString MainConfig::username = "shoufeichu";
QString MainConfig::password = "123456";
QString MainConfig::loginUrl = "http://test.tall.wiki/gateway/tall3/v3.0/users/signin";
QString MainConfig::sendUserInfoUrl = "https://test.tall.wiki/gateway/qcp/v3.0/button/idCardDiscern";
QString MainConfig::oneKeyStartUrl = "https://test.tall.wiki/gateway/qcp/v3.0/button/buttonStart";
QString MainConfig::serviceStatusChangedUrl = "https://test.tall.wiki/gateway/qcp/v3.0/button/updateStatus";
QString MainConfig::wsUrl = "wss://test.tall.wiki/websocket/message/v4.0/ws";
QString MainConfig::wsHeartInterval = "10";
MainConfig::MainConfig(QObject *parent) : QObject(parent)
{
}
/**
* @brief 使ini文件QSetting模式无法写入注释
*/
void MainConfig::createConfigFileWithDefaultValues()
{
//创建ini配置文件
// QSettings *iniFile = new QSettings(D_CONFIG_FILE_PATH, QSettings::IniFormat);
// iniFile->beginGroup("MAIN");
// iniFile->setValue("videodir", videodir);
// iniFile->setValue("videoNumInRow", videoNumInRow);
// iniFile->setValue("videoAutoPlay", videoAutoPlay);
// iniFile->setValue("videoAutoMode", videoAutoMode);
// iniFile->endGroup();
// iniFile->beginGroup("USER");
// iniFile->setValue("username", username);
// iniFile->setValue("password", password);
// iniFile->endGroup();
QString content = "[USER]\n";
content.append(";登录用户名\n").append("username = ").append(username).append("\n");
content.append(";登录密码\n").append("password = ").append(password).append("\n");
content.append("\n");
content.append("[HTTP]\n");
content.append(";登录请求URL\n").append("loginUrl = ").append(loginUrl).append("\n");
content.append(";发送身份证信息URL\n").append("sendUserInfoUrl = ").append(sendUserInfoUrl).append("\n");
content.append(";一键启动URL\n").append("oneKeyStartUrl = ").append(oneKeyStartUrl).append("\n");
content.append(";服务状态改变URL(rgb)\n").append("serviceStatusChangedUrl = ").append(serviceStatusChangedUrl).append("\n");
content.append("\n");
content.append("[WEBSOCKET]\n");
content.append(";Websocket URL\n").append("wsUrl = ").append(wsUrl).append("\n");
content.append(";Websocket心跳间隔(s)\n").append("wsHeartInterval = ").append(wsHeartInterval).append("\n");
QFile file(D_CONFIG_FILE_PATH);
file.open(QIODevice::WriteOnly | QIODevice::Text);
file.write(content.toUtf8());
file.close();
}
void MainConfig::readConfigFile(){
//创建ini配置文件
QSettings *iniFile = new QSettings(D_CONFIG_FILE_PATH, QSettings::IniFormat);
iniFile->setIniCodec("UTF-8");
//获取配置文件名
QString fileName = iniFile->fileName();
qDebug().noquote()<<"fileName:"<<fileName;
//判断键是否存在
if(iniFile->contains("USER/username")){
username = iniFile->value("USER/username").toString();
}
if(iniFile->contains("USER/password")){
password = iniFile->value("USER/password").toString();
}
if(iniFile->contains("HTTP/loginUrl")){
loginUrl = iniFile->value("HTTP/loginUrl").toString();
}
if(iniFile->contains("HTTP/sendUserInfoUrl")){
sendUserInfoUrl = iniFile->value("HTTP/sendUserInfoUrl").toString();
}
if(iniFile->contains("HTTP/oneKeyStartUrl")){
oneKeyStartUrl = iniFile->value("HTTP/oneKeyStartUrl").toString();
}
if(iniFile->contains("HTTP/serviceStatusChangedUrl")){
serviceStatusChangedUrl = iniFile->value("HTTP/serviceStatusChangedUrl").toString();
}
if(iniFile->contains("WEBSOCKET/wsUrl")){
wsUrl = iniFile->value("WEBSOCKET/wsUrl").toString();
}
if(iniFile->contains("WEBSOCKET/wsHeartInterval")){
wsHeartInterval = iniFile->value("WEBSOCKET/wsHeartInterval").toString();
}
qDebug() << username << password << "\n"
<< loginUrl << sendUserInfoUrl << oneKeyStartUrl << serviceStatusChangedUrl << "\n"
<< wsUrl << wsHeartInterval ;
}
void MainConfig::initConfig()
{
QFile file(D_CONFIG_FILE_PATH);
if(!file.exists()){
qDebug() << D_CONFIG_FILE_PATH << " Not Exist. Create it by defalut values.";
createConfigFileWithDefaultValues();
}else{
qDebug() << D_CONFIG_FILE_PATH << "Exists";
readConfigFile();
}
}

35
mainconfig.h

@ -0,0 +1,35 @@
#ifndef MAINCONFIG_H
#define MAINCONFIG_H
#include <QObject>
#include <QHash>
class MainConfig : public QObject
{
Q_OBJECT
public:
explicit MainConfig(QObject *parent = 0);
static void initConfig();
static void createConfigFileWithDefaultValues();
static void readConfigFile();
static void createUserConfigFileWithDefaultValues();
static void readUserConfigFile();
public:
static QString token;
static QString username;
static QString password;
static QString loginUrl;
static QString sendUserInfoUrl;
static QString oneKeyStartUrl;
static QString serviceStatusChangedUrl;
static QString wsUrl;
static QString wsHeartInterval;
signals:
public slots:
};
#endif // MAINCONFIG_H

33
mainwidget.cpp

@ -1,5 +1,7 @@
#include "mainwidget.h"
#include "ui_mainwidget.h"
#include <QtCore>
#include "httpservice.h"
MainWidget::MainWidget(QWidget *parent) :
QWidget(parent),
@ -12,3 +14,34 @@ MainWidget::~MainWidget()
{
delete ui;
}
void MainWidget::onWsConnectedStatusChanged(int status)
{
qDebug() << "MainWidget::onWsConnectedStatusChanged " << status;
}
void MainWidget::onNewPatientMergencyInfo(QString firstAidId, QString name, QString content, quint64 realCountDownInSeconds)
{
qDebug() << "MainWidget::onNewPatientMergencyInfo " << firstAidId << name << content << realCountDownInSeconds;
}
void MainWidget::onPatientMergencyStatusChanged(QString firstAidId,QString time, QString status)
{
//TODO firstAidId == null 选择倒计时最小的急救
qDebug() << "MainWidget::onPatientMergencyStatusChanged " << firstAidId << time << status;
if(status == 0){
return;
}
//发送信号,该信号与httpservice的updatestatus请求绑定
emit statusChanged(firstAidId,status);
//处理状态改变
if(status == 1){ //进行中(拍了一下按键)
}else if(status == 2){//服务环节结束
}
}

8
mainwidget.h

@ -17,6 +17,14 @@ public:
private:
Ui::MainWidget *ui;
public slots:
void onWsConnectedStatusChanged(int);
void onNewPatientMergencyInfo(QString firstAidId,QString name,QString content,quint64 realCountDownInSeconds);
void onPatientMergencyStatusChanged(QString firstAidId,QString time,QString status);
signals:
statusChanged(QString firstAidId,QString status);
};
#endif // MAINWIDGET_H

8
patientemergencyinfo.cpp

@ -0,0 +1,8 @@
#include "patientemergencyinfo.h"
PatientEmergencyInfo::PatientEmergencyInfo(
QString id,QString name,QString text,quint64 realCountDownInSeconds,QObject *parent)
:id(id),name(name),text(text),realCountDownInSeconds(realCountDownInSeconds),QObject(parent)
{
}

22
patientemergencyinfo.h

@ -0,0 +1,22 @@
#ifndef PATIENTEMERGENCYINFO_H
#define PATIENTEMERGENCYINFO_H
#include <QObject>
class PatientEmergencyInfo : public QObject
{
Q_OBJECT
public:
explicit PatientEmergencyInfo(
QString id,QString name,QString text,quint64 realCountDownInSeconds,QObject *parent = 0);
QString id;
QString name;
QString text;
quint64 realCountDownInSeconds;
signals:
public slots:
};
#endif // PATIENTEMERGENCYINFO_H

9
resttest

@ -0,0 +1,9 @@
https://example.com/comments/1
POST https://example.com/comments HTTP/1.1
content-type: application/json
{
"name": "sample",
"time": "Wed, 21 Oct 2015 18:27:50 GMT"
}

131
websocketservice.cpp

@ -0,0 +1,131 @@
#include "websocketservice.h"
#include "mainconfig.h"
#include <QtCore>
WebsocketService::WebsocketService(QObject *parent)
:QObject(parent)
{
m_wsHeartInterval = MainConfig::wsHeartInterval.toInt();
m_heartTimer.setInterval(1 * 1000);
m_heartTimer.start();
connect(&m_heartTimer,&QTimer::timeout,this,&WebsocketService::wsSendPingMsg);
connect(&m_webSocket, &QWebSocket::connected, this, &WebsocketService::onConnected);
connect(&m_webSocket, &QWebSocket::disconnected, this, &WebsocketService::onDisconnected);
connect(&m_webSocket, &QWebSocket::textMessageReceived, this,&WebsocketService::onTextMessageReceived);
}
void WebsocketService::connectToServer(QString url)
{
m_url = url;
m_webSocket.open(QUrl(url));
}
void WebsocketService::onConnected()
{
qDebug() << QDateTime::currentDateTime().toString("hh:mm:ss") << "ws connected..";
emit wsConnectedStatusChanged(1);
//发送授权包
wsSendAuthMsg();
}
void WebsocketService::onDisconnected()
{
qDebug() << QDateTime::currentDateTime().toString("hh:mm:ss") << "ws disconnected..";
emit wsConnectedStatusChanged(0);
//重新连接服务器
connectToServer(m_url);
}
void WebsocketService::wsSendAuthMsg()
{
m_lastSendDataInSeconds = QDateTime::currentSecsSinceEpoch();
QString rawJson = "{\"toDomain\":\"Server\",\"data\":\"{\\\"type\\\":\\\"Auth\\\",\\\"data\\\":{\\\"token\\\":\\\"%1\\\"}}\"}";
QString json = rawJson.arg(MainConfig::token);
m_webSocket.sendTextMessage(json);
qDebug() << QDateTime::currentDateTime().toString("hh:mm:ss") << "wsSendAuthMsg: " << json;
}
void WebsocketService::wsSendPingMsg()
{
quint64 now = QDateTime::currentSecsSinceEpoch();
if(now - m_lastSendDataInSeconds < m_wsHeartInterval){
return;
}
m_lastSendDataInSeconds = now;
QString rawJson = "{\"toDomain\":\"Server\",\"data\":\"{\\\"type\\\":\\\"Ping\\\"}\"}";
QString json = rawJson;
m_webSocket.sendTextMessage(json);
qDebug() << QDateTime::currentDateTime().toString("hh:mm:ss") << "wsSendPingMsg: " << json;
}
void WebsocketService::sendWsAckMessage(QString ackId)
{
m_lastSendDataInSeconds = QDateTime::currentSecsSinceEpoch();
QString rawJson = "{\"toDomain\":\"Server\",\"data\":\"{\\\"type\\\":\\\"Ack\\\",\\\"data\\\":{\\\"ackId\\\":\\\"%1\\\"}}\"}";
QString json = rawJson.arg(ackId);
m_webSocket.sendTextMessage(json);
}
void WebsocketService::onTextMessageReceived(const QString &message)
{
qDebug() << QDateTime::currentDateTime().toString("hh:mm:ss") << "wsRecvMsg: " << message.toUtf8();
//解析响应中的data字段,data又是一个json字符串
QJsonParseError jerror;
QJsonDocument jdoc;
QJsonObject jobj;
jdoc = QJsonDocument::fromJson(message.toUtf8(), &jerror);
if (jerror.error != QJsonParseError::NoError || !jdoc.isObject() || !jdoc.object().contains("messageSet"))
{
qDebug() << QString::fromUtf8("ws消息错误");
return;
}
jobj = jdoc.object();
QString ackId = jobj.take("ackId").toString();
QString dataString = jobj.take("messageSet").toArray().at(0).toObject().take("data").toString();
//解析data字段
jdoc = QJsonDocument::fromJson(dataString.toUtf8(), &jerror);
if (jerror.error != QJsonParseError::NoError || !jdoc.isObject() || !jdoc.object().contains("type"))
{
qDebug() << QString::fromUtf8("ws data消息错误");
return;
}
jobj = jdoc.object();
QString notifyType = jobj.take("type").toString();
if(notifyType == "buttonStart"){
qDebug() << "buttonStart Message";
//处理消息
handleWsButtonStartMsg(jobj.take("data").toObject());
//回复ws消息
sendWsAckMessage(ackId);
}else if(notifyType == "updateStatus"){
qDebug() << "updateStatus Message";
//处理消息
handleWsUpdateStatusMsg(jobj.take("data").toObject());
//回复ws消息
sendWsAckMessage(ackId);
}else if(notifyType == "Pong"){
qDebug() << "Pong Message";
}else if(notifyType == "ChannelStatus"){
qDebug() << "Auth Message";
}
}
void WebsocketService::handleWsButtonStartMsg(QJsonObject jobj)
{
QString firstAidId = jobj.take("firstAidId").toString();
QString name = jobj.take("name").toString();
QString content = jobj.take("content").toString();
quint64 realCountdown = jobj.take("realCountdown").toInt(0) / 1000;
emit newPatientMergencyInfo(firstAidId,name,content,realCountdown);
}
void WebsocketService::handleWsUpdateStatusMsg(QJsonObject jobj)
{
QString firstAidId = jobj.take("firstAidId").toString();
QString time = jobj.take("time").toString();
QString status = jobj.take("status").toString();
emit patientMergencyStatusChanged(firstAidId,time,status);
}

38
websocketservice.h

@ -0,0 +1,38 @@
#ifndef WEBSOCKETSERVICE_H
#define WEBSOCKETSERVICE_H
#include <QObject>
#include <QtWebSockets/QWebSocket>
#include <QTimer>
#include "patientemergencyinfo.h"
class WebsocketService : public QObject
{
Q_OBJECT
public:
explicit WebsocketService(QObject *parent = 0);
void connectToServer(QString url);
void handleWsButtonStartMsg(QJsonObject jobj);
void handleWsUpdateStatusMsg(QJsonObject jobj);
void sendWsAckMessage(QString ackId);
private:
QWebSocket m_webSocket;
QString m_url;
qint64 m_lastSendDataInSeconds;
QTimer m_heartTimer;
quint32 m_wsHeartInterval;
signals:
void wsConnectedStatusChanged(int);
//void newPatientMergencyInfo(PatientEmergencyInfo *);
void newPatientMergencyInfo(QString firstAidId,QString name,QString content,quint64 realCountDownInSeconds);
void patientMergencyStatusChanged(QString firstAidId,QString time,QString status);
public slots:
void onConnected();
void onDisconnected();
void wsSendPingMsg();
void wsSendAuthMsg();
void onTextMessageReceived(const QString &message);
};
#endif // WEBSOCKETSERVICE_H
Loading…
Cancel
Save