pws2mqtt-qt/pws2mqtt.cpp

125 lines
2.9 KiB
C++
Raw Normal View History

2024-09-10 20:34:16 +02:00
#include "pws2mqtt.h"
#include "mqtt.h"
//#include "httpserver.h"
#include <unistd.h>
#include <QtGlobal>
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <QtHttpServer/QHttpServer>
#include <QtHttpServer/QHttpServerRequest>
extern MqttClient *mqttClient;
extern Pws2mqtt *pws2mqtt;
extern QHttpServer *httpServer;
Pws2mqtt::Pws2mqtt()
{
this->init();
}
Pws2mqtt::~Pws2mqtt()
{
}
void Pws2mqtt::init()
{
debug(DEBUGMACRO, "init http server", DEBUG);
httpServer->route("/query", [this](const QHttpServerRequest &request)
{
//QString data;
//QTextStream result(&data);
debug(DEBUGMACRO, "Request body :" + request.body() , DEBUG);
/* debug(DEBUGMACRO, "Request value :" + request.query().toString() , DEBUG);
debug(DEBUGMACRO, "Request value :" + request.url().toString() , DEBUG);
for (auto pair : request.query().queryItems())
{
if (!data.isEmpty())
{
result << "\n";
}
debug(DEBUGMACRO, pair.first + "=" + pair.second, DEBUG);
}*/
this->parseData(request.body());
debug(DEBUGMACRO, "Returning 'success'", DEBUG);
//mqttClient.send_message(jsonString);
return QHttpServerResponse("text/plain", "Success\n");
});
}
void Pws2mqtt::listeningHttp()
{
//QByteArray data;
debug (DEBUGMACRO, "listening http requests", DEBUG);
const auto port = httpServer->listen(QHostAddress::Any, 5000);
if (!port)
{
debug(DEBUGMACRO, "Http Server failed to listen on a port.", ERROR);
//return 0;
}
debug(DEBUGMACRO, "Listening on port " + QString::number(port));
}
void Pws2mqtt::parseData(QByteArray data)
{
QList<QByteArray> dataList;
QString jsonString = "{";
QString deviceString = "\"device\": {\"ieeeAddress\": \"" + mqttClient->macAddress + "\", \"type\": \"" + mqttClient->type + "\", " + "\"powerSource\": \"Battery\", ";
QList<QByteArray> dataSplitted;
QString str;
uint j;
uint listSize;
bool propertyFlag = false;
bool deviceFlag = false;
QString topic;
debug(DEBUGMACRO, "Parsing Datas", DEBUG);
dataList = data.split('&');
listSize = dataList.size() - 1;
for (j=2;j<listSize;j++)
{
debug(DEBUGMACRO, dataList[j], DEBUG);
dataSplitted = dataList[j].split('=');
str = dataSplitted[0];
if (this->deviceProperties.contains(str))
{
if(deviceFlag == false)
{
deviceFlag = true;
}else
{
deviceString.append(", ");
}
deviceString.append("\"" + str + "\": ");
deviceString.append(addValue(dataSplitted[1]));
}else
{
if(propertyFlag == false)
{
propertyFlag = true;
}else
{
jsonString.append(", ");
}
jsonString.append("\"" + str + "\": ");
jsonString.append(addValue(dataSplitted[1]));
//mqttClient.send_message(topic, jsonString);
}
}
jsonString = jsonString +", " + deviceString + "}}";
mqttClient->send_message(jsonString);
debug(DEBUGMACRO, "sent => " + jsonString, DEBUG);
debug(DEBUGMACRO, "parseData: Returning", DEBUG);
//return jsonString;
}