Squashed 'libs/CommService/' content from commit 7ccc0fc

git-subtree-dir: libs/CommService
git-subtree-split: 7ccc0fce88bbc5969df060058cf0fb57abe3bcf9
This commit is contained in:
Henry Winkel
2022-09-15 09:53:53 +02:00
commit cc67e4840f
799 changed files with 179487 additions and 0 deletions

View File

@@ -0,0 +1,116 @@
#ifndef COMMSERVICE
#define COMMSERVICE
#include <CommService/Message.hpp>
#include <CommService/ThreadsafeQueue.hpp>
#include <atomic>
#include <cstdint>
#include <memory>
#include <mutex>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <thread>
#include <unistd.h>
#include <sys/select.h>
#include <string>
#include <vector>
namespace CommService {
class LocalUDPClients{
public:
unsigned short port;
std::uint16_t id;
};
class CommService {
private:
/// device id
std::uint16_t deviceID_;
/// participant MajorType
deviceMajorType majorType_;
/// minor Type
std::string minorType_;
/// the IP Address to send messages to
std::string dstIp;
/// the local source IP Address
std::string srcIp;
/// the udp port on which to broadcast and receive messages
unsigned short broadcastPort = 0;
/// the port we are listing on for messages, should normally be broadcastPort, but...
unsigned short localPort = 0;
/// the network socket to work on
int inetSocket = -1;
/// vector of local client ports we forward messages to
std::vector<LocalUDPClients> clients;
/// mutex for exclusive access to the clients vector
std::mutex mutexClients;
/// variable for holding the receive thread identifier
std::thread receiveThread;
/// variable indicating if the receiveThread should be stopped
std::atomic<bool> stopReceiveThread;
std::atomic<bool> receiving;
/// show if the service is connected or not
std::atomic<bool> connected;
std::mutex mutex;
std::shared_ptr<ThreadsafeQueue<Message>> ReceivingMessageQueue;
/// attribute identifying this service as a gateway and all packets should be forwarded
bool gateway = false;
void setGateway(bool);
public:
CommService(std::string dst,std::string src, std::uint16_t id, deviceMajorType majorType, std::string minorType, unsigned short dstPort ):
dstIp(dst),srcIp(src),majorType_(majorType),minorType_(minorType),broadcastPort(dstPort),stopReceiveThread(false),deviceID_(id){}
~CommService();
void connect();
void disconnect();
void publish(Message m);
void receiveThreadFunc();
void asyncReceive();
void processMsg(std::vector<unsigned char> *m);
void start();
void stop();
std::shared_ptr<ThreadsafeQueue<Message>> getReceivedMessageQueue();
};
};
#endif

View File

@@ -0,0 +1,241 @@
#ifndef NETWORKBUFFCONVERT
#define NETWORKBUFFCONVERT
#include <cstring>
#include <stdexcept>
#include <vector>
#include <string>
namespace CommService {
class Convert{
public:
/*
* @brief template function to byte swap int/uint datatypes - used for endianess conversion
*
* @param v - pointer to a variable of some int/uint datatype - in place byte swapped
*/
template <typename T>
static void swapBytes(T *v) {
for (unsigned int i = 0; i < sizeof(T)/2; ++i)
{
std::swap(((char *)v)[i], ((char *)v)[sizeof(T)-1-i]);
}
}
/**
* @brief function to convert a std::vector<unsigned char> to an simple datatype
*
* this is the partner function to fromSimpleToByteArray.
* it extracts the simple datatype like int, double, etc. from the vector and
* returns it
*
* @param v - the vector to convert to a simple datatype
* @return simple datatype
* @throw std::invalid_argument: "the bytevector is too small to fit the datatype"
*/
template<typename T>
static T fromByteArrayToSimple(std::vector<unsigned char> &bytes)
{
T convVariable;
if(bytes.size() < sizeof(T))
{
throw(std::invalid_argument(std::string(__FILE__) + ":" + std::string(__PRETTY_FUNCTION__) + ":" + std::to_string(__LINE__) + ": the bytevector is too small to fit the datatype"));
}
std::memcpy(reinterpret_cast<unsigned char*>(&convVariable),bytes.data(),sizeof(T));
#ifndef IS_BIG_ENDIAN
swapBytes(&convVariable);
#endif
return std::move(convVariable);
}
/**
* @brief template for converting of simple datatypes to a byte_array, including endianness conversion to big endian
*
* @param variable - the variable to convert to a byte vector, needs to be int/uint datatype
*
* @return the std::vector<unsigned char>
*/
template<typename T>
static std::vector<unsigned char> fromSimpleToByteArray(T &variable)
{
std::vector<unsigned char> bytes;
bytes.clear();
bytes.resize(sizeof(T));
#ifndef IS_BIG_ENDIAN
T convVariable = variable;
swapBytes(&convVariable);
std::memcpy(bytes.data(),reinterpret_cast<const unsigned char*>(&convVariable),sizeof(T));
#else
std::memcpy(bytes.data(),reinterpret_cast<const unsigned char*>(&variable),sizeof(T));
#endif
return bytes;
}
/**
* @brief function to convert a container of a simple datatype to a std::vector<unsigned char>
*
* this is the partner function to fromByteArrayToSimpleContainer.
* the number of container elements is prepended to the std::vector and the simple datatype
* elements follow.
*
* @param data - the container of a simple datatype
*
* @return the std::vector<unsigned char>;
*/
template<class T>
static std::vector<unsigned char> fromSimpleContainerToByteArray(T &data)
{
std::vector<unsigned char> bytes;
std::vector<unsigned char> convert;
uint32_t size=data.size();
bytes=fromSimpleToByteArray(size);
for(auto it = data.begin(); it!=data.end(); ++it)
{
convert=fromSimpleToByteArray(*it);
bytes.insert(std::end(bytes), std::begin(convert), std::end(convert));
}
return bytes;
}
/**
* @brief function to convert a std::vector<unsigned char> to a container of simple datatype elements
*
* this is the partner function to fromSimpleContainerToByteArray. It takes the
* first 4 byte of the vector as an uint32_t element count and parses the all the elements
* from the vector.
*
* @param v - the vector to convert to a container of simple datatype elements
*
* @return the container
*/
template<class T, typename S>
static T fromByteArrayToSimpleContainer(std::vector<unsigned char> &v)
{
T data;
uint32_t size = fromByteArrayToSimple<S>(v);
v.erase(v.begin(), v.begin()+sizeof(size));
for(uint32_t i=0; i<size; i++)
{
S convert = fromByteArrayToSimple<S>(v);
v.erase(v.begin(), v.begin()+sizeof(convert));
data.push_back(convert);
}
return std::move(data);
}
/**
* @brief function to convert a std::string to an std::vector<unsigned char>
*
* for converting the string, first the length of the string is converted as
* an uint32_t into the std::vector to be able to correctly parse the string
* in a larger vector.
*
* @param variable - the std::string to convert
*
* @return the std::vector<unsigned char>
*/
static std::vector<unsigned char> fromStringToByteArray(const std::string &variable)
{
std::vector<unsigned char> bytes;
uint32_t size=variable.length();
bytes=fromSimpleToByteArray(size);
bytes.insert(std::end(bytes),std::begin(variable), std::end(variable));
return bytes;
}
/**
* @brief function to convert a std::vector<unsigned char> to an std::string
*
* this is the partner function to fromStringToByteArray. It takes the
* first 4 byte of the vector as an uint32_t string length identifier and
* uses the following length chars as the string
*
* @param v - the vector to convert to a string
* @return the string read from the vector
* @throw std::invalid_argument: "vector too short for <X> chars"
*/
static std::string fromByteArrayToString(std::vector<unsigned char> &v)
{
uint32_t length=fromByteArrayToSimple<uint32_t>(v);
if (v.size()-sizeof(uint32_t) < length)
{
throw(std::invalid_argument(std::string(__FILE__) + ":" + std::string(__PRETTY_FUNCTION__) + ":" + std::to_string(__LINE__) + ": vector too short for " + std::to_string(length) + " chars"));
}
std::string str(v.begin()+sizeof(uint32_t), v.begin()+sizeof(uint32_t)+length) ;
return str;
}
/**
* @brief function to convert a container of strings to a std::vector<unsigned char>
*
* @param data - the container of std::string
*
* @return the std::vector<unsigned char>
*/
template<class T>
static std::vector<unsigned char> fromStringContainerToByteArray(T &data)
{
std::vector<unsigned char> bytes;
std::vector<unsigned char> convert;
uint32_t size=data.size();
bytes=fromSimpleToByteArray(size);
for(auto it = data.begin(); it!=data.end(); ++it)
{
convert=fromStringToByteArray(*it);
bytes.insert(std::end(bytes), std::begin(convert), std::end(convert));
}
return bytes;
}
/**
* @brief function to convert a std::vector<unsigned char> to a container of strings
*
* @param data - the container of std::string
*
* @return the std::vector<unsigned char>
*/
template<class T>
static T fromByteArrayToStringContainer(std::vector<unsigned char> &v)
{
T data;
uint32_t size = fromByteArrayToSimple<uint32_t>(v);
v.erase(v.begin(), v.begin()+sizeof(size));
for(uint32_t i=0; i<size; i++)
{
std::string convert = fromByteArrayToString(v);
data.push_back(convert);
}
return std::move(data);
}
};
};
#endif

View File

@@ -0,0 +1,96 @@
#ifndef MESSAGE
#define MESSAGE
#include <CommService/transmittable.hpp>
#include <string>
#include <vector>
namespace CommService {
enum messageTopic : std::uint16_t {
/// udp client joins
LOCAL_JOIN,
/// local udp clients leave
LOCAL_LEAVE,
/// remote participant joins the sim
JOIN,
/// remote participant leave the sim
LEAVE,
/// sends id to participant
ID_MESSAGE
};
enum deviceMajorType : std::uint16_t {
ID_SERVICE,
GATEWAY,
CIVIL_SHIP,
WAR_SHIP,
RADAR,
SONAR,
WEAPON
};
class Message : public transmittable{
public:
// the device id of the device/endpoint sending this Message
std::uint16_t sourceID;
/// the major type of the device/endpoint transmitting this message
deviceMajorType srcMajorType;
/// the minor type of the device/endpoint transmitting this message
std::string srcMinorType;
/// which topic does this message have ? helps identifying the transmitted datatype
messageTopic topic;
Message();
/**
* @brief Constructor for generationg a Message object from a received std::vector<unsiged char>
*
* @param v - the std::vector<unsigned char> representing a message object
*/
Message(std::vector<unsigned char>);
/**
* @brief Copy constructor of the Message class
*
* creates a copy of the object, including copies of all data
*
* @param obj - the object from which to copy everything
*/
Message(const Message &obj);
void setData(const transmittable &d){data=d.toByteVector();}
/**
* @brief converts the whole message information into a byte vector
*
* all information of the message class is converted into a byte vector for transmission
* through any kind of network.
*
* @param payload - returns the byte vector by call by reference
*/
std::vector<unsigned char> toByteVector() const override;
/**
* @brief return the raw byte vector of the data object, required for data reception
*
* @return the std::vector<unsigned char>
*/
std::vector<unsigned char> getRawData() const {return data;}
private:
std::vector<unsigned char> data;
};
};
#endif

View File

@@ -0,0 +1,62 @@
#ifndef __PAYLOADS_JOIN__
#define __PAYLOADS_JOIN__
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/**
* @file
* @brief main header file for the BC::Payloads::HotPlugJoin payload
* @author Dominik Meyer <dmeyer@hsu-hh.de>
* @date 2019-02-03
* @copyright 2019 no yet defined
*/
#include <CommService/transmittable.hpp>
#include <cstdint>
#include <vector>
namespace CommService
{
namespace PayLoads
{
/**
* @brief class representing the payload of a HotPlugJoin message
*
* the HotPlugJoin messages is transmitted by every PubSub Service after connection
* has been established to the underlying network/transport layer.
* It provides information about the type of service, the id and the underlying
* network/transport layer addresses.
*
*/
class Join : public transmittable
{
public:
Join()=default;
/**
* @brief constructor to recreate the HotPlugJoin payload from a a std::vector<unsigned char>
*/
explicit Join(std::vector<unsigned char> v);
/// the address of the underlying network layer used to join the network
unsigned char networkLayerAddress[16];
/// the address of the underlying transport layer used to join the network
std::uint32_t transportLayerAddress;
/**
* @brief converts the information of the class (the attributes) to a byte vector
*
* @param byteVector - returns a std::vector of bytes representing the class
*/
std::vector<unsigned char> toByteVector() const override;
};
}; //namespace Payloads
}; //namespace BC
#endif

View File

@@ -0,0 +1,50 @@
#ifndef __PAYLOADS_LEAVE__
#define __PAYLOADS_LEAVE__
#include <CommService/transmittable.hpp>
#include <cstdint>
#include <vector>
namespace CommService
{
namespace PayLoads
{
/**
* @brief class representing the payload of a HotPlugLeave message
*
* the HotPlugLeave messages is transmitted by every PubSub Service before disconnecting
* from the network.
* It provides information about the type of service, the id and the underlying
* network/transport layer addresses.
*
*/
class Leave : public transmittable
{
public:
Leave()=default;
/**
* @brief constructor to recreate the HotPlugJoin payload from a a std::vector<unsigned char>
*/
explicit Leave(std::vector<unsigned char> v);
/// the address of the underlying network layer used to join the network
unsigned char networkLayerAddress[16];
/// the address of the underlying transport layer used to join the network
uint32_t transportLayerAddress;
/**
* @brief converts the information of the class (the attributes) to a byte vector
*
* @param byteVector - returns a std::vector of bytes representing the class
*/
std::vector<unsigned char> toByteVector() const override;
};
}; //namespace Payloads
}; //namespace BC
#endif

View File

@@ -0,0 +1,62 @@
#ifndef __PAYLOADS_PING__
#define __PAYLOADS_PING__
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/**
* @file
* @brief main header file for the BC::Payloads::Ping payload
* @author Dominik Meyer <dmeyer@hsu-hh.de>
* @date 2019-02-06
* @copyright 2019 no yet defined
*/
#include <CommService/transmittable.hpp>
#include <cstdint>
#include <vector>
#include <random>
namespace CommService
{
namespace PayLoads
{
/**
* @brief class representing the payload of a Ping message
*
* the Ping messages is transmitted can be published to all or individual nodes.
* these nodes will answer with a Pong message
*
*/
class Ping : public transmittable
{
public:
Ping();
/**
* @brief constructor to recreate the HotPlugJoin payload from a a std::vector<unsigned char>
*/
explicit Ping(std::vector<unsigned char> v);
/// message id uniqly identifying one ping message
uint64_t messageID;
/// the sequence number of the ping
uint64_t sequenceNr;
/// the local clock ticks
uint64_t pingTime;
/**
* @brief converts the information of the class (the attributes) to a byte vector
*
* @param byteVector - returns a std::vector of bytes representing the class
*/
std::vector<unsigned char> toByteVector() const override;
};
}; //namespace Payloads
}; //namespace BC
#endif

View File

@@ -0,0 +1,59 @@
#ifndef __LIBBC_BC_PAYLOADS_PONG_HPP__
#define __LIBBC_BC_PAYLOADS_PONG_HPP__
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/**
* @file
* @brief main header file for the BC::Payloads::Pong payload
* @author Dominik Meyer <dmeyer@hsu-hh.de>
* @date 2019-02-06
* @copyright 2019 no yet defined
*/
#include <CommService/transmittable.hpp>
#include <cstdint>
#include <vector>
namespace CommService
{
namespace PayLoads
{
/**
* @brief class representing the payload of a Pong message
*
* the Pong messages is the reply to a ping message.
*
*/
class Pong : public transmittable
{
public:
Pong()=default;
/**
* @brief constructor to recreate the HotPlugJoin payload from a a std::vector<unsigned char>
*/
explicit Pong(std::vector<unsigned char> v);
/// message id uniqly identifying one ping message
uint64_t pingMessageID;
/// ping transmission time
int pingTransmissionTime;
/// the sequence number of the ping
uint64_t sequenceNr;
/**
* @brief converts the information of the class (the attributes) to a byte vector
*
* @param byteVector - returns a std::vector of bytes representing the class
*/
std::vector<unsigned char> toByteVector() const override;
};
}; //namespace Payloads
}; //namespace BC
#endif

View File

@@ -0,0 +1,47 @@
#include <optional>
#include <queue>
#include <mutex>
template<typename T>
class ThreadsafeQueue {
std::queue<T> queue_;
mutable std::mutex mutex_;
// Moved out of public interface to prevent races between this
// and pop().
bool empty() const {
return queue_.empty();
}
public:
ThreadsafeQueue() = default;
ThreadsafeQueue(const ThreadsafeQueue<T> &) = delete ;
ThreadsafeQueue& operator=(const ThreadsafeQueue<T> &) = delete ;
ThreadsafeQueue(ThreadsafeQueue<T>&& other) {
std::lock_guard<std::mutex> lock(mutex_);
queue_ = std::move(other.queue_);
}
virtual ~ThreadsafeQueue() { }
unsigned long size() const {
std::lock_guard<std::mutex> lock(mutex_);
return queue_.size();
}
std::optional<T> pop() {
std::lock_guard<std::mutex> lock(mutex_);
if (queue_.empty()) {
return {};
}
T tmp = queue_.front();
queue_.pop();
return tmp;
}
void push(const T &item) {
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(item);
}
};

View File

@@ -0,0 +1,31 @@
#ifndef __TRANSMITTABLE__
#define __TRANSMITTABLE__
#include <vector>
#include <functional>
namespace CommService
{
/**
* @brief abstract class providing the interface for classes being transmittable through a network
*
* the developer has to make sure that the correct endianess is used in the toByteVector function
* and in the Factory for each Class
*/
class transmittable
{
public:
/**
* @brief converts the information of the class (the attributes) to a byte vector
*
* @param byteVector - returns a std::vector of bytes representing the class
*/
virtual std::vector<unsigned char> toByteVector() const = 0;
};
};
#endif