UdpIODevice.cc 1.46 KB
Newer Older
Willian Galvani's avatar
Willian Galvani committed
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
Willian Galvani's avatar
Willian Galvani committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "UdpIODevice.h"
#include <algorithm>

UdpIODevice::UdpIODevice(QObject *parent) : QUdpSocket(parent)
{
    // this might cause data to be available only after a second readyRead() signal
    connect(this, &QUdpSocket::readyRead, this, &UdpIODevice::_readAvailableData);
}

bool UdpIODevice::canReadLine() const
{
    return _buffer.indexOf('\n') > -1;
}

qint64 UdpIODevice::readLineData(char *data, qint64 maxSize)
{
    int length = _buffer.indexOf('\n') + 1; // add 1 to include the '\n'
    if (length == 0) {
        return 0;
    }
    length = std::min(length, static_cast<int>(maxSize));
    // copy lines to output
    std::copy(_buffer.data(), _buffer.data() + length, data);
    // trim buffer to remove consumed line
    _buffer = _buffer.right(_buffer.size() - length);
    // return number of bytes read
    return length;
}

void UdpIODevice::_readAvailableData() {
    while (hasPendingDatagrams()) {
        int previousSize = _buffer.size();
        _buffer.resize(static_cast<int>(_buffer.size() + pendingDatagramSize()));
        readDatagram((_buffer.data() + previousSize), pendingDatagramSize());
    }
}