@@ -30,11 +30,8 @@ Helloworld::Helloworld(const std::string name, const HelloworldJsonObject &conf)
3030 logger ()->info (" Creating Helloworld instance" );
3131 setAction (conf.getAction ());
3232
33- // set an initial state before doing any change to the configuration
34- // UINT16_MAX means that the port is not connected
35- auto ports_map = get_array_table<uint16_t >(" ports_map" );
36- ports_map.set (0 , UINT16_MAX);
37- ports_map.set (1 , UINT16_MAX);
33+ // initialize ports map (at this point there are not ports)
34+ update_ports_map ();
3835
3936 addPortsList (conf.getPorts ());
4037}
@@ -64,41 +61,30 @@ void Helloworld::addPorts(const std::string &name,
6461 throw std::runtime_error (" maximum number of ports reached" );
6562 }
6663
67- auto p = add_port<PortsJsonObject>(name, conf);
64+ add_port<PortsJsonObject>(name, conf);
6865 logger ()->info (" port {0} was connected" , name);
69-
70- auto ports_table = get_array_table<uint16_t >(" ports_map" );
71-
72- uint32_t port_map_index;
73- try {
74- // Look for first free entry to save the port id
75- if (ports_table.get (0x0 ) == UINT16_MAX) {
76- port_map_index = 0x0 ;
77- } else if (ports_table.get (0x1 ) == UINT16_MAX) {
78- port_map_index = 0x1 ;
79- }
80- } catch (std::exception &e) {
81- logger ()->error (" port {0} does not exist" , name);
82- // TODO: should Cube::remove_port be called?
83- throw std::runtime_error (" Port does not exist" );
84- }
85-
86- ports_table.set (port_map_index, p->index ());
66+ update_ports_map ();
8767}
8868
8969void Helloworld::delPorts (const std::string &name) {
90- int index = get_port (name)->index ();
70+ remove_port (name);
71+ logger ()->info (" port {0} was removed" , name);
72+ update_ports_map ();
73+ }
9174
75+ void Helloworld::update_ports_map () {
9276 auto ports_table = get_array_table<uint16_t >(" ports_map" );
77+ auto ports = get_ports ();
78+ uint32_t i = 0 ;
9379
94- uint32_t port_map_index;
95- if (ports_table.get (0x0 ) == index) {
96- port_map_index = 0x0 ;
97- } else if (ports_table.get (0x1 ) == index) {
98- port_map_index = 0x1 ;
80+ for (auto &port: ports) {
81+ ports_table.set (i, port->index ());
82+ i++;
83+ }
84+
85+ // mark other ports as empty (UINT16_MAX means empty)
86+ while (i < 2 ) {
87+ ports_table.set (i, UINT16_MAX);
88+ i++;
9989 }
100- // mark entry as free
101- ports_table.set (port_map_index, UINT16_MAX);
102- remove_port (name);
103- logger ()->info (" port {0} was removed" , name);
10490}
0 commit comments