Monogram API
Search…
⌃K

C++ UDP Example

The easiest way to connect to Monogram from C++ is via UDP sockets. The example uses the Qt framework's UDP network classes.

Setup

Add your configuration bundle to Monogram Creator. Read the Guide to learn how.
Specify a UDP connection in your config.json. We use port 4001 here as an example but you should make this unique to your application.
{
"id": "com.example.myapp",
"name": "MyApp",
"connection": [
{
"type": "udp", "port": 4001
}
]
}
Monogram forwards messages to port 4001 for your application.
Note: Some error checking has been omitted.

Implementation

monogram.h

#ifndef MONOGRAM_H
#define MONOGRAM_H
#include <QUdpSocket>
class Monogram : public QUdpSocket
{
Q_OBJECT
public:
enum OperationType {
PULSE,
NUDGE,
SET
};
struct Message {
QString input;
QList<double> params;
OperationType operation;
};
explicit Monogram(quint16 port);
signals:
void messageReceived(const Message &);
void error(const QString &);
private:
quint16 port;
void processDatagram(const QByteArray &datagram);
private slots:
void readPendingDatagrams();
};
#endif // MONOGRAM_H

monogram.cpp

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include "monogram.h"
Monogram::Monogram(quint16 port): QUdpSocket(), port(port) {
bind(QHostAddress::LocalHost, port);
// Listen for new network messages
connect(this, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
void Monogram::readPendingDatagrams() {
while (hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(static_cast<int>(pendingDatagramSize()));
qint64 bytesRead = readDatagram(datagram.data(), datagram.size());
if (bytesRead <= 0) continue; // Invalid data
processDatagram(datagram);
}
}
void Monogram::processDatagram(const QByteArray &datagram) {
QJsonObject json = QJsonDocument::fromJson(datagram).object();
Message message;
message.operation = PULSE;
message.input = json["input"].toString();
QString operation = json["operation"].toString();
QJsonArray params = json["params"].toArray();
for (int i = 0; i < params.count(); i++) {
QJsonValue param = params[i];
message.params.append(params[i].toDouble());
}
if (operation.length() == 1) {
switch (operation[0].toLatin1()) {
case '+':
message.operation = NUDGE;
break;
case '=':
message.operation = SET;
break;
default:
message.operation = PULSE;
}
}
emit messageReceived(message);
}

Usage

Specify port 4001 when initializing the Monogram class.
#include <QGuiApplication>
#include "monogram.h"
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
Monogram monogram(4001); // use a unique port number
QObject::connect(&monogram, &Monogram::messageReceived, [=](Monogram::Message message) {
if (message.operation == Monogram::SET) {
setParamTo(message.input, message.params[0]);
} else if (message.operation == Monogram::NUDGE) {
nudgeParamBy(message.input, message.params[0]);
} else {
execAction(message.input);
}
});
return app.exec();
}