LED-BOARD/simulation/VirtualLedBoard/udpserver.cpp

85 lines
2.5 KiB
C++
Raw Permalink Normal View History

2023-08-13 22:38:07 +02:00
#include "udpserver.h"
2023-08-15 13:38:07 +02:00
#include "settings.h"
2023-08-13 22:38:07 +02:00
#include <QUdpSocket>
#include <QNetworkDatagram>
#include <ostream>
#include "mainwindow.h"
2023-08-13 22:38:07 +02:00
#define UDP_IMAGE_PORT 4242
2023-08-17 21:51:03 +02:00
UdpLedServer::UdpLedServer (QObject *parent, MainWindow *window)
2023-08-14 13:53:34 +02:00
: QObject(parent)
2023-08-13 22:38:07 +02:00
{
initSocket();
connect(this,
&UdpLedServer::changeLEDstate,
2023-08-17 21:51:03 +02:00
window,
&MainWindow::setLED);
connect(this,
&UdpLedServer::updatePanelContent,
2023-08-17 21:51:03 +02:00
window,
&MainWindow::updatePanel);
2023-08-17 21:51:03 +02:00
for(int x=0; x < (PANEL_WIDTH * MAXIMUM_PANELSIZE); x++) {
for(int y=0; y < PANEL_HEIGHT; y++) {
changeLEDstate(x, y);
}
}
updatePanelContent();
2023-08-13 22:38:07 +02:00
}
2023-08-14 13:53:34 +02:00
void UdpLedServer ::initSocket()
2023-08-13 22:38:07 +02:00
{
this->mUdpSocket = new QUdpSocket(this);
this->mUdpSocket->bind(QHostAddress::LocalHost, UDP_IMAGE_PORT);
connect(this->mUdpSocket, &QUdpSocket::readyRead,
2023-08-14 13:53:34 +02:00
this, &UdpLedServer ::readPendingDatagrams);
2023-08-13 22:38:07 +02:00
}
2023-08-14 13:53:34 +02:00
void UdpLedServer ::readPendingDatagrams()
2023-08-13 22:38:07 +02:00
{
while (this->mUdpSocket->hasPendingDatagrams()) {
QNetworkDatagram datagram = this->mUdpSocket->receiveDatagram();
processTheDatagram(datagram);
}
}
2023-08-14 13:53:34 +02:00
void UdpLedServer::processTheDatagram(QNetworkDatagram datagram) {
2023-08-15 13:38:07 +02:00
if (datagram.isValid() && datagram.data().length() == PACKET_LENGTH) {
qInfo("Received regular datagram.");
uint8_t brightness = datagram.data().at(PACKET_INDEX_BRIGHTNESS);
int currentIndex = PACKET_INDEX_PANEL0;
uint16_t mask = 1;
2023-08-17 22:19:12 +02:00
for(int y=0; y < PANEL_HEIGHT; y++) {
for(int x=0; x < (PANEL_WIDTH * MAXIMUM_PANELSIZE); x++) {
if (datagram.data().at(currentIndex) & mask) {
this->changeLEDstate(x, y);
2023-08-17 21:51:03 +02:00
qDebug() << x << "x" << y << " set";
}
mask = (mask << 1);
if (mask >= 256) {
mask = 1;
currentIndex++;
}
}
}
this->updatePanelContent();
qDebug() << "Received datagram:" << brightness;
} else if (datagram.isValid() && datagram.data().length() != PACKET_LENGTH) {
qDebug("Received status-check datagram.");
//socket = new QUdpSocket(this);
this->mUdpSocket->writeDatagram(datagram.data(), sizeof(datagram.data()), datagram.senderAddress(), datagram.senderPort());
//this->mUdpSocket->writeDatagram(datagram);
qDebug("Returned datagram");
} else {
qDebug("Received invalid datagram.");
2023-08-13 22:38:07 +02:00
}
}