Grazie mrdebug,
sono arrivato ad un risultato.
Posto il codice a beneficio di tutti gli utenti, anche se c'è un'ultima cosa che non torna.
MAIN.CPP
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "myudp.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<MyUDP>("MyUDP", 1, 0, "MyUDP");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
MYUDP.H
#ifndef MYUDP_H
#define MYUDP_H
#include <QObject>
#include <QUdpSocket>
class MyUDP : public QObject
{
Q_OBJECT
Q_PROPERTY(QByteArray type READ type WRITE setType NOTIFY typeChanged)
public:
explicit MyUDP(QObject *parent = 0);
void SayHello();
QByteArray type();
void setType(const QByteArray &t);
signals:
void typeChanged();
public slots:
void readyRead();
private:
QUdpSocket *socket;
QByteArray _type;
};
#endif // MYUDP_H
MYUDP.C
#include "myudp.h"
MyUDP::MyUDP(QObject *parent) : QObject(parent)
{
socket = new QUdpSocket(this);
socket->bind(1129, QUdpSocket::ShareAddress);
connect(socket,SIGNAL(readyRead()),this, SLOT(readyRead()));
}
// send message in client mode
void MyUDP::SayHello()
{
QByteArray Data;
Data.append("test message");
socket->writeDatagram(Data,QHostAddress::LocalHost,5824);
}
void MyUDP::readyRead()
{
QByteArray Buffer;
Buffer.resize(socket->pendingDatagramSize());;
QHostAddress sender;
quint16 senderPort;
socket->readDatagram(Buffer.data(),Buffer.size(), &sender, &senderPort);
qDebug()<< "Message size:" << Buffer.size();
setType(Buffer);
}
QByteArray MyUDP::type()
{
return _type;
}
void MyUDP::setType(const QByteArray &t)
{
_type = t;
emit typeChanged();
}
MAIN.QML
import QtQuick 2.0
import QtQuick.Controls 2.2
import "main.js" as SpkScript
import MyUDP 1.0
ApplicationWindow
{
id: window
visible: true
title: qsTr("AESA.Monitor")
MyUDP
{
id:myUdp
onTypeChanged:
{
console.log("[QML]Msg:" + type)
}
}
}
L'esempio funziona in ricezione. Il pacchetto ricevuto è contenuto in "type" (lato QML).
Se si fa una console.log(typeof type) il risultato è "object".
Se si ricevono caratteri stampabili va tutto bene. Ho provato il codice seguente che trasforma type in stringa permettendo l'uso di tutte le funzioni relative:
var m=type.toString();
if(m.slice(0,4)==="col=")
{
ecc.ecc...
il problema (nel mio caso) è che ricevo dati binari, per cui la conversione a stringa non funziona più bene (al primo carattere non stampabile la stringa si interrompe).
Ho provato a ricavare i singoli byte dalla variabile type ma senza successo:
type[0] ritorna "not defined"
type.charCodeAt(0) non funziona (non è una stringa)
ci vorrebbe una conversione ad array ma non so come fare.
grazie per tutti i suggerimenti
ciao