udphandler.cpp 2.49 KB
#include "udphandler.h"

#include <QtDebug>

#define IPC_UDP_SYS_HOST    "127.0.0.1"
#define IPC_UDP_SYS_PORT    4001
#define IPC_UDP_GUI_PORT    4000

typedef struct {
    int header;
    char body[];
} STRUCT_PACK packet_t;

UdpHandler::UdpHandler(QObject *parent) : QObject(parent)
{

}

bool UdpHandler::init()
{
    sock = new QUdpSocket(this);
    if (!sock->bind(IPC_UDP_GUI_PORT))
        return false;

    connect(sock, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));

    return true;
}

void UdpHandler::readPendingDatagrams()
{
    while (sock->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(sock->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        sock->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        processDatagram(datagram);
    }
}

void UdpHandler::processDatagram(QByteArray &datagram)
{
    qDebug() << "Received";
    sock->writeDatagram(datagram, QHostAddress("192.168.4.191"), 4000);
    packet_t *packet = (packet_t *) datagram.data();
    switch (packet->header)
    {
    case HDR_OVEN_CONTROL:
        processControl((oven_control_t *) packet->body);
        break;
    case HDR_OVEN_STATE:
        processState((oven_state_t *) packet->body);
        break;
    case HDR_ERROR_CODE:
        break;
    }
}

void UdpHandler::processControl(oven_control_t *control)
{
    if (memcmp(&this->control, control, sizeof(this->control)))
    {
        memcpy(&this->control, control, sizeof(this->control));
        emit changed();
    }
}

void UdpHandler::processState(oven_state_t *state)
{
    if (memcmp(&this->state, state, sizeof(this->state)))
    {
        memcpy(&this->state, state, sizeof(this->state));
        emit changed();
    }
}

void UdpHandler::turnOn(int target)
{
    sendCommand(CMD_ONOFF, target, SWITCH_ON);
}

void UdpHandler::turnOff(int target)
{
    sendCommand(CMD_ONOFF, target, SWITCH_OFF);
}

void UdpHandler::set(int target, int value)
{
    sendCommand(CMD_VALUE, target, value);
}

void UdpHandler::sendCommand(int cmd, int target, int value)
{
    command_t command = { cmd, target, value };
    qDebug() << "Send" << cmd << target << value;
    sock->writeDatagram((const char *) &command, sizeof(command), QHostAddress(IPC_UDP_SYS_HOST), IPC_UDP_SYS_PORT);
}

void UdpHandler::fillControl(oven_control_t &container)
{
    memcpy(&container, &control, sizeof(control));
}

void UdpHandler::fillData(oven_state_t &container)
{
    memcpy(&container, &state, sizeof(state));
}