ModbusConnections.h 2.79 KB
/****************************************************************************
 * Copyright (c) 2022 Priva B.V.
 ****************************************************************************/
#pragma once

// Flexblox
#include "IModbusAdapter.h"
#include "ModbusAdapter.h"

// std
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>

using AdapterList = std::vector<std::shared_ptr<IModbusAdapter>>;

class ModbusConnections
{
public:
    /*!
     * \brief ModbusConnections
     */
    explicit ModbusConnections();

    /*!
     * \brief ~ModbusConnections
     */
    virtual ~ModbusConnections();

    /*!
     * \brief CreateConnection
     * \param config
     * \return
     */
    bool    CreateConnection( const ConnectionConfig &config );

    /*!
     * \brief DeleteConnection
     * \param portName
     * \param endpoint
     * \return
     */
    bool    DeleteConnection( const ConnectionPort portName, const std::string &endpoint = std::string() );

    /*!
     * \brief ConnectionCount
     * \return
     */
    int ConnectionCount();

    /*!
     * \brief getConnection
     * \param portName
     * \param endpoint
     * \return
     */
    std::shared_ptr<IModbusAdapter> getConnection( const ConnectionPort portName, const std::string &endpoint = std::string() );

    // Convenient functions
    /*!
     * \brief getConnection
     * \param portName
     * \param ipAddress
     * \param tcpPortNumber
     * \return
     */
    std::shared_ptr<IModbusAdapter> getConnection( const ConnectionPort portName, const std::string &ipAddress, int tcpPortNumber );

    /*!
     * \brief getConnections
     * \return
     */
    AdapterList getConnections();

private:
    /*!
     * \brief connectionExist
     * \param portName
     * \param endpoint
     * \return
     */
    std::shared_ptr<IModbusAdapter> connectionExist( const ConnectionPort portName, const std::string &endpoint = std::string() );

    /*!
     * \brief createEndPoint
     * \param ipAddress
     * \param portNumber
     * \return
     */
    std::string createEndPoint( const std::string &ipAddress, int portNumber );

    /*!
     * \brief createEndPoint
     * \param config
     * \return
     */
    std::string createEndPoint( const ConnectionConfig &config );

private:
    std::mutex m_mapSerialMutex;                                                        ///< Mutex protecting the serialmap
    std::mutex m_mapTcpMutex;                                                           ///< Mutex protecting the TCPmap
    std::unordered_map<ConnectionPort, std::shared_ptr<IModbusAdapter>> m_mapSerial;    ///< Unordered map holding the Modbus connections By PortName
    std::unordered_map<std::string, std::shared_ptr<IModbusAdapter>>    m_mapTcp;       ///< Unordered map holding the Modbus connections By tcp://endpoint:port
};