This repository has been archived on 2024-06-03. You can view files and clone it, but cannot push or open issues or pull requests.
app/buzzerconn.cpp

94 lines
2.4 KiB
C++

#include "buzzerconn.h"
BuzzerConn::BuzzerConn(QObject *parent) : QObject(parent)
{
this->networkManager = new QNetworkAccessManager();
connect();
}
bool BuzzerConn::connect()
{
QList<double> times = gettimes();
if(times[0] == 200.0){
this->connected = true;
calcoffset();
calcoffset();
calcoffset();
return(true);
}
else{
return(false);
}
}
void BuzzerConn::calcoffset()
{
QList<double> times = gettimes();
QDateTime * date = new QDateTime;
double offset = date->currentMSecsSinceEpoch() - times[2];
this->latest_offsets.append(offset);
double mem = 0;
for(int i=0;i<latest_offsets.length();i++){
qDebug()<<latest_offsets[i];
mem += latest_offsets[i];
}
this->offset = mem / double(latest_offsets.length());
}
QList<double> BuzzerConn::gettimes()
{
QList<double> times;
ReturnData_t ret = senddata(QUrl("http://192.168.4.1"));
times.append(double(ret.status_code));
if(ret.status_code == 200){
qDebug()<<ret.text;
ret.text.replace("\n","");
ret.text.replace("\r","");
QStringList times_cache = ret.text.split("<br>");
times.append(times_cache[0].toDouble());
times.append(times_cache[1].toDouble());
return(times);
}
else{
return(times);
}
}
ReturnData_t BuzzerConn::senddata(QUrl serviceUrl)
{
ReturnData_t ret; //this is a custom type to store the returned data
// Call the webservice
QNetworkRequest request(serviceUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader,
"application/x-www-form-urlencoded");
//set ssl configuration
//send a POST request with the given url and data to the server
QUrlQuery pdata;
QNetworkReply* reply;
reply = this->networkManager->post(request, pdata.toString(QUrl::FullyEncoded).toUtf8());
//wait until the request has finished
QEventLoop loop;
loop.connect(this->networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(quit()));
loop.exec();
//get the status code
QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
ret.status_code = status_code.toInt();
if(ret.status_code == 0){ //if tehstatus code is zero, the connecion to the server was not possible
ret.status_code = 444;
}
//get the full text response
ret.text = QString::fromUtf8(reply->readAll());
//return the data
return(ret);
}