Select Git revision
SmartOpcServer.cpp

Armin Co authored
SmartOpcServer.cpp 2.99 KiB
///
#include "SmartOpcServer.hpp"
using namespace OpcUa;
const char* k_opc_server_url = "opc.tcp://localhost:4840/opcua/smart-grid-model";
class SubClientTime : public SubscriptionHandler
{
public:
SubClientTime(SmartGridModel &model)
: m_model{model}{}
private:
void DataChange(uint32_t handle, const Node &node, const Variant &val, AttributeId attr) override
{
auto v = val.As<int>();
m_model.set_time(v);
}
SmartGridModel &m_model;
};
class SubClientProductionEnabled : public SubscriptionHandler
{
public:
SubClientProductionEnabled(SmartGridModel &model) : m_model{model}{}
private:
void DataChange(uint32_t handle, const Node &node, const Variant &val, AttributeId attr) override
{
auto v = val.As<bool>();
m_model.set_producing_state(v);
}
SmartGridModel &m_model;
};
class SubClientSimModeEnabled : public SubscriptionHandler
{
public:
SubClientSimModeEnabled(SmgStateMachine &state_machine) : m_state_machine{state_machine}{}
private:
void DataChange(uint32_t handle, const Node &node, const Variant &val, AttributeId attr) override
{
auto v = val.As<bool>();
m_state_machine.set_sim_mode_enabled(v);
}
SmgStateMachine &m_state_machine;
};
SmartOpcServer::SmartOpcServer(SmgStateMachine &state_machine)
: m_state_machine{state_machine}
{
// m_logger = spdlog::stderr_color_mt("server");
m_server = UaServer();
m_server.SetEndpoint(k_opc_server_url);
m_server.SetServerURI("Smart Grid OPC UA server");
}
void SmartOpcServer::setup_server()
{
m_server.Start();
m_idx = m_server.RegisterNamespace("https://gitlab.cvh-server.de/aco/smart-grid-modell");
m_objects_folder = m_server.GetObjectsNode();
m_root_node = m_server.GetRootNode();
Node smart_grid_folder{m_objects_folder.AddFolder(m_idx, "smart_grid_model")};
m_state = smart_grid_folder.AddObject(m_idx, "state");
m_time = m_state.AddVariable(m_idx, "time", Variant(m_state_machine.m_model.get_time()));
m_excess_power = m_state.AddVariable(m_idx, "excess_power", Variant(m_state_machine.m_model.get_excess_power()));
m_controls = smart_grid_folder.AddObject(m_idx, "controls");
m_producing = m_controls.AddVariable(m_idx, "producing", Variant(m_state_machine.m_model.get_producing_state()));
m_sim_mode_enabled = m_controls.AddVariable(m_idx, "sim_mode_enabled", Variant(m_state_machine.is_sim_mode_enabled()));
}
void SmartOpcServer::run_server()
{
setup_server();
SubClientTime subcl_time{m_state_machine.m_model};
auto sub_time = m_server.CreateSubscription(100, subcl_time);
sub_time->SubscribeDataChange(m_time);
SubClientProductionEnabled subcl_production_enabled{m_state_machine.m_model};
auto sub_production_enabled = m_server.CreateSubscription(100, subcl_production_enabled);
sub_production_enabled->SubscribeDataChange(m_producing);
while(true)
{
m_state_machine.run();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}