LoginSignup
0
0

c++ で osc する (oscpack)

Last updated at Posted at 2023-07-11

(c++ で書けることを python で書くのは情弱だゾ to 自分)

背景

自分が c++ 弱くて、osc + c++ の公式??のサンプル↓は動かず、動かし方もあんま書いてなく、サンプルもあんまりシンプルじゃなかったので、デバッグしておれおれシンプル版にまとめてみました。

とりあえず、同じマシン内で文字列の送受信ができることをゴールにしてます。

環境

ubuntu 20.04 (on docker)

環境構築

g++をまだ入れてない場合は

sudo apt update
sudo apt install build-essential

そして、liboscpackを入れる (← これになかなかたどり着けなかった…)

sudo apt install liboscpack-dev

入れれたか確認

dpkg -l | grep liboscpack

送信側

send.cpp
#include "oscpack/osc/OscOutboundPacketStream.h"
#include "oscpack/ip/UdpSocket.h"
#include <iostream>
#include <string>

#define ADDRESS "127.0.0.1"
#define PORT 7000
#define OUTPUT_BUFFER_SIZE 1024

int main()
{
    UdpTransmitSocket transmitSocket(IpEndpointName(ADDRESS, PORT));

    while (true)
    {
        std::string input;
        std::cout << "Enter a message to send: ";
        std::getline(std::cin, input);

        if (input == "quit")
            break;

        char buffer[OUTPUT_BUFFER_SIZE];
        osc::OutboundPacketStream p(buffer, OUTPUT_BUFFER_SIZE);

        p << osc::BeginBundleImmediate
            << osc::BeginMessage("/test")
            << input.c_str() << osc::EndMessage
            << osc::EndBundle;

        transmitSocket.Send(p.Data(), p.Size());
    }

    return 0;
}

受信側

receive.cpp
#include "oscpack/osc/OscReceivedElements.h"
#include "oscpack/osc/OscPacketListener.h"
#include "oscpack/ip/UdpSocket.h"
#include <iostream>

#define PORT 7000

class ExamplePacketListener : public osc::OscPacketListener
{
protected:
    virtual void ProcessMessage(const osc::ReceivedMessage& m, const IpEndpointName& remoteEndpoint)
    {
        try
        {
            if (std::strcmp(m.AddressPattern(), "/test") == 0)
            {
                osc::ReceivedMessage::const_iterator arg = m.ArgumentsBegin();
                std::string a1 = (arg++)->AsString();
                if (arg != m.ArgumentsEnd())
                    throw osc::ExcessArgumentException();

                std::cout << "received '/test' message with arguments: " << a1 << "\n";
            }
        }
        catch (osc::Exception& e)
        {
            std::cout << "error while parsing message: " << m.AddressPattern() << ": " << e.what() << "\n";
        }
    }
};

int main()
{
    ExamplePacketListener listener;
    UdpListeningReceiveSocket s(IpEndpointName(IpEndpointName::ANY_ADDRESS, PORT), &listener);

    std::cout << "press ctrl-c to end\n";

    s.RunUntilSigInt();

    return 0;
}

コンパイル&実行!

g++ -o send send.cpp -loscpack
g++ -o receive receive.cpp -loscpack

で実行ファイルができたら、ターミナルを2つ開いておいて、./send./receive を実行!

osc.JPG

以上!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0