mqtttypeconverter.h 2.79 KB
#ifndef OSDEV_COMPONENTS_MQTT_MLOGICTYPECONVERTER_H
#define OSDEV_COMPONENTS_MQTT_MLOGICTYPECONVERTER_H

// std
#include <chrono>
#include <ctime>
#include "date.h"
#include <string>

// boost
#include <boost/uuid/uuid.hpp>

#include "commondefs.h"

namespace osdev {
namespace components {
namespace mqtt {

/**
 * @brief Utility namespace to convert between mqtt common types and other frequently used types.
 */
namespace MqttTypeConverter {

/**
 * @brief Converts from MqttId to std::string.
 * @param mqttId The mqttId to convert.
 * @return The std::string with contents of the provided mqttId. Format is 12345678-9abc-def0-1234-56789abcdef0.
 */
std::string toStdString(const MqttId& mqttId);

/**
 * @brief Converts from system clock timepoint to std::string.
 * @tparam Duration std::chrono::duration instance.
 *         Duration::Period is used to determine the precision
 *         of the subsecond part of the returned ISO8601 string.
 *         Uses the duration of the StdTime type by default.
 * @param tp The timepoint to converter.
 * @return ISO8601 string representation of stdTime.
 */
template <typename Duration>
std::string toStdString(const std::chrono::time_point<std::chrono::system_clock, Duration>& tp)
{
    return date::format("%FT%T%Ez", tp);
}

/**
 * @brief Converts from std::string to MqttId.
 * @param mqttId The MqttId string to convert.
 * @return the converted string to MqttId.
 */
MqttId toMqttId(const std::string& mqttId);

/**
 * @brief Creates a descriptive string based on the specified input parameters.
 * @param str The prefix of the string.
 * @param mqttId The id of which to use the first 4 characters.
 * @return str + "-" + <first 4 characters of mqttId>
 * Example: "Unassigned-a2c4".
 */
std::string toShortGuidAppendedString(const std::string& str, const MqttId& mqttId);

/**
 * @brief Converts from PosixTime (time_t) to StdTime.
 * @param posixTime The Posix Time (time_t) to convert.
 * @return The StdTime with same value as the provided posixTime.
 */
StdTime toStdTime(const std::time_t& posixTime);

/**
 * @brief Converts from StdTime to PosixTime (time_t).
 * @param stdTime The StdTime to convert.
 * @return The PosixTime with the same value as the provided stdTime.
 */
time_t toPosixTime(const osdev::components::mqtt::StdTime& stdTime);

/**
 * @brief Converts the specified posixTimeString to an OptionalTime.
 * @param posixTimeString A posix time as string.
 * @return The converted posixTimeString.
 * @retval boost::none if the specified posixTimeString could not be converted to a StdTime.
 */
osdev::components::mqtt::OptionalTime toOptionalTime(const std::string& posixTimeString);

}       // End namespace MqttTypeConverter
}       // End namespace mqtt
}       // End namespace components
}       // End namespace osdev

#endif  // OSDEV_COMPONENTS_MQTT_MQTTTYPECONVERTER_H