Просмотр исходного кода

Merge remote-tracking branch 'refs/remotes/origin/patch-1'

pogojotz 9 лет назад
Родитель
Сommit
1430189d61
39 измененных файлов с 984 добавлено и 698 удалено
  1. 1 0
      README.md
  2. 2 2
      source/buildsupport/POSIX/OpENer_PLATFORM_INCLUDES.cmake
  3. 51 48
      source/src/cip/appcontype.c
  4. 9 9
      source/src/cip/appcontype.h
  5. 29 31
      source/src/cip/cipassembly.c
  6. 3 3
      source/src/cip/cipassembly.h
  7. 8 6
      source/src/cip/cipclass3connection.c
  8. 9 5
      source/src/cip/cipclass3connection.h
  9. 122 144
      source/src/cip/cipcommon.c
  10. 12 12
      source/src/cip/cipcommon.h
  11. 71 76
      source/src/cip/cipconnectionmanager.c
  12. 16 7
      source/src/cip/cipconnectionmanager.h
  13. 19 15
      source/src/cip/cipethernetlink.c
  14. 2 0
      source/src/cip/cipethernetlink.h
  15. 11 16
      source/src/cip/cipidentity.c
  16. 1 1
      source/src/cip/cipidentity.h
  17. 42 49
      source/src/cip/cipioconnection.c
  18. 2 2
      source/src/cip/cipioconnection.h
  19. 32 36
      source/src/cip/cipmessagerouter.c
  20. 1 1
      source/src/cip/cipmessagerouter.h
  21. 23 23
      source/src/cip/ciptcpipinterface.c
  22. 2 0
      source/src/cip/ciptcpipinterface.h
  23. 6 6
      source/src/cip/ciptypes.h
  24. 149 27
      source/src/enet_encap/cpf.c
  25. 3 3
      source/src/enet_encap/cpf.h
  26. 40 29
      source/src/enet_encap/encap.c
  27. 1 1
      source/src/enet_encap/encap.h
  28. 13 13
      source/src/enet_encap/endianconv.c
  29. 8 8
      source/src/enet_encap/endianconv.h
  30. 46 46
      source/src/opener_api.h
  31. 1 1
      source/src/ports/POSIX/CMakeLists.txt
  32. 31 0
      source/src/ports/POSIX/opener_error.c
  33. 10 10
      source/src/ports/POSIX/sample_application/sampleapplication.c
  34. 1 1
      source/src/ports/WIN32/CMakeLists.txt
  35. 26 0
      source/src/ports/WIN32/opener_error.c
  36. 6 6
      source/src/ports/WIN32/sample_application/sampleapplication.c
  37. 118 49
      source/src/ports/generic_networkhandler.c
  38. 32 0
      source/src/ports/opener_error.h
  39. 25 12
      source/tests/enet_encap/endianconvtest.cpp

+ 1 - 0
README.md

@@ -73,6 +73,7 @@ Directory structure:
 		- ports ... the platform specific code
 		- ports ... the platform specific code
 		- utils ... utility functions
 		- utils ... utility functions
 	- tests ... the test source code
 	- tests ... the test source code
+		- enet_encap ... tests for Ethernet encapsulation layer
 		- utils ... tests for utility functions
 		- utils ... tests for utility functions
 
 
 Documentation:
 Documentation:

+ 2 - 2
source/buildsupport/POSIX/OpENer_PLATFORM_INCLUDES.cmake

@@ -1,6 +1,6 @@
 macro(opener_platform_spec)
 macro(opener_platform_spec)
   include_directories(${PORTS_SRC_DIR}/${OpENer_PLATFORM} ${PORTS_SRC_DIR}/${OpENer_PLATFORM}/sample_application)
   include_directories(${PORTS_SRC_DIR}/${OpENer_PLATFORM} ${PORTS_SRC_DIR}/${OpENer_PLATFORM}/sample_application)
-  set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ansi -std=c99 -Werror=implicit-function-declaration" )
-  add_definitions( -D_POSIX_C_SOURCE=199309L )
+  set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -Werror=implicit-function-declaration" )
+  add_definitions( -D_POSIX_C_SOURCE=200112L -D__USE_GNU -D__USE_XOPEN2K)
 endmacro(opener_platform_spec)
 endmacro(opener_platform_spec)
 
 

+ 51 - 48
source/src/cip/appcontype.c

@@ -3,14 +3,20 @@
  * All rights reserved.
  * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
+
+#include <string.h>
+
 #include "appcontype.h"
 #include "appcontype.h"
+
 #include "cipconnectionmanager.h"
 #include "cipconnectionmanager.h"
 #include "opener_api.h"
 #include "opener_api.h"
-#include <string.h>
+#include "assert.h"
+
 
 
 /** @brief External globals needed from connectionmanager.c */
 /** @brief External globals needed from connectionmanager.c */
 extern ConnectionObject *g_active_connection_list;
 extern ConnectionObject *g_active_connection_list;
 
 
+/** @brief Exclusive Owner connection data */
 typedef struct {
 typedef struct {
   unsigned int output_assembly; /**< the O-to-T point for the connection */
   unsigned int output_assembly; /**< the O-to-T point for the connection */
   unsigned int input_assembly; /**< the T-to-O point for the connection */
   unsigned int input_assembly; /**< the T-to-O point for the connection */
@@ -18,6 +24,7 @@ typedef struct {
   ConnectionObject connection_data; /**< the connection data, only one connection is allowed per O-to-T point*/
   ConnectionObject connection_data; /**< the connection data, only one connection is allowed per O-to-T point*/
 } ExclusiveOwnerConnection;
 } ExclusiveOwnerConnection;
 
 
+/** @brief Input Only connection data */
 typedef struct {
 typedef struct {
   unsigned int output_assembly; /**< the O-to-T point for the connection */
   unsigned int output_assembly; /**< the O-to-T point for the connection */
   unsigned int input_assembly; /**< the T-to-O point for the connection */
   unsigned int input_assembly; /**< the T-to-O point for the connection */
@@ -25,6 +32,7 @@ typedef struct {
   ConnectionObject connection_data[OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH]; /*< the connection data */
   ConnectionObject connection_data[OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH]; /*< the connection data */
 } InputOnlyConnection;
 } InputOnlyConnection;
 
 
+/** @brief Listen Only connection data */
 typedef struct {
 typedef struct {
   unsigned int output_assembly; /**< the O-to-T point for the connection */
   unsigned int output_assembly; /**< the O-to-T point for the connection */
   unsigned int input_assembly; /**< the T-to-O point for the connection */
   unsigned int input_assembly; /**< the T-to-O point for the connection */
@@ -32,25 +40,25 @@ typedef struct {
   ConnectionObject connection_data[OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH]; /**< the connection data */
   ConnectionObject connection_data[OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH]; /**< the connection data */
 } ListenOnlyConnection;
 } ListenOnlyConnection;
 
 
-ExclusiveOwnerConnection g_exlusive_owner_connections[OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS];
+ExclusiveOwnerConnection g_exlusive_owner_connections[OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS]; /**< Exclusive Owner connections */
 
 
-InputOnlyConnection g_input_only_connections[OPENER_CIP_NUM_INPUT_ONLY_CONNS];
+InputOnlyConnection g_input_only_connections[OPENER_CIP_NUM_INPUT_ONLY_CONNS]; /**< Input Only connections */
 
 
-ListenOnlyConnection g_listen_only_connections[OPENER_CIP_NUM_LISTEN_ONLY_CONNS];
+ListenOnlyConnection g_listen_only_connections[OPENER_CIP_NUM_LISTEN_ONLY_CONNS]; /**< Listen Only connections */
 
 
 ConnectionObject *GetExclusiveOwnerConnection(
 ConnectionObject *GetExclusiveOwnerConnection(
-    ConnectionObject *connection_object, EipUint16 *extended_error);
+    const ConnectionObject *restrict connection_object, EipUint16 *const extended_error);
 
 
-ConnectionObject *GetInputOnlyConnection(ConnectionObject *connection_object,
-                                         EipUint16 *extended_error);
+ConnectionObject *GetInputOnlyConnection(const ConnectionObject *const restrict connection_object,
+                                         EipUint16 *const extended_error);
 
 
-ConnectionObject *GetListenOnlyConnection(ConnectionObject *connection_object,
-                                          EipUint16 *extended_error);
+ConnectionObject *GetListenOnlyConnection(const ConnectionObject *const restrict connection_object,
+                                          EipUint16 *const extended_error);
 
 
-void ConfigureExclusiveOwnerConnectionPoint(unsigned int connection_number,
-                                            unsigned int output_assembly,
-                                            unsigned int input_assembly,
-                                            unsigned int config_assembly) {
+void ConfigureExclusiveOwnerConnectionPoint(const unsigned int connection_number,
+                                            const unsigned int output_assembly,
+                                            const unsigned int input_assembly,
+                                            const unsigned int config_assembly) {
   if (OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS > connection_number) {
   if (OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS > connection_number) {
     g_exlusive_owner_connections[connection_number].output_assembly =
     g_exlusive_owner_connections[connection_number].output_assembly =
         output_assembly;
         output_assembly;
@@ -61,10 +69,10 @@ void ConfigureExclusiveOwnerConnectionPoint(unsigned int connection_number,
   }
   }
 }
 }
 
 
-void ConfigureInputOnlyConnectionPoint(unsigned int connection_number,
-                                       unsigned int output_assembly,
-                                       unsigned int input_assembly,
-                                       unsigned int config_assembly) {
+void ConfigureInputOnlyConnectionPoint(const unsigned int connection_number,
+                                       const unsigned int output_assembly,
+                                       const unsigned int input_assembly,
+                                       const unsigned int config_assembly) {
   if (OPENER_CIP_NUM_INPUT_ONLY_CONNS > connection_number) {
   if (OPENER_CIP_NUM_INPUT_ONLY_CONNS > connection_number) {
     g_input_only_connections[connection_number].output_assembly =
     g_input_only_connections[connection_number].output_assembly =
         output_assembly;
         output_assembly;
@@ -74,10 +82,10 @@ void ConfigureInputOnlyConnectionPoint(unsigned int connection_number,
   }
   }
 }
 }
 
 
-void ConfigureListenOnlyConnectionPoint(unsigned int connection_number,
-                                        unsigned int output_assembly,
-                                        unsigned int input_assembly,
-                                        unsigned int config_assembly) {
+void ConfigureListenOnlyConnectionPoint(const unsigned int connection_number,
+                                        const unsigned int output_assembly,
+                                        const unsigned int input_assembly,
+                                        const unsigned int config_assembly) {
   if (OPENER_CIP_NUM_LISTEN_ONLY_CONNS > connection_number) {
   if (OPENER_CIP_NUM_LISTEN_ONLY_CONNS > connection_number) {
     g_listen_only_connections[connection_number].output_assembly =
     g_listen_only_connections[connection_number].output_assembly =
         output_assembly;
         output_assembly;
@@ -89,7 +97,7 @@ void ConfigureListenOnlyConnectionPoint(unsigned int connection_number,
 }
 }
 
 
 ConnectionObject *GetIoConnectionForConnectionData(
 ConnectionObject *GetIoConnectionForConnectionData(
-    ConnectionObject *connection_object, EipUint16 *extended_error) {
+    ConnectionObject *const restrict connection_object, EipUint16 *const extended_error) {
   ConnectionObject *io_connection = NULL;
   ConnectionObject *io_connection = NULL;
   *extended_error = 0;
   *extended_error = 0;
 
 
@@ -129,11 +137,10 @@ ConnectionObject *GetIoConnectionForConnectionData(
 }
 }
 
 
 ConnectionObject *GetExclusiveOwnerConnection(
 ConnectionObject *GetExclusiveOwnerConnection(
-    ConnectionObject *connection_object, EipUint16 *extended_error) {
+    const ConnectionObject *const restrict connection_object, EipUint16 *const extended_error) {
   ConnectionObject *exclusive_owner_connection = NULL;
   ConnectionObject *exclusive_owner_connection = NULL;
-  int i;
 
 
-  for (i = 0; i < OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS; i++) {
+  for (int i = 0; i < OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS; i++) {
     if ((g_exlusive_owner_connections[i].output_assembly
     if ((g_exlusive_owner_connections[i].output_assembly
         == connection_object->connection_path.connection_point[0])
         == connection_object->connection_path.connection_point[0])
         && (g_exlusive_owner_connections[i].input_assembly
         && (g_exlusive_owner_connections[i].input_assembly
@@ -156,12 +163,11 @@ ConnectionObject *GetExclusiveOwnerConnection(
   return exclusive_owner_connection;
   return exclusive_owner_connection;
 }
 }
 
 
-ConnectionObject *GetInputOnlyConnection(ConnectionObject *connection_object,
-                                         EipUint16 *extended_error) {
-  ConnectionObject *input_only_connection = NULL;
-  int i, j;
+ConnectionObject *GetInputOnlyConnection(const ConnectionObject *const restrict connection_object,
+                                         EipUint16 *const extended_error) {
+  ConnectionObject *input_only_connection = NULL; //TODO: This variable has no use
 
 
-  for (i = 0; i < OPENER_CIP_NUM_INPUT_ONLY_CONNS; i++) {
+  for (int i = 0; i < OPENER_CIP_NUM_INPUT_ONLY_CONNS; i++) {
     if (g_input_only_connections[i].output_assembly
     if (g_input_only_connections[i].output_assembly
         == connection_object->connection_path.connection_point[0]) { /* we have the same output assembly */
         == connection_object->connection_path.connection_point[0]) { /* we have the same output assembly */
       if (g_input_only_connections[i].input_assembly
       if (g_input_only_connections[i].input_assembly
@@ -177,7 +183,7 @@ ConnectionObject *GetInputOnlyConnection(ConnectionObject *connection_object,
         break;
         break;
       }
       }
 
 
-      for (j = 0; j < OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH; j++) {
+      for (int j = 0; j < OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH; j++) {
         if (kConnectionStateNonExistent
         if (kConnectionStateNonExistent
             == g_input_only_connections[i].connection_data[j].state) {
             == g_input_only_connections[i].connection_data[j].state) {
           return &(g_input_only_connections[i].connection_data[j]);
           return &(g_input_only_connections[i].connection_data[j]);
@@ -191,10 +197,9 @@ ConnectionObject *GetInputOnlyConnection(ConnectionObject *connection_object,
   return input_only_connection;
   return input_only_connection;
 }
 }
 
 
-ConnectionObject *GetListenOnlyConnection(ConnectionObject *connection_object,
-                                          EipUint16 *extended_error) {
-  ConnectionObject *listen_only_connection = NULL;
-  int i, j;
+ConnectionObject *GetListenOnlyConnection(const ConnectionObject *const restrict connection_object,
+                                          EipUint16 *const extended_error) {
+  ConnectionObject *listen_only_connection = NULL; //TODO: This variable has no use
 
 
   if (kRoutingTypeMulticastConnection
   if (kRoutingTypeMulticastConnection
       != (connection_object->t_to_o_network_connection_parameter
       != (connection_object->t_to_o_network_connection_parameter
@@ -205,7 +210,7 @@ ConnectionObject *GetListenOnlyConnection(ConnectionObject *connection_object,
     return NULL;
     return NULL;
   }
   }
 
 
-  for (i = 0; i < OPENER_CIP_NUM_LISTEN_ONLY_CONNS; i++) {
+  for (int i = 0; i < OPENER_CIP_NUM_LISTEN_ONLY_CONNS; i++) {
     if (g_listen_only_connections[i].output_assembly
     if (g_listen_only_connections[i].output_assembly
         == connection_object->connection_path.connection_point[0]) { /* we have the same output assembly */
         == connection_object->connection_path.connection_point[0]) { /* we have the same output assembly */
       if (g_listen_only_connections[i].input_assembly
       if (g_listen_only_connections[i].input_assembly
@@ -229,7 +234,7 @@ ConnectionObject *GetListenOnlyConnection(ConnectionObject *connection_object,
         break;
         break;
       }
       }
 
 
-      for (j = 0; j < OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH; j++) {
+      for (int j = 0; j < OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH; j++) {
         if (kConnectionStateNonExistent
         if (kConnectionStateNonExistent
             == g_listen_only_connections[i].connection_data[j].state) {
             == g_listen_only_connections[i].connection_data[j].state) {
           return &(g_listen_only_connections[i].connection_data[j]);
           return &(g_listen_only_connections[i].connection_data[j]);
@@ -243,7 +248,7 @@ ConnectionObject *GetListenOnlyConnection(ConnectionObject *connection_object,
   return listen_only_connection;
   return listen_only_connection;
 }
 }
 
 
-ConnectionObject *GetExistingProducerMulticastConnection(EipUint32 input_point) {
+ConnectionObject *GetExistingProducerMulticastConnection(const EipUint32 input_point) {
   ConnectionObject *producer_multicast_connection = g_active_connection_list;
   ConnectionObject *producer_multicast_connection = g_active_connection_list;
 
 
   while (NULL != producer_multicast_connection) {
   while (NULL != producer_multicast_connection) {
@@ -271,7 +276,7 @@ ConnectionObject *GetExistingProducerMulticastConnection(EipUint32 input_point)
   return producer_multicast_connection;
   return producer_multicast_connection;
 }
 }
 
 
-ConnectionObject *GetNextNonControlMasterConnection(EipUint32 input_point) {
+ConnectionObject *GetNextNonControlMasterConnection(const EipUint32 input_point) {
   ConnectionObject *next_non_control_master_connection =
   ConnectionObject *next_non_control_master_connection =
       g_active_connection_list;
       g_active_connection_list;
 
 
@@ -301,24 +306,22 @@ ConnectionObject *GetNextNonControlMasterConnection(EipUint32 input_point) {
   return next_non_control_master_connection;
   return next_non_control_master_connection;
 }
 }
 
 
-void CloseAllConnectionsForInputWithSameType(EipUint32 input_point,
-                                             ConnectionType instance_type) {
+void CloseAllConnectionsForInputWithSameType(const EipUint32 input_point,
+                                             const ConnectionType instance_type) {
   ConnectionObject *connection = g_active_connection_list;
   ConnectionObject *connection = g_active_connection_list;
-  ConnectionObject *connection_to_delete;
 
 
   while (NULL != connection) {
   while (NULL != connection) {
     if ((instance_type == connection->instance_type)
     if ((instance_type == connection->instance_type)
         && (input_point == connection->connection_path.connection_point[1])) {
         && (input_point == connection->connection_path.connection_point[1])) {
-      connection_to_delete = connection;
+      ConnectionObject *connection_to_delete = connection;
       connection = connection->next_connection_object;
       connection = connection->next_connection_object;
       CheckIoConnectionEvent(
       CheckIoConnectionEvent(
           connection_to_delete->connection_path.connection_point[0],
           connection_to_delete->connection_path.connection_point[0],
           connection_to_delete->connection_path.connection_point[1],
           connection_to_delete->connection_path.connection_point[1],
           kIoConnectionEventClosed);
           kIoConnectionEventClosed);
 
 
-      /* FIXME check if this is ok */
+      assert(connection_to_delete->connection_close_function != NULL);
       connection_to_delete->connection_close_function(connection_to_delete);
       connection_to_delete->connection_close_function(connection_to_delete);
-      /*closeConnection(pstToDelete); will remove the connection from the active connection list */
     } else {
     } else {
       connection = connection->next_connection_object;
       connection = connection->next_connection_object;
     }
     }
@@ -328,17 +331,17 @@ void CloseAllConnectionsForInputWithSameType(EipUint32 input_point,
 void CloseAllConnections(void) {
 void CloseAllConnections(void) {
   ConnectionObject *connection = g_active_connection_list;
   ConnectionObject *connection = g_active_connection_list;
   while (NULL != connection) {
   while (NULL != connection) {
-    /*FIXME check if m_pfCloseFunc would be suitable*/
+    assert(connection->connection_close_function != NULL);
+    connection->connection_close_function(connection);
     CloseConnection(connection);
     CloseConnection(connection);
     /* Close connection will remove the connection from the list therefore we
     /* Close connection will remove the connection from the list therefore we
      * need to get again the start until there is no connection left
      * need to get again the start until there is no connection left
      */
      */
     connection = g_active_connection_list;
     connection = g_active_connection_list;
   }
   }
-
 }
 }
 
 
-EipBool8 ConnectionWithSameConfigPointExists(EipUint32 config_point) {
+EipBool8 ConnectionWithSameConfigPointExists(const EipUint32 config_point) {
   ConnectionObject *connection = g_active_connection_list;
   ConnectionObject *connection = g_active_connection_list;
 
 
   while (NULL != connection) {
   while (NULL != connection) {

+ 9 - 9
source/src/cip/appcontype.h

@@ -16,15 +16,15 @@ void InitializeIoConnectionData(void);
  *  If a suitable connection is found the connection data is transfered the
  *  If a suitable connection is found the connection data is transfered the
  *  application connection type is set (i.e., EConnType).
  *  application connection type is set (i.e., EConnType).
  *  @param connection_object connection data to be used
  *  @param connection_object connection data to be used
- *  @param extended_error if an error occurred this value has the according
+ *  @param extended_error pointer to the extended_error variable, if an error occurred this value has the according
  *     error code for the response
  *     error code for the response
  *  @return
  *  @return
  *        - on success: A pointer to the connection object already containing the connection
  *        - on success: A pointer to the connection object already containing the connection
- *          data given in pa_pstConnData.
+ *          data given in connection_object.
  *        - on error: NULL
  *        - on error: NULL
  */
  */
 ConnectionObject *GetIoConnectionForConnectionData(
 ConnectionObject *GetIoConnectionForConnectionData(
-    ConnectionObject *connection_object, EipUint16 *extended_error);
+    ConnectionObject *const restrict connection_object, EipUint16 *const extended_error);
 
 
 /** @brief Check if there exists already an exclusive owner or listen only connection
 /** @brief Check if there exists already an exclusive owner or listen only connection
  *         which produces the input assembly.
  *         which produces the input assembly.
@@ -32,7 +32,7 @@ ConnectionObject *GetIoConnectionForConnectionData(
  *  @param input_point the Input point to be produced
  *  @param input_point the Input point to be produced
  *  @return if a connection could be found a pointer to this connection if not NULL
  *  @return if a connection could be found a pointer to this connection if not NULL
  */
  */
-ConnectionObject *GetExistingProducerMulticastConnection(EipUint32 input_point);
+ConnectionObject *GetExistingProducerMulticastConnection(const EipUint32 input_point);
 
 
 /** @brief check if there exists an producing multicast exclusive owner or
 /** @brief check if there exists an producing multicast exclusive owner or
  * listen only connection that should produce the same input but is not in charge
  * listen only connection that should produce the same input but is not in charge
@@ -42,16 +42,16 @@ ConnectionObject *GetExistingProducerMulticastConnection(EipUint32 input_point);
  * @return if a connection could be found the pointer to this connection
  * @return if a connection could be found the pointer to this connection
  *      otherwise NULL.
  *      otherwise NULL.
  */
  */
-ConnectionObject *GetNextNonControlMasterConnection(EipUint32 input_point);
+ConnectionObject *GetNextNonControlMasterConnection(const EipUint32 input_point);
 
 
 /** @brief Close all connection producing the same input and have the same type
 /** @brief Close all connection producing the same input and have the same type
  * (i.e., listen only or input only).
  * (i.e., listen only or input only).
  *
  *
- * @param input_point  the input point
+ * @param input_point the input point
  * @param instance_type the connection application type
  * @param instance_type the connection application type
  */
  */
-void CloseAllConnectionsForInputWithSameType(EipUint32 input_point,
-                                             ConnectionType instance_type);
+void CloseAllConnectionsForInputWithSameType(const EipUint32 input_point,
+                                             const ConnectionType instance_type);
 
 
 /**@ brief close all open connections.
 /**@ brief close all open connections.
  *
  *
@@ -66,6 +66,6 @@ void CloseAllConnections(void);
  * @param config_point The configuration point
  * @param config_point The configuration point
  * @return true if connection was found, otherwise false
  * @return true if connection was found, otherwise false
  */
  */
-EipBool8 ConnectionWithSameConfigPointExists(EipUint32 config_point);
+EipBool8 ConnectionWithSameConfigPointExists(const EipUint32 config_point);
 
 
 #endif /* OPENER_APPCONTYPE_H_ */
 #endif /* OPENER_APPCONTYPE_H_ */

+ 29 - 31
source/src/cip/cipassembly.c

@@ -18,13 +18,17 @@
  *  Currently only supports Attribute 3 (CIP_BYTE_ARRAY) of an Assembly
  *  Currently only supports Attribute 3 (CIP_BYTE_ARRAY) of an Assembly
  */
  */
 EipStatus SetAssemblyAttributeSingle(
 EipStatus SetAssemblyAttributeSingle(
-    CipInstance *instance, CipMessageRouterRequest *message_router_request,
-    CipMessageRouterResponse *message_router_response);
+    CipInstance *const instance, CipMessageRouterRequest *const message_router_request,
+    CipMessageRouterResponse *const message_router_response);
 
 
+/** @brief Constructor for the assembly object class
+ *
+ *  Creates an initializes Assembly class or object instances
+ *  @return Pointer to the created Assembly object
+ */
 CipClass *CreateAssemblyClass(void) {
 CipClass *CreateAssemblyClass(void) {
-  CipClass *assembly_class;
   /* create the CIP Assembly object with zero instances */
   /* create the CIP Assembly object with zero instances */
-  assembly_class = CreateCipClass(kCipAssemblyClassCode, 0, /* # class attributes*/
+  CipClass *assembly_class = CreateCipClass(kCipAssemblyClassCode, 0, /* # class attributes*/
                                   0, /* 0 as the assembly object should not have a get_attribute_all service*/
                                   0, /* 0 as the assembly object should not have a get_attribute_all service*/
                                   0, /* # class services*/
                                   0, /* # class services*/
                                   2, /* # instance attributes*/
                                   2, /* # instance attributes*/
@@ -42,19 +46,20 @@ CipClass *CreateAssemblyClass(void) {
   return assembly_class;
   return assembly_class;
 }
 }
 
 
-EipStatus CipAssemblyInitialize(void) { /* create the CIP Assembly object with zero instances */
+/** @brief create the CIP Assembly object with zero instances
+ *
+ */
+EipStatus CipAssemblyInitialize(void) {
   return (NULL != CreateAssemblyClass()) ? kEipStatusOk : kEipStatusError;
   return (NULL != CreateAssemblyClass()) ? kEipStatusOk : kEipStatusError;
 }
 }
 
 
 void ShutdownAssemblies(void) {
 void ShutdownAssemblies(void) {
   CipClass *assembly_class = GetCipClass(kCipAssemblyClassCode);
   CipClass *assembly_class = GetCipClass(kCipAssemblyClassCode);
-  CipAttributeStruct *attribute;
-  CipInstance *instance;
 
 
   if (NULL != assembly_class) {
   if (NULL != assembly_class) {
-    instance = assembly_class->instances;
+    CipInstance *instance = assembly_class->instances;
     while (NULL != instance) {
     while (NULL != instance) {
-      attribute = GetCipAttribute(instance, 3);
+      CipAttributeStruct *attribute = GetCipAttribute(instance, 3);
       if (NULL != attribute) {
       if (NULL != attribute) {
         CipFree(attribute->data);
         CipFree(attribute->data);
       }
       }
@@ -63,22 +68,19 @@ void ShutdownAssemblies(void) {
   }
   }
 }
 }
 
 
-CipInstance *CreateAssemblyObject(EipUint32 instance_id, EipByte *data,
-                                  EipUint16 data_length) {
-  CipClass *assembly_class;
-  CipInstance *instance;
-  CipByteArray *assembly_byte_array;
-
+CipInstance *CreateAssemblyObject(const EipUint32 instance_id, EipByte *const data,
+                                  const EipUint16 data_length) {
+  CipClass *assembly_class = NULL;
   if (NULL == (assembly_class = GetCipClass(kCipAssemblyClassCode))) {
   if (NULL == (assembly_class = GetCipClass(kCipAssemblyClassCode))) {
     if (NULL == (assembly_class = CreateAssemblyClass())) {
     if (NULL == (assembly_class = CreateAssemblyClass())) {
       return NULL;
       return NULL;
     }
     }
   }
   }
 
 
-  instance = AddCIPInstance(assembly_class, instance_id); /* add instances (always succeeds (or asserts))*/
+  CipInstance *const instance = AddCIPInstance(assembly_class, instance_id); /* add instances (always succeeds (or asserts))*/
 
 
-  if ((assembly_byte_array = (CipByteArray *) CipCalloc(1, sizeof(CipByteArray)))
-      == NULL) {
+  CipByteArray *const assembly_byte_array = (CipByteArray *) CipCalloc(1, sizeof(CipByteArray));
+  if (assembly_byte_array == NULL) {
     return NULL; /*TODO remove assembly instance in case of error*/
     return NULL; /*TODO remove assembly instance in case of error*/
   }
   }
 
 
@@ -93,17 +95,15 @@ CipInstance *CreateAssemblyObject(EipUint32 instance_id, EipByte *data,
   return instance;
   return instance;
 }
 }
 
 
-EipStatus NotifyAssemblyConnectedDataReceived(CipInstance *instance,
-                                              EipUint8 *data,
-                                              EipUint16 data_length) {
-  CipByteArray *assembly_byte_array;
-
+EipStatus NotifyAssemblyConnectedDataReceived(CipInstance *const instance,
+                                              const EipUint8 *const data,
+                                              const EipUint16 data_length) {
   /* empty path (path size = 0) need to be checked and taken care of in future */
   /* empty path (path size = 0) need to be checked and taken care of in future */
   /* copy received data to Attribute 3 */
   /* copy received data to Attribute 3 */
-  assembly_byte_array = (CipByteArray *) instance->attributes->data;
+  CipByteArray *assembly_byte_array = (CipByteArray *) instance->attributes->data;
   if (assembly_byte_array->length != data_length) {
   if (assembly_byte_array->length != data_length) {
     OPENER_TRACE_ERR("wrong amount of data arrived for assembly object\n");
     OPENER_TRACE_ERR("wrong amount of data arrived for assembly object\n");
-    return kEipStatusError; /*TODO question should we notify the application that wrong data has been recieved???*/
+    return kEipStatusError; /*TODO question should we notify the application that wrong data has been received???*/
   } else {
   } else {
     memcpy(assembly_byte_array->data, data, data_length);
     memcpy(assembly_byte_array->data, data, data_length);
     /* call the application that new data arrived */
     /* call the application that new data arrived */
@@ -113,14 +113,12 @@ EipStatus NotifyAssemblyConnectedDataReceived(CipInstance *instance,
 }
 }
 
 
 EipStatus SetAssemblyAttributeSingle(
 EipStatus SetAssemblyAttributeSingle(
-    CipInstance *instance, CipMessageRouterRequest *message_router_request,
-    CipMessageRouterResponse *message_router_response) {
-  EipUint8 *router_request_data;
-  CipAttributeStruct *attribute;
+    CipInstance *const instance, CipMessageRouterRequest *const message_router_request,
+    CipMessageRouterResponse *const message_router_response) {
   OPENER_TRACE_INFO(" setAttribute %d\n",
   OPENER_TRACE_INFO(" setAttribute %d\n",
                     message_router_request->request_path.attribute_number);
                     message_router_request->request_path.attribute_number);
 
 
-  router_request_data = message_router_request->data;
+  const EipUint8 *const router_request_data = message_router_request->data;
 
 
   message_router_response->data_length = 0;
   message_router_response->data_length = 0;
   message_router_response->reply_service = (0x80
   message_router_response->reply_service = (0x80
@@ -128,7 +126,7 @@ EipStatus SetAssemblyAttributeSingle(
   message_router_response->general_status = kCipErrorAttributeNotSupported;
   message_router_response->general_status = kCipErrorAttributeNotSupported;
   message_router_response->size_of_additional_status = 0;
   message_router_response->size_of_additional_status = 0;
 
 
-  attribute = GetCipAttribute(
+  CipAttributeStruct *attribute = GetCipAttribute(
       instance, message_router_request->request_path.attribute_number);
       instance, message_router_request->request_path.attribute_number);
 
 
   if ((attribute != NULL)
   if ((attribute != NULL)

+ 3 - 3
source/src/cip/cipassembly.h

@@ -43,8 +43,8 @@ void ShutdownAssemblies(void);
  *     - EIP_OK the received data was okay
  *     - EIP_OK the received data was okay
  *     - EIP_ERROR the received data was wrong
  *     - EIP_ERROR the received data was wrong
  */
  */
-EipStatus NotifyAssemblyConnectedDataReceived(CipInstance *instance,
-                                              EipUint8 *data,
-                                              EipUint16 data_length);
+EipStatus NotifyAssemblyConnectedDataReceived(CipInstance *const instance,
+                                              const EipUint8 *const data,
+                                              const EipUint16 data_length);
 
 
 #endif /* OPENER_CIPASSEMBLY_H_ */
 #endif /* OPENER_CIPASSEMBLY_H_ */

+ 8 - 6
source/src/cip/cipclass3connection.c

@@ -16,10 +16,9 @@ ConnectionObject *GetFreeExplicitConnection(void);
 ConnectionObject g_explicit_connections[OPENER_CIP_NUM_EXPLICIT_CONNS];
 ConnectionObject g_explicit_connections[OPENER_CIP_NUM_EXPLICIT_CONNS];
 
 
 /**** Implementation ****/
 /**** Implementation ****/
-EipStatus EstablishClass3Connection(ConnectionObject *connection_object,
-                              EipUint16 *extended_error) {
+EipStatus EstablishClass3Connection(ConnectionObject *restrict const connection_object,
+                              EipUint16 *const extended_error) {
   EipStatus eip_status = kEipStatusOk;
   EipStatus eip_status = kEipStatusOk;
-  EipUint32 produced_connection_id_buffer;
 
 
   /*TODO add check for transport type trigger */
   /*TODO add check for transport type trigger */
   /* if (0x03 == (g_stDummyConnectionObject.TransportTypeClassTrigger & 0x03)) */
   /* if (0x03 == (g_stDummyConnectionObject.TransportTypeClassTrigger & 0x03)) */
@@ -33,7 +32,7 @@ EipStatus EstablishClass3Connection(ConnectionObject *connection_object,
   } else {
   } else {
     CopyConnectionData(explicit_connection, connection_object);
     CopyConnectionData(explicit_connection, connection_object);
 
 
-    produced_connection_id_buffer = explicit_connection->produced_connection_id;
+    EipUint32 produced_connection_id_buffer = explicit_connection->produced_connection_id;
     GeneralConnectionConfiguration(explicit_connection);
     GeneralConnectionConfiguration(explicit_connection);
     explicit_connection->produced_connection_id = produced_connection_id_buffer;
     explicit_connection->produced_connection_id = produced_connection_id_buffer;
     explicit_connection->instance_type = kConnectionTypeExplicit;
     explicit_connection->instance_type = kConnectionTypeExplicit;
@@ -51,9 +50,12 @@ EipStatus EstablishClass3Connection(ConnectionObject *connection_object,
   return eip_status;
   return eip_status;
 }
 }
 
 
+/** @brief Searches and returns a free explicit connection slot
+ *
+ * @return Free explicit connection slot, or NULL if no slot is free
+ */
 ConnectionObject *GetFreeExplicitConnection(void) {
 ConnectionObject *GetFreeExplicitConnection(void) {
-  int i;
-  for (i = 0; i < OPENER_CIP_NUM_EXPLICIT_CONNS; i++) {
+  for (int i = 0; i < OPENER_CIP_NUM_EXPLICIT_CONNS; i++) {
     if (g_explicit_connections[i].state == kConnectionStateNonExistent)
     if (g_explicit_connections[i].state == kConnectionStateNonExistent)
       return &(g_explicit_connections[i]);
       return &(g_explicit_connections[i]);
   }
   }

+ 9 - 5
source/src/cip/cipclass3connection.h

@@ -17,15 +17,19 @@
 /** @brief Check if Class3 connection is available and if yes setup all data.
 /** @brief Check if Class3 connection is available and if yes setup all data.
  *
  *
  * This function can be called after all data has been parsed from the forward open request
  * This function can be called after all data has been parsed from the forward open request
- * @param pa_pstConnObj pointer to the connection object structure holding the parsed data from the forward open request
- * @param pa_pnExtendedError the extended error code in case an error happened
+ * @param connection_object pointer to the connection object structure holding the parsed data from the forward open request
+ * @param extended_error the extended error code in case an error happened
  * @return general status on the establishment
  * @return general status on the establishment
- *    - EIP_OK ... on success
+ *    - kEipStatusOk ... on success
  *    - On an error the general status code to be put into the response
  *    - On an error the general status code to be put into the response
  */
  */
-EipStatus EstablishClass3Connection(ConnectionObject *connection_object,
-                              EipUint16 *extended_error);
+EipStatus EstablishClass3Connection(ConnectionObject *restrict const connection_object,
+                              EipUint16 *const extended_error);
 
 
+/** @brief Initializes the explicit connections mechanism
+ *
+ *  Prepares the available explicit connection slots for use at the start of the OpENer
+ */
 void InitializeClass3ConnectionData(void);
 void InitializeClass3ConnectionData(void);
 
 
 #endif /* OPENER_CIPCLASS3CONNECTION_H_ */
 #endif /* OPENER_CIPCLASS3CONNECTION_H_ */

+ 122 - 144
source/src/cip/cipcommon.c

@@ -23,18 +23,17 @@
 #include "appcontype.h"
 #include "appcontype.h"
 
 
 /* global public variables */
 /* global public variables */
-EipUint8 g_message_data_reply_buffer[OPENER_MESSAGE_DATA_REPLY_BUFFER];
+EipUint8 g_message_data_reply_buffer[OPENER_MESSAGE_DATA_REPLY_BUFFER]; /**< Reply buffer */
 
 
-const EipUint16 kCipUintZero = 0;
+const EipUint16 kCipUintZero = 0; /**< Zero value for returning the UINT standard value */
 
 
 /* private functions*/
 /* private functions*/
 int EncodeEPath(CipEpath *epath, EipUint8 **message);
 int EncodeEPath(CipEpath *epath, EipUint8 **message);
 
 
-void CipStackInit(EipUint16 unique_connection_id) {
-  EipStatus eip_status;
+void CipStackInit(const EipUint16 unique_connection_id) {
   EncapsulationInit();
   EncapsulationInit();
   /* The message router is the first CIP object be initialized!!! */
   /* The message router is the first CIP object be initialized!!! */
-  eip_status = CipMessageRouterInit();
+  EipStatus eip_status = CipMessageRouterInit();
   OPENER_ASSERT(kEipStatusOk == eip_status);
   OPENER_ASSERT(kEipStatusOk == eip_status);
   eip_status = CipIdentityInit();
   eip_status = CipIdentityInit();
   OPENER_ASSERT(kEipStatusOk == eip_status);
   OPENER_ASSERT(kEipStatusOk == eip_status);
@@ -65,26 +64,22 @@ void ShutdownCipStack(void) {
   DeleteAllClasses();
   DeleteAllClasses();
 }
 }
 
 
-EipStatus NotifyClass(CipClass *cip_class,
-                      CipMessageRouterRequest *message_router_request,
-                      CipMessageRouterResponse *message_router_response) {
-  int i;
-  CipInstance *instance;
-  CipServiceStruct *service;
-  unsigned instance_number; /* my instance number */
+EipStatus NotifyClass(const CipClass *restrict const cip_class,
+                      CipMessageRouterRequest *const message_router_request,
+                      CipMessageRouterResponse *const message_router_response) {
 
 
   /* find the instance: if instNr==0, the class is addressed, else find the instance */
   /* find the instance: if instNr==0, the class is addressed, else find the instance */
-  instance_number = message_router_request->request_path.instance_number; /* get the instance number */
-  instance = GetCipInstance(cip_class, instance_number); /* look up the instance (note that if inst==0 this will be the class itself) */
+  EipUint16 instance_number = message_router_request->request_path.instance_number; /* get the instance number */
+  CipInstance * instance = GetCipInstance(cip_class, instance_number); /* look up the instance (note that if inst==0 this will be the class itself) */
   if (instance) /* if instance is found */
   if (instance) /* if instance is found */
   {
   {
     OPENER_TRACE_INFO("notify: found instance %d%s\n", instance_number,
     OPENER_TRACE_INFO("notify: found instance %d%s\n", instance_number,
                       instance_number == 0 ? " (class object)" : "");
                       instance_number == 0 ? " (class object)" : "");
 
 
-    service = instance->cip_class->services; /* get pointer to array of services */
-    if (service) /* if services are defined */
+    CipServiceStruct *service = instance->cip_class->services; /* get pointer to array of services */
+    if (NULL != service) /* if services are defined */
     {
     {
-      for (i = 0; i < instance->cip_class->number_of_services; i++) /* seach the services list */
+      for (int i = 0; i < instance->cip_class->number_of_services; i++) /* seach the services list */
       {
       {
         if (message_router_request->service == service->service_number) /* if match is found */
         if (message_router_request->service == service->service_number) /* if match is found */
         {
         {
@@ -116,10 +111,9 @@ EipStatus NotifyClass(CipClass *cip_class,
   return kEipStatusOkSend;
   return kEipStatusOkSend;
 }
 }
 
 
-CipInstance *AddCipInstances(CipClass *cip_class, int number_of_instances) {
-  CipInstance *first_instance, *current_instance, **next_instance;
-  int i;
-  int instance_number = 1; /* the first instance is number 1 */
+CipInstance *AddCipInstances(CipClass *restrict const cip_class, const int number_of_instances) {
+  CipInstance **next_instance = NULL;
+  EipUint32 instance_number = 1; /* the first instance is number 1 */
 
 
   OPENER_TRACE_INFO("adding %d instances to class %s\n", number_of_instances,
   OPENER_TRACE_INFO("adding %d instances to class %s\n", number_of_instances,
                     cip_class->class_name);
                     cip_class->class_name);
@@ -131,14 +125,16 @@ CipInstance *AddCipInstances(CipClass *cip_class, int number_of_instances) {
     instance_number++; /*    keep track of what the first new instance number will be */
     instance_number++; /*    keep track of what the first new instance number will be */
   }
   }
 
 
-  first_instance = current_instance = (CipInstance *) CipCalloc(
-      number_of_instances, sizeof(CipInstance)); /* allocate a block of memory for all created instances*/
+  CipInstance *current_instance = current_instance = (CipInstance *) CipCalloc(
+        number_of_instances, sizeof(CipInstance)); /* allocate a block of memory for all created instances*/
+  CipInstance *first_instance = current_instance; /* allocate a block of memory for all created instances*/
+
   OPENER_ASSERT(NULL != current_instance);
   OPENER_ASSERT(NULL != current_instance);
   /* fail if run out of memory */
   /* fail if run out of memory */
 
 
   cip_class->number_of_instances += number_of_instances; /* add the number of instances just created to the total recorded by the class */
   cip_class->number_of_instances += number_of_instances; /* add the number of instances just created to the total recorded by the class */
 
 
-  for (i = 0; i < number_of_instances; i++) /* initialize all the new instances */
+  for (int i = 0; i < number_of_instances; i++) /* initialize all the new instances */
   {
   {
     *next_instance = current_instance; /* link the previous pointer to this new node */
     *next_instance = current_instance; /* link the previous pointer to this new node */
 
 
@@ -159,7 +155,7 @@ CipInstance *AddCipInstances(CipClass *cip_class, int number_of_instances) {
   return first_instance;
   return first_instance;
 }
 }
 
 
-CipInstance *AddCIPInstance(CipClass *class, EipUint32 instance_id) {
+CipInstance *AddCIPInstance(CipClass *restrict const class, const EipUint32 instance_id) {
   CipInstance *instance = GetCipInstance(class, instance_id);
   CipInstance *instance = GetCipInstance(class, instance_id);
 
 
   if (0 == instance) { /*we have no instance with given id*/
   if (0 == instance) { /*we have no instance with given id*/
@@ -169,22 +165,19 @@ CipInstance *AddCIPInstance(CipClass *class, EipUint32 instance_id) {
   return instance;
   return instance;
 }
 }
 
 
-CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
-                         EipUint32 get_all_class_attributes_mask,
-                         int number_of_class_services,
-                         int number_of_instance_attributes,
-                         EipUint32 get_all_instance_attributes_mask,
-                         int number_of_instance_services,
-                         int number_of_instances, char *name,
-                         EipUint16 revision) {
-  CipClass *class; /* pointer to the class struct */
-  CipClass *meta_class; /* pointer to the metaclass struct */
+CipClass *CreateCipClass(const EipUint32 class_id, const int number_of_class_attributes,
+                         const EipUint32 get_all_class_attributes_mask,
+                         const int number_of_class_services,
+                         const int number_of_instance_attributes,
+                         const EipUint32 get_all_instance_attributes_mask,
+                         const int number_of_instance_services,
+                         const int number_of_instances, char *name,
+                         const EipUint16 revision) {
 
 
   OPENER_TRACE_INFO("creating class '%s' with id: 0x%"PRIX32"\n", name,
   OPENER_TRACE_INFO("creating class '%s' with id: 0x%"PRIX32"\n", name,
                     class_id);
                     class_id);
 
 
-  class = GetCipClass(class_id); /* check if an class with the ClassID already exists */
-  OPENER_ASSERT(NULL == class);
+  OPENER_ASSERT(NULL == GetCipClass(class_id)); /* check if an class with the ClassID already exists */
   /* should never try to redefine a class*/
   /* should never try to redefine a class*/
 
 
   /* a metaClass is a class that holds the class attributes and services
   /* a metaClass is a class that holds the class attributes and services
@@ -193,8 +186,8 @@ CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
    and contains a pointer to a metaclass
    and contains a pointer to a metaclass
    CIP never explicitly addresses a metaclass*/
    CIP never explicitly addresses a metaclass*/
 
 
-  class = (CipClass*) CipCalloc(1, sizeof(CipClass)); /* create the class object*/
-  meta_class = (CipClass*) CipCalloc(1, sizeof(CipClass)); /* create the metaclass object*/
+  CipClass *const class = (CipClass*) CipCalloc(1, sizeof(CipClass)); /* create the class object*/
+  CipClass *const meta_class = (CipClass*) CipCalloc(1, sizeof(CipClass)); /* create the metaclass object*/
 
 
   /* initialize the class-specific fields of the Class struct*/
   /* initialize the class-specific fields of the Class struct*/
   class->class_id = class_id; /* the class remembers the class ID */
   class->class_id = class_id; /* the class remembers the class ID */
@@ -220,19 +213,19 @@ CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
   strcat(meta_class->class_name, name);
   strcat(meta_class->class_name, name);
 
 
   /* initialize the instance-specific fields of the Class struct*/
   /* initialize the instance-specific fields of the Class struct*/
-  class->m_stSuper.instance_number = 0; /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
-  class->m_stSuper.attributes = 0; /* this will later point to the class attibutes*/
-  class->m_stSuper.cip_class = meta_class; /* the class's class is the metaclass (like SmallTalk)*/
-  class->m_stSuper.next = 0; /* the next link will always be zero, sinc there is only one instance of any particular class object */
+  class->class_instance.instance_number = 0; /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
+  class->class_instance.attributes = 0; /* this will later point to the class attibutes*/
+  class->class_instance.cip_class = meta_class; /* the class's class is the metaclass (like SmallTalk)*/
+  class->class_instance.next = 0; /* the next link will always be zero, sinc there is only one instance of any particular class object */
 
 
-  meta_class->m_stSuper.instance_number = 0xffffffff; /*the metaclass object does not really have a valid instance number*/
-  meta_class->m_stSuper.attributes = 0; /* the metaclass has no attributes*/
-  meta_class->m_stSuper.cip_class = 0; /* the metaclass has no class*/
-  meta_class->m_stSuper.next = 0; /* the next link will always be zero, since there is only one instance of any particular metaclass object*/
+  meta_class->class_instance.instance_number = 0xffffffff; /*the metaclass object does not really have a valid instance number*/
+  meta_class->class_instance.attributes = 0; /* the metaclass has no attributes*/
+  meta_class->class_instance.cip_class = 0; /* the metaclass has no class*/
+  meta_class->class_instance.next = 0; /* the next link will always be zero, since there is only one instance of any particular metaclass object*/
 
 
   /* further initialization of the class object*/
   /* further initialization of the class object*/
 
 
-  class->m_stSuper.attributes = (CipAttributeStruct *) CipCalloc(
+  class->class_instance.attributes = (CipAttributeStruct *) CipCalloc(
       meta_class->number_of_attributes, sizeof(CipAttributeStruct));
       meta_class->number_of_attributes, sizeof(CipAttributeStruct));
   /* TODO -- check that we didn't run out of memory?*/
   /* TODO -- check that we didn't run out of memory?*/
 
 
@@ -286,15 +279,13 @@ CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
   return class;
   return class;
 }
 }
 
 
-void InsertAttribute(CipInstance *instance, EipUint16 attribute_number,
-                     EipUint8 cip_type, void *data, EipByte cip_flags) {
-  int i;
-  CipAttributeStruct *attribute;
+void InsertAttribute(CipInstance *const instance, const EipUint16 attribute_number,
+                     const EipUint8 cip_type, void *const data, const EipByte cip_flags) {
 
 
-  attribute = instance->attributes;
+  CipAttributeStruct *attribute = instance->attributes;
   OPENER_ASSERT(NULL != attribute);
   OPENER_ASSERT(NULL != attribute);
   /* adding a attribute to a class that was not declared to have any attributes is not allowed */
   /* adding a attribute to a class that was not declared to have any attributes is not allowed */
-  for (i = 0; i < instance->cip_class->number_of_attributes; i++) {
+  for (int i = 0; i < instance->cip_class->number_of_attributes; i++) {
     if (attribute->data == NULL) { /* found non set attribute */
     if (attribute->data == NULL) { /* found non set attribute */
       attribute->attribute_number = attribute_number;
       attribute->attribute_number = attribute_number;
       attribute->type = cip_type;
       attribute->type = cip_type;
@@ -312,57 +303,55 @@ void InsertAttribute(CipInstance *instance, EipUint16 attribute_number,
 
 
   OPENER_TRACE_ERR(
   OPENER_TRACE_ERR(
       "Tried to insert to many attributes into class: %"PRIu32", instance %"PRIu32"\n",
       "Tried to insert to many attributes into class: %"PRIu32", instance %"PRIu32"\n",
-      instance->cip_class->m_stSuper.instance_number,
+      instance->cip_class->class_instance.instance_number,
       instance->instance_number);
       instance->instance_number);
   OPENER_ASSERT(0);
   OPENER_ASSERT(0);
   /* trying to insert too many attributes*/
   /* trying to insert too many attributes*/
 }
 }
 
 
-void InsertService(CipClass * class, EipUint8 service_number,
-                   CipServiceFunction service_function, char *service_name) {
-  int i;
-  CipServiceStruct *p;
+void InsertService(const CipClass *const class, const EipUint8 service_number,
+                   const CipServiceFunction service_function, char *const service_name) {
 
 
-  p = class->services; /* get a pointer to the service array*/
-  OPENER_ASSERT(p != 0);
+  CipServiceStruct *service = class->services; /* get a pointer to the service array*/
+  OPENER_ASSERT(service != 0);
   /* adding a service to a class that was not declared to have services is not allowed*/
   /* adding a service to a class that was not declared to have services is not allowed*/
-  for (i = 0; i < class->number_of_services; i++) /* Iterate over all service slots attached to the class */
+  for (int i = 0; i < class->number_of_services; i++) /* Iterate over all service slots attached to the class */
   {
   {
-    if (p->service_number == service_number || p->service_function == NULL) /* found undefined service slot*/
+    if (service->service_number == service_number || service->service_function == NULL) /* found undefined service slot*/
     {
     {
-      p->service_number = service_number; /* fill in service number*/
-      p->service_function = service_function; /* fill in function address*/
-      p->name = service_name;
+      service->service_number = service_number; /* fill in service number*/
+      service->service_function = service_function; /* fill in function address*/
+      service->name = service_name;
       return;
       return;
     }
     }
-    p++;
+    ++service;
   }
   }
   OPENER_ASSERT(0);
   OPENER_ASSERT(0);
   /* adding more services than were declared is a no-no*/
   /* adding more services than were declared is a no-no*/
 }
 }
 
 
-CipAttributeStruct *GetCipAttribute(CipInstance * instance,
-                                    EipUint16 attribute_number) {
-  int i;
+CipAttributeStruct *GetCipAttribute(const CipInstance *const instance,
+                                    const EipUint16 attribute_number) {
+
   CipAttributeStruct *attribute = instance->attributes; /* init pointer to array of attributes*/
   CipAttributeStruct *attribute = instance->attributes; /* init pointer to array of attributes*/
-  for (i = 0; i < instance->cip_class->number_of_attributes; i++) {
+  for (int i = 0; i < instance->cip_class->number_of_attributes; i++) {
     if (attribute_number == attribute->attribute_number)
     if (attribute_number == attribute->attribute_number)
       return attribute;
       return attribute;
     else
     else
-      attribute++;
+      ++attribute;
   }
   }
 
 
   OPENER_TRACE_WARN("attribute %d not defined\n", attribute_number);
   OPENER_TRACE_WARN("attribute %d not defined\n", attribute_number);
 
 
-  return 0;
+  return NULL;
 }
 }
 
 
 /* TODO this needs to check for buffer overflow*/
 /* TODO this needs to check for buffer overflow*/
-EipStatus GetAttributeSingle(CipInstance *instance,
-                             CipMessageRouterRequest *message_router_request,
-                             CipMessageRouterResponse *message_router_response) {
+EipStatus GetAttributeSingle(CipInstance *restrict const instance,
+                             CipMessageRouterRequest *const message_router_request,
+                             CipMessageRouterResponse *const message_router_response) {
   /* Mask for filtering get-ability */
   /* Mask for filtering get-ability */
-  EipByte get_mask;
+  EipByte get_mask = kNotSetOrGetable;
 
 
   CipAttributeStruct *attribute = GetCipAttribute(
   CipAttributeStruct *attribute = GetCipAttribute(
       instance, message_router_request->request_path.attribute_number);
       instance, message_router_request->request_path.attribute_number);
@@ -409,7 +398,7 @@ EipStatus GetAttributeSingle(CipInstance *instance,
   return kEipStatusOkSend;
   return kEipStatusOkSend;
 }
 }
 
 
-int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
+int EncodeData(const EipUint8 cip_type, const void *const cip_data, EipUint8 **cip_message) {
   int counter = 0;
   int counter = 0;
 
 
   switch (cip_type)
   switch (cip_type)
@@ -419,24 +408,20 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
     case (kCipSint):
     case (kCipSint):
     case (kCipUsint):
     case (kCipUsint):
     case (kCipByte):
     case (kCipByte):
-      **message = *(EipUint8 *) (data);
-      ++(*message);
-      counter = 1;
+      counter = AddSintToMessage(*(EipUint8 *) (cip_data), cip_message);
       break;
       break;
 
 
     case (kCipInt):
     case (kCipInt):
     case (kCipUint):
     case (kCipUint):
     case (kCipWord):
     case (kCipWord):
-      AddIntToMessage(*(EipUint16 *) (data), message);
-      counter = 2;
+      counter = AddIntToMessage(*(EipUint16 *) (cip_data), cip_message);
       break;
       break;
 
 
     case (kCipDint):
     case (kCipDint):
     case (kCipUdint):
     case (kCipUdint):
     case (kCipDword):
     case (kCipDword):
     case (kCipReal):
     case (kCipReal):
-      AddDintToMessage(*(EipUint32 *) (data), message);
-      counter = 4;
+      counter = AddDintToMessage(*(EipUint32 *) (cip_data), cip_message);
       break;
       break;
 
 
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
@@ -444,8 +429,7 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
     case (kCipUlint):
     case (kCipUlint):
     case (kCipLword):
     case (kCipLword):
     case (kCipLreal):
     case (kCipLreal):
-      AddLintToMessage(*(EipUint64 *) (data), message);
-      counter = 8;
+      counter = AddLintToMessage(*(EipUint64 *) (cip_data), cip_message);
       break;
       break;
 #endif
 #endif
 
 
@@ -455,17 +439,17 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
     case (kCipDateAndTime):
     case (kCipDateAndTime):
       break;
       break;
     case (kCipString): {
     case (kCipString): {
-      CipString *string = (CipString *) data;
+      CipString *const string = (CipString *) cip_data;
 
 
-      AddIntToMessage(*(EipUint16 *) &(string->length), message);
-      memcpy(*message, string->string, string->length);
-      *message += string->length;
+      AddIntToMessage(*(EipUint16 *) &(string->length), cip_message);
+      memcpy(*cip_message, string->string, string->length);
+      *cip_message += string->length;
 
 
       counter = string->length + 2; /* we have a two byte length field */
       counter = string->length + 2; /* we have a two byte length field */
       if (counter & 0x01) {
       if (counter & 0x01) {
         /* we have an odd byte count */
         /* we have an odd byte count */
-        **message = 0;
-        ++(*message);
+        **cip_message = 0;
+        ++(*cip_message);
         counter++;
         counter++;
       }
       }
       break;
       break;
@@ -478,13 +462,13 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
       break;
       break;
 
 
     case (kCipShortString): {
     case (kCipShortString): {
-      CipShortString *short_string = (CipShortString *) data;
+      CipShortString *const short_string = (CipShortString *) cip_data;
 
 
-      **message = short_string->length;
-      ++(*message);
+      **cip_message = short_string->length;
+      ++(*cip_message);
 
 
-      memcpy(*message, short_string->string, short_string->length);
-      *message += short_string->length;
+      memcpy(*cip_message, short_string->string, short_string->length);
+      *cip_message += short_string->length;
 
 
       counter = short_string->length + 1;
       counter = short_string->length + 1;
       break;
       break;
@@ -494,19 +478,19 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
       break;
       break;
 
 
     case (kCipEpath):
     case (kCipEpath):
-      counter = EncodeEPath((CipEpath *) data, message);
+      counter = EncodeEPath((CipEpath *) cip_data, cip_message);
       break;
       break;
 
 
     case (kCipEngUnit):
     case (kCipEngUnit):
       break;
       break;
 
 
     case (kCipUsintUsint): {
     case (kCipUsintUsint): {
-      CipRevision *revision = (CipRevision *) data;
+      CipRevision *revision = (CipRevision *) cip_data;
 
 
-      **message = revision->major_revision;
-      ++(*message);
-      **message = revision->minor_revision;
-      ++(*message);
+      **cip_message = revision->major_revision;
+      ++(*cip_message);
+      **cip_message = revision->minor_revision;
+      ++(*cip_message);
       counter = 2;
       counter = 2;
       break;
       break;
     }
     }
@@ -514,28 +498,27 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
     case (kCipUdintUdintUdintUdintUdintString): {
     case (kCipUdintUdintUdintUdintUdintString): {
       /* TCP/IP attribute 5 */
       /* TCP/IP attribute 5 */
       CipTcpIpNetworkInterfaceConfiguration *tcp_ip_network_interface_configuration =
       CipTcpIpNetworkInterfaceConfiguration *tcp_ip_network_interface_configuration =
-          (CipTcpIpNetworkInterfaceConfiguration *) data;
-      AddDintToMessage(
-          ntohl(tcp_ip_network_interface_configuration->ip_address), message);
-      AddDintToMessage(
-          ntohl(tcp_ip_network_interface_configuration->network_mask), message);
-      AddDintToMessage(ntohl(tcp_ip_network_interface_configuration->gateway),
-                       message);
-      AddDintToMessage(
-          ntohl(tcp_ip_network_interface_configuration->name_server), message);
-      AddDintToMessage(
+          (CipTcpIpNetworkInterfaceConfiguration *) cip_data;
+      counter += AddDintToMessage(
+          ntohl(tcp_ip_network_interface_configuration->ip_address), cip_message);
+      counter += AddDintToMessage(
+          ntohl(tcp_ip_network_interface_configuration->network_mask), cip_message);
+      counter += AddDintToMessage(ntohl(tcp_ip_network_interface_configuration->gateway),
+                       cip_message);
+      counter += AddDintToMessage(
+          ntohl(tcp_ip_network_interface_configuration->name_server), cip_message);
+      counter += AddDintToMessage(
           ntohl(tcp_ip_network_interface_configuration->name_server_2),
           ntohl(tcp_ip_network_interface_configuration->name_server_2),
-          message);
-      counter = 20;
+          cip_message);
       counter += EncodeData(
       counter += EncodeData(
           kCipString, &(tcp_ip_network_interface_configuration->domain_name),
           kCipString, &(tcp_ip_network_interface_configuration->domain_name),
-          message);
+          cip_message);
       break;
       break;
     }
     }
 
 
     case (kCip6Usint): {
     case (kCip6Usint): {
-      EipUint8 *p = (EipUint8 *) data;
-      memcpy(*message, p, 6);
+      EipUint8 *p = (EipUint8 *) cip_data;
+      memcpy(*cip_message, p, 6);
       counter = 6;
       counter = 6;
       break;
       break;
     }
     }
@@ -544,25 +527,24 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
       break;
       break;
 
 
     case (kCipByteArray): {
     case (kCipByteArray): {
-      CipByteArray *cip_byte_array;
       OPENER_TRACE_INFO(" -> get attribute byte array\r\n");
       OPENER_TRACE_INFO(" -> get attribute byte array\r\n");
-      cip_byte_array = (CipByteArray *) data;
-      memcpy(*message, cip_byte_array->data, cip_byte_array->length);
-      *message += cip_byte_array->length;
+      CipByteArray *cip_byte_array = (CipByteArray *) cip_data;
+      memcpy(*cip_message, cip_byte_array->data, cip_byte_array->length);
+      *cip_message += cip_byte_array->length;
       counter = cip_byte_array->length;
       counter = cip_byte_array->length;
     }
     }
       break;
       break;
 
 
     case (kInternalUint6): /* TODO for port class attribute 9, hopefully we can find a better way to do this*/
     case (kInternalUint6): /* TODO for port class attribute 9, hopefully we can find a better way to do this*/
     {
     {
-      EipUint16 *internal_unit16_6 = (EipUint16 *) data;
-
-      AddIntToMessage(internal_unit16_6[0], message);
-      AddIntToMessage(internal_unit16_6[1], message);
-      AddIntToMessage(internal_unit16_6[2], message);
-      AddIntToMessage(internal_unit16_6[3], message);
-      AddIntToMessage(internal_unit16_6[4], message);
-      AddIntToMessage(internal_unit16_6[5], message);
+      EipUint16 *internal_unit16_6 = (EipUint16 *) cip_data;
+
+      AddIntToMessage(internal_unit16_6[0], cip_message);
+      AddIntToMessage(internal_unit16_6[1], cip_message);
+      AddIntToMessage(internal_unit16_6[2], cip_message);
+      AddIntToMessage(internal_unit16_6[3], cip_message);
+      AddIntToMessage(internal_unit16_6[4], cip_message);
+      AddIntToMessage(internal_unit16_6[5], cip_message);
       counter = 12;
       counter = 12;
       break;
       break;
     }
     }
@@ -574,7 +556,7 @@ int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
   return counter;
   return counter;
 }
 }
 
 
-int DecodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
+int DecodeData(const EipUint8 cip_type, void *const data, const EipUint8 **const message) {
   int number_of_decoded_bytes = -1;
   int number_of_decoded_bytes = -1;
 
 
   switch (cip_type)
   switch (cip_type)
@@ -650,20 +632,16 @@ int DecodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
 EipStatus GetAttributeAll(CipInstance *instance,
 EipStatus GetAttributeAll(CipInstance *instance,
                           CipMessageRouterRequest *message_router_request,
                           CipMessageRouterRequest *message_router_request,
                           CipMessageRouterResponse *message_router_response) {
                           CipMessageRouterResponse *message_router_response) {
-  int i, j;
-  EipUint8 *reply;
-  CipAttributeStruct *attribute;
-  CipServiceStruct *service;
 
 
-  reply = message_router_response->data; /* pointer into the reply */
-  attribute = instance->attributes; /* pointer to list of attributes*/
-  service = instance->cip_class->services; /* pointer to list of services*/
+  EipUint8 *reply = message_router_response->data; /* pointer into the reply */
+  CipAttributeStruct *attribute = instance->attributes; /* pointer to list of attributes*/
+  CipServiceStruct *service = instance->cip_class->services; /* pointer to list of services*/
 
 
   if (instance->instance_number == 2) {
   if (instance->instance_number == 2) {
     OPENER_TRACE_INFO("GetAttributeAll: instance number 2\n");
     OPENER_TRACE_INFO("GetAttributeAll: instance number 2\n");
   }
   }
 
 
-  for (i = 0; i < instance->cip_class->number_of_services; i++) /* hunt for the GET_ATTRIBUTE_SINGLE service*/
+  for (int i = 0; i < instance->cip_class->number_of_services; i++) /* hunt for the GET_ATTRIBUTE_SINGLE service*/
   {
   {
     if (service->service_number == kGetAttributeSingle) /* found the service */
     if (service->service_number == kGetAttributeSingle) /* found the service */
     {
     {
@@ -674,7 +652,7 @@ EipStatus GetAttributeAll(CipInstance *instance,
         message_router_response->general_status = kCipErrorServiceNotSupported;
         message_router_response->general_status = kCipErrorServiceNotSupported;
         message_router_response->size_of_additional_status = 0;
         message_router_response->size_of_additional_status = 0;
       } else {
       } else {
-        for (j = 0; j < instance->cip_class->number_of_attributes; j++) /* for each instance attribute of this class */
+        for (int j = 0; j < instance->cip_class->number_of_attributes; j++) /* for each instance attribute of this class */
         {
         {
           int attrNum = attribute->attribute_number;
           int attrNum = attribute->attribute_number;
           if (attrNum < 32
           if (attrNum < 32
@@ -759,9 +737,9 @@ int EncodeEPath(CipEpath *epath, EipUint8 **message) {
   return 2 + epath->path_size * 2; /* path size is in 16 bit chunks according to the specification */
   return 2 + epath->path_size * 2; /* path size is in 16 bit chunks according to the specification */
 }
 }
 
 
-int DecodePaddedEPath(CipEpath *epath, EipUint8 **message) {
-  unsigned int number_of_decoded_elements;
-  EipUint8 *message_runner = *message;
+int DecodePaddedEPath(CipEpath *epath, const EipUint8 **message) {
+  unsigned int number_of_decoded_elements = 0;
+  const EipUint8 *message_runner = *message;
 
 
   epath->path_size = *message_runner;
   epath->path_size = *message_runner;
   message_runner++;
   message_runner++;

+ 12 - 12
source/src/cip/cipcommon.h

@@ -27,27 +27,27 @@ extern EipUint8 g_message_data_reply_buffer[];
  * @param message_router_request request message
  * @param message_router_request request message
  * @param message_router_response reply message
  * @param message_router_response reply message
  * @return
  * @return
- *     - EIP_OK_SEND    ... success
- *     - EIP_OK  ... no reply to send back
- *     - EIP_ERROR ... error
+ *     - kEipStatusOkSend ... success
+ *     - kEipStatusOk ... no reply to send back
+ *     - kEipStatusError ... error
  */
  */
-EipStatus NotifyClass(CipClass *class,
-                      CipMessageRouterRequest *message_router_request,
-                      CipMessageRouterResponse *message_router_response);
+EipStatus NotifyClass(const CipClass *restrict const class,
+                      CipMessageRouterRequest *const message_router_request,
+                      CipMessageRouterResponse *const message_router_response);
 
 
 /** @brief Generic implementation of the GetAttributeSingle CIP service
 /** @brief Generic implementation of the GetAttributeSingle CIP service
  *
  *
- *  Check from classID which Object requests an attribute, search if object has
- *  the appropriate attribute implemented.
+ * Check from classID which Object requests an attribute, search if object has
+ * the appropriate attribute implemented.
  * @param instance pointer to instance.
  * @param instance pointer to instance.
  * @param message_router_request pointer to request.
  * @param message_router_request pointer to request.
  * @param message_router_response pointer to response.
  * @param message_router_response pointer to response.
  * @return status  >0 .. success
  * @return status  >0 .. success
  *          -1 .. requested attribute not available
  *          -1 .. requested attribute not available
  */
  */
-EipStatus GetAttributeSingle(CipInstance *instance,
-                             CipMessageRouterRequest *message_router_request,
-                             CipMessageRouterResponse *message_router_response);
+EipStatus GetAttributeSingle(CipInstance *restrict const instance,
+                             CipMessageRouterRequest *const message_router_request,
+                             CipMessageRouterResponse *const message_router_response);
 
 
 /** @brief Generic implementation of the GetAttributeAll CIP service
 /** @brief Generic implementation of the GetAttributeAll CIP service
  *
  *
@@ -67,6 +67,6 @@ EipStatus GetAttributeAll(CipInstance *instance,
  *  @param message CIP Message to decode
  *  @param message CIP Message to decode
  *  @return Number of decoded bytes
  *  @return Number of decoded bytes
  */
  */
-int DecodePaddedEPath(CipEpath *epath, EipUint8 **data);
+int DecodePaddedEPath(CipEpath *epath, const EipUint8 **data);
 
 
 #endif /* OPENER_CIPCOMMON_H_ */
 #endif /* OPENER_CIPCOMMON_H_ */

+ 71 - 76
source/src/cip/cipconnectionmanager.c

@@ -49,7 +49,7 @@ typedef struct {
 /** List holding information on the object classes and open/close function
 /** List holding information on the object classes and open/close function
  * pointers to which connections may be established.
  * pointers to which connections may be established.
  */
  */
-ConnectionManagementHandling g_astConnMgmList[2
+ConnectionManagementHandling g_connection_management_list[2
     + OPENER_CIP_NUM_APPLICATION_SPECIFIC_CONNECTABLE_OBJECTS];
     + OPENER_CIP_NUM_APPLICATION_SPECIFIC_CONNECTABLE_OBJECTS];
 
 
 /** List holding all currently active connections*/
 /** List holding all currently active connections*/
@@ -125,7 +125,7 @@ EipUint8 ParseConnectionPath(ConnectionObject *connection_object,
                              CipMessageRouterRequest *message_router_request,
                              CipMessageRouterRequest *message_router_request,
                              EipUint16 *extended_error);
                              EipUint16 *extended_error);
 
 
-ConnectionManagementHandling* GetConnMgmEntry(EipUint32 class_id);
+ConnectionManagementHandling* GetConnectionManagementEntry(EipUint32 class_id);
 
 
 void InitializeConnectionManagerData(void);
 void InitializeConnectionManagerData(void);
 
 
@@ -135,8 +135,9 @@ void AddNullAddressItem(
 /** @brief gets the padded logical path TODO: enhance documentation
 /** @brief gets the padded logical path TODO: enhance documentation
  * @param logical_path_segment TheLogical Path Segment
  * @param logical_path_segment TheLogical Path Segment
  *
  *
+ * @return The padded logical path
  */
  */
-unsigned int GetPaddedLogicalPath(unsigned char **logical_path_segment) {
+unsigned int GetPaddedLogicalPath(const EipUint8 **logical_path_segment) {
   unsigned int padded_logical_path = *(*logical_path_segment)++;
   unsigned int padded_logical_path = *(*logical_path_segment)++;
 
 
   if ((padded_logical_path & 3) == 0) {
   if ((padded_logical_path & 3) == 0) {
@@ -251,18 +252,17 @@ EipStatus HandleReceivedConnectedData(EipUint8 *data, int data_length,
   return kEipStatusOk;
   return kEipStatusOk;
 }
 }
 
 
-/*   @brief Check if resources for new connection available, generate ForwardOpen Reply message.
- *      instance	pointer to CIP object instance
- *      message_router_request		pointer to Message Router Request.
- *      message_router_response		pointer to Message Router Response.
- * 		@return >0 .. success, 0 .. no reply to send back
+/** @brief Check if resources for new connection available, generate ForwardOpen Reply message.
+ *  @param instance	pointer to CIP object instance
+ *  @param message_router_request		pointer to Message Router Request.
+ *  @param message_router_response		pointer to Message Router Response.
+ * 	@return >0 .. success, 0 .. no reply to send back
  *      	-1 .. error
  *      	-1 .. error
  */
  */
 EipStatus ForwardOpen(CipInstance *instance,
 EipStatus ForwardOpen(CipInstance *instance,
                       CipMessageRouterRequest *message_router_request,
                       CipMessageRouterRequest *message_router_request,
                       CipMessageRouterResponse *message_router_response) {
                       CipMessageRouterResponse *message_router_response) {
   EipUint16 connection_status = kConnectionManagerStatusCodeSuccess;
   EipUint16 connection_status = kConnectionManagerStatusCodeSuccess;
-  ConnectionManagementHandling *connection_management_entry;
 
 
   (void) instance; /*suppress compiler warning */
   (void) instance; /*suppress compiler warning */
 
 
@@ -373,7 +373,7 @@ EipStatus ForwardOpen(CipInstance *instance,
   }
   }
 
 
   /*parsing is now finished all data is available and check now establish the connection */
   /*parsing is now finished all data is available and check now establish the connection */
-  connection_management_entry = GetConnMgmEntry(
+  ConnectionManagementHandling *connection_management_entry = GetConnectionManagementEntry(
       g_dummy_connection_object.connection_path.class_id);
       g_dummy_connection_object.connection_path.class_id);
   if (NULL != connection_management_entry) {
   if (NULL != connection_management_entry) {
     temp = connection_management_entry->open_connection_function(
     temp = connection_management_entry->open_connection_function(
@@ -524,7 +524,6 @@ EipStatus GetConnectionOwner(CipInstance *instance,
 }
 }
 
 
 EipStatus ManageConnections(MilliSeconds elapsed_time) {
 EipStatus ManageConnections(MilliSeconds elapsed_time) {
-  EipStatus eip_status;
   ConnectionObject *connection_object;
   ConnectionObject *connection_object;
 
 
   /*Inform application that it can execute */
   /*Inform application that it can execute */
@@ -567,7 +566,7 @@ EipStatus ManageConnections(MilliSeconds elapsed_time) {
           if (connection_object->transmission_trigger_timer <= 0) { /* need to send package */
           if (connection_object->transmission_trigger_timer <= 0) { /* need to send package */
             OPENER_ASSERT(
             OPENER_ASSERT(
                 NULL != connection_object->connection_send_data_function);
                 NULL != connection_object->connection_send_data_function);
-            eip_status = connection_object->connection_send_data_function(
+            EipStatus eip_status = connection_object->connection_send_data_function(
                 connection_object);
                 connection_object);
             if (eip_status == kEipStatusError) {
             if (eip_status == kEipStatusError) {
               OPENER_TRACE_ERR(
               OPENER_TRACE_ERR(
@@ -700,7 +699,7 @@ EipStatus AssembleForwardOpenResponse(
 }
 }
 
 
 /**
 /**
- * Adds a Null Address Item to the common data packet format data
+ * @brief Adds a Null Address Item to the common data packet format data
  * @param common_data_packet_format_data The CPF data packet where the Null Address Item shall be added
  * @param common_data_packet_format_data The CPF data packet where the Null Address Item shall be added
  */
  */
 void AddNullAddressItem(
 void AddNullAddressItem(
@@ -897,7 +896,7 @@ EipStatus CheckElectronicKeyData(EipUint8 key_format, CipKeyData *key_data,
 EipUint8 ParseConnectionPath(ConnectionObject *connection_object,
 EipUint8 ParseConnectionPath(ConnectionObject *connection_object,
                              CipMessageRouterRequest *message_router_request,
                              CipMessageRouterRequest *message_router_request,
                              EipUint16 *extended_error) {
                              EipUint16 *extended_error) {
-  EipUint8 *message = message_router_request->data;
+  const EipUint8 *message = message_router_request->data;
   int remaining_path_size = connection_object->connection_path_size =
   int remaining_path_size = connection_object->connection_path_size =
       *message++; /* length in words */
       *message++; /* length in words */
   CipClass *class = NULL;
   CipClass *class = NULL;
@@ -1105,7 +1104,7 @@ EipUint8 ParseConnectionPath(ConnectionObject *connection_object,
           case kDataSegmentTypeSimpleDataMessage:
           case kDataSegmentTypeSimpleDataMessage:
             /* we have a simple data segment */
             /* we have a simple data segment */
             g_config_data_length = message[1] * 2; /*data segments store length 16-bit word wise */
             g_config_data_length = message[1] * 2; /*data segments store length 16-bit word wise */
-            g_config_data_buffer = &(message[2]);
+            g_config_data_buffer = (EipUint8 *)message + 2;
             remaining_path_size -= (g_config_data_length + 2);
             remaining_path_size -= (g_config_data_length + 2);
             message += (g_config_data_length + 2);
             message += (g_config_data_length + 2);
             break;
             break;
@@ -1141,128 +1140,124 @@ EipUint8 ParseConnectionPath(ConnectionObject *connection_object,
   return kEipStatusOk;
   return kEipStatusOk;
 }
 }
 
 
-void CloseConnection(ConnectionObject *pa_pstConnObj) {
-  pa_pstConnObj->state = kConnectionStateNonExistent;
-  if (0x03 != (pa_pstConnObj->transport_type_class_trigger & 0x03)) {
+void CloseConnection(ConnectionObject *restrict connection_object) {
+  connection_object->state = kConnectionStateNonExistent;
+  if (0x03 != (connection_object->transport_type_class_trigger & 0x03)) {
     /* only close the UDP connection for not class 3 connections */
     /* only close the UDP connection for not class 3 connections */
     IApp_CloseSocket_udp(
     IApp_CloseSocket_udp(
-        pa_pstConnObj->socket[kUdpCommuncationDirectionConsuming]);
-    pa_pstConnObj->socket[kUdpCommuncationDirectionConsuming] =
+        connection_object->socket[kUdpCommuncationDirectionConsuming]);
+    connection_object->socket[kUdpCommuncationDirectionConsuming] =
         kEipInvalidSocket;
         kEipInvalidSocket;
     IApp_CloseSocket_udp(
     IApp_CloseSocket_udp(
-        pa_pstConnObj->socket[kUdpCommuncationDirectionProducing]);
-    pa_pstConnObj->socket[kUdpCommuncationDirectionProducing] =
+        connection_object->socket[kUdpCommuncationDirectionProducing]);
+    connection_object->socket[kUdpCommuncationDirectionProducing] =
         kEipInvalidSocket;
         kEipInvalidSocket;
   }
   }
-  RemoveFromActiveConnections(pa_pstConnObj);
+  RemoveFromActiveConnections(connection_object);
 }
 }
 
 
-void CopyConnectionData(ConnectionObject *pa_pstDst,
-                        ConnectionObject *pa_pstSrc) {
-  memcpy(pa_pstDst, pa_pstSrc, sizeof(ConnectionObject));
+void CopyConnectionData(ConnectionObject *restrict destination,
+                        const ConnectionObject *restrict const source) {
+  memcpy(destination, source, sizeof(ConnectionObject));
 }
 }
 
 
-void AddNewActiveConnection(ConnectionObject *pa_pstConn) {
-  pa_pstConn->first_connection_object = NULL;
-  pa_pstConn->next_connection_object = g_active_connection_list;
+void AddNewActiveConnection(ConnectionObject *connection_object) {
+  connection_object->first_connection_object = NULL;
+  connection_object->next_connection_object = g_active_connection_list;
   if (NULL != g_active_connection_list) {
   if (NULL != g_active_connection_list) {
-    g_active_connection_list->first_connection_object = pa_pstConn;
+    g_active_connection_list->first_connection_object = connection_object;
   }
   }
-  g_active_connection_list = pa_pstConn;
+  g_active_connection_list = connection_object;
   g_active_connection_list->state = kConnectionStateEstablished;
   g_active_connection_list->state = kConnectionStateEstablished;
 }
 }
 
 
-void RemoveFromActiveConnections(ConnectionObject *pa_pstConn) {
-  if (NULL != pa_pstConn->first_connection_object) {
-    pa_pstConn->first_connection_object->next_connection_object = pa_pstConn
+void RemoveFromActiveConnections(ConnectionObject *connection_object) {
+  if (NULL != connection_object->first_connection_object) {
+    connection_object->first_connection_object->next_connection_object = connection_object
         ->next_connection_object;
         ->next_connection_object;
   } else {
   } else {
-    g_active_connection_list = pa_pstConn->next_connection_object;
+    g_active_connection_list = connection_object->next_connection_object;
   }
   }
-  if (NULL != pa_pstConn->next_connection_object) {
-    pa_pstConn->next_connection_object->first_connection_object = pa_pstConn
+  if (NULL != connection_object->next_connection_object) {
+    connection_object->next_connection_object->first_connection_object = connection_object
         ->first_connection_object;
         ->first_connection_object;
   }
   }
-  pa_pstConn->first_connection_object = NULL;
-  pa_pstConn->next_connection_object = NULL;
-  pa_pstConn->state = kConnectionStateNonExistent;
+  connection_object->first_connection_object = NULL;
+  connection_object->next_connection_object = NULL;
+  connection_object->state = kConnectionStateNonExistent;
 }
 }
 
 
-EipBool8 IsConnectedOutputAssembly(EipUint32 pa_nInstanceNr) {
-  EipBool8 bRetVal = false;
+EipBool8 IsConnectedOutputAssembly(const EipUint32 instance_number) {
+  EipBool8 is_connected = false;
 
 
-  ConnectionObject *pstRunner = g_active_connection_list;
+  ConnectionObject *iterator = g_active_connection_list;
 
 
-  while (NULL != pstRunner) {
-    if (pa_nInstanceNr == pstRunner->connection_path.connection_point[0]) {
-      bRetVal = true;
+  while (NULL != iterator) {
+    if (instance_number == iterator->connection_path.connection_point[0]) {
+      is_connected = true;
       break;
       break;
     }
     }
-    pstRunner = pstRunner->next_connection_object;
+    iterator = iterator->next_connection_object;
   }
   }
-  return bRetVal;
+  return is_connected;
 }
 }
 
 
-EipStatus AddConnectableObject(EipUint32 pa_nClassId,
-                               OpenConnectionFunction pa_pfOpenFunc) {
-  int i;
-  EipStatus nRetVal;
-  nRetVal = kEipStatusError;
+EipStatus AddConnectableObject(EipUint32 class_id,
+                               OpenConnectionFunction open_connection_function) {
+  EipStatus status = kEipStatusError;
 
 
   /*parsing is now finished all data is available and check now establish the connection */
   /*parsing is now finished all data is available and check now establish the connection */
-  for (i = 0; i < g_kNumberOfConnectableObjects; ++i) {
-    if ((0 == g_astConnMgmList[i].class_id)
-        || (pa_nClassId == g_astConnMgmList[i].class_id)) {
-      g_astConnMgmList[i].class_id = pa_nClassId;
-      g_astConnMgmList[i].open_connection_function = pa_pfOpenFunc;
-      nRetVal = kEipStatusOk;
+  for (int i = 0; i < g_kNumberOfConnectableObjects; ++i) {
+    if ((0 == g_connection_management_list[i].class_id)
+        || (class_id == g_connection_management_list[i].class_id)) {
+      g_connection_management_list[i].class_id = class_id;
+      g_connection_management_list[i].open_connection_function = open_connection_function;
+      status = kEipStatusOk;
       break;
       break;
     }
     }
   }
   }
 
 
-  return nRetVal;
+  return status;
 }
 }
 
 
 ConnectionManagementHandling *
 ConnectionManagementHandling *
-GetConnMgmEntry(EipUint32 class_id) {
-  int i;
-  ConnectionManagementHandling *pstRetVal;
+GetConnectionManagementEntry(EipUint32 class_id) {
 
 
-  pstRetVal = NULL;
+  ConnectionManagementHandling *connection_management_entry = NULL;
 
 
-  for (i = 0; i < g_kNumberOfConnectableObjects; ++i) {
-    if (class_id == g_astConnMgmList[i].class_id) {
-      pstRetVal = &(g_astConnMgmList[i]);
+  for (int i = 0; i < g_kNumberOfConnectableObjects; ++i) {
+    if (class_id == g_connection_management_list[i].class_id) {
+      connection_management_entry = &(g_connection_management_list[i]);
       break;
       break;
     }
     }
   }
   }
-  return pstRetVal;
+  return connection_management_entry;
 }
 }
 
 
-EipStatus TriggerConnections(unsigned int pa_unOutputAssembly,
-                             unsigned int pa_unInputAssembly) {
-  EipStatus nRetVal = kEipStatusError;
+EipStatus TriggerConnections(unsigned int output_assembly,
+                             unsigned int input_assembly) {
+  EipStatus status = kEipStatusError;
 
 
   ConnectionObject *pstRunner = g_active_connection_list;
   ConnectionObject *pstRunner = g_active_connection_list;
   while (NULL != pstRunner) {
   while (NULL != pstRunner) {
-    if ((pa_unOutputAssembly == pstRunner->connection_path.connection_point[0])
-        && (pa_unInputAssembly == pstRunner->connection_path.connection_point[1])) {
+    if ((output_assembly == pstRunner->connection_path.connection_point[0])
+        && (input_assembly == pstRunner->connection_path.connection_point[1])) {
       if (kConnectionTriggerTypeApplicationTriggeredConnection
       if (kConnectionTriggerTypeApplicationTriggeredConnection
           == (pstRunner->transport_type_class_trigger
           == (pstRunner->transport_type_class_trigger
               & kConnectionTriggerTypeProductionTriggerMask)) {
               & kConnectionTriggerTypeProductionTriggerMask)) {
         /* produce at the next allowed occurrence */
         /* produce at the next allowed occurrence */
         pstRunner->transmission_trigger_timer = pstRunner
         pstRunner->transmission_trigger_timer = pstRunner
             ->production_inhibit_timer;
             ->production_inhibit_timer;
-        nRetVal = kEipStatusOk;
+        status = kEipStatusOk;
       }
       }
       break;
       break;
     }
     }
   }
   }
-  return nRetVal;
+  return status;
 }
 }
 
 
 void InitializeConnectionManagerData() {
 void InitializeConnectionManagerData() {
-  memset(g_astConnMgmList, 0,
+  memset(g_connection_management_list, 0,
          g_kNumberOfConnectableObjects * sizeof(ConnectionManagementHandling));
          g_kNumberOfConnectableObjects * sizeof(ConnectionManagementHandling));
   InitializeClass3ConnectionData();
   InitializeClass3ConnectionData();
   InitializeIoConnectionData();
   InitializeIoConnectionData();

+ 16 - 7
source/src/cip/cipconnectionmanager.h

@@ -226,6 +226,9 @@ static const int g_kCipConnectionManagerClassCode = 0x06;
 /* public functions */
 /* public functions */
 
 
 /** @brief Initialize the data of the connection manager object
 /** @brief Initialize the data of the connection manager object
+ *
+ *  @param A unique connection id
+ *  @return kEipStatusOk if successful, otherwise kEipStatusError
  */
  */
 EipStatus ConnectionManagerInit(EipUint16 unique_connection_id);
 EipStatus ConnectionManagerInit(EipUint16 unique_connection_id);
 
 
@@ -240,15 +243,18 @@ ConnectionObject* GetConnectedObject(EipUint32 connection_id);
 /**  Get a connection object for a given output assembly.
 /**  Get a connection object for a given output assembly.
  *
  *
  *   @param output_assembly_id requested output assembly of requested
  *   @param output_assembly_id requested output assembly of requested
- *connection
+ *  connection
  *   @return pointer to connected Object
  *   @return pointer to connected Object
  *           0 .. connection not present in device
  *           0 .. connection not present in device
  */
  */
 ConnectionObject *GetConnectedOutputAssembly(EipUint32 output_assembly_id);
 ConnectionObject *GetConnectedOutputAssembly(EipUint32 output_assembly_id);
 
 
-/** Copy the given connection data from pa_pstSrc to pa_pstDst
+/** @brief Copy the given connection data from source to destination
+ *
+ * @param destination Destination of the copy operation
+ * @param osurce Source of the copy operation
  */
  */
-void CopyConnectionData(ConnectionObject *destination, ConnectionObject *source);
+void CopyConnectionData(ConnectionObject *restrict destination, const ConnectionObject *restrict const source);
 
 
 /** @brief Close the given connection
 /** @brief Close the given connection
  *
  *
@@ -257,16 +263,16 @@ void CopyConnectionData(ConnectionObject *destination, ConnectionObject *source)
  * @param connection_object pointer to the connection object structure to be
  * @param connection_object pointer to the connection object structure to be
  *closed
  *closed
  */
  */
-void CloseConnection(ConnectionObject *connection_object);
+void CloseConnection(ConnectionObject *restrict connection_object);
 
 
 /* TODO: Missing documentation */
 /* TODO: Missing documentation */
-EipBool8 IsConnectedOutputAssembly(EipUint32 instance_number);
+EipBool8 IsConnectedOutputAssembly(const EipUint32 instance_number);
 
 
 /** @brief Generate the ConnectionIDs and set the general configuration
 /** @brief Generate the ConnectionIDs and set the general configuration
  * parameter in the given connection object.
  * parameter in the given connection object.
  *
  *
  * @param connection_object pointer to the connection object that should be set
  * @param connection_object pointer to the connection object that should be set
- *up.
+ * up.
  */
  */
 void GeneralConnectionConfiguration(ConnectionObject *connection_object);
 void GeneralConnectionConfiguration(ConnectionObject *connection_object);
 
 
@@ -281,7 +287,10 @@ void GeneralConnectionConfiguration(ConnectionObject *connection_object);
  */
  */
 void AddNewActiveConnection(ConnectionObject *connection_object);
 void AddNewActiveConnection(ConnectionObject *connection_object);
 
 
-/* TODO: Missing documentation */
+/** @brief Removes connection from the list of active connections
+ *
+ * @param connection_object Connection object to be removed from the active connection list
+ */
 void RemoveFromActiveConnections(ConnectionObject *connection_object);
 void RemoveFromActiveConnections(ConnectionObject *connection_object);
 
 
 #endif /* OPENER_CIPCONNECTIONMANAGER_H_ */
 #endif /* OPENER_CIPCONNECTIONMANAGER_H_ */

+ 19 - 15
source/src/cip/cipethernetlink.c

@@ -13,39 +13,43 @@
 #include "endianconv.h"
 #include "endianconv.h"
 #include "opener_api.h"
 #include "opener_api.h"
 
 
+/** @brief Data of an CIP Ethernet Link object */
 typedef struct {
 typedef struct {
-  EipUint32 interface_speed;
-  EipUint32 interface_flags;
-  EipUint8 physical_address[6];
+  EipUint32 interface_speed; /**< 10/100/1000 Mbit/sec */
+  EipUint32 interface_flags; /**< Inferface flags as defined in the CIP specification */
+  EipUint8 physical_address[6]; /**< MAC address of the Ethernet link */
 } CipEthernetLinkObject;
 } CipEthernetLinkObject;
 
 
 /* global private variables */
 /* global private variables */
 CipEthernetLinkObject g_ethernet_link;
 CipEthernetLinkObject g_ethernet_link;
 
 
-void ConfigureMacAddress(const EipUint8 *mac_address) {
+/** @bried Configures the MAC address of the Ethernet Link object*
+ *
+ *  @param mac_address The MAC address of the Ethernet Link
+ */
+void ConfigureMacAddress(const EipUint8 *const mac_address) {
   memcpy(&g_ethernet_link.physical_address, mac_address,
   memcpy(&g_ethernet_link.physical_address, mac_address,
          sizeof(g_ethernet_link.physical_address));
          sizeof(g_ethernet_link.physical_address));
 
 
 }
 }
 
 
 EipStatus CipEthernetLinkInit() {
 EipStatus CipEthernetLinkInit() {
-  CipClass *ethernet_link_class;
-  CipInstance *ethernet_link_instance;
+  CipClass *ethernet_link_class = CreateCipClass(CIP_ETHERNETLINK_CLASS_CODE, 0, /* # class attributes*/
+                                                 0xffffffff, /* class getAttributeAll mask*/
+                                                 0, /* # class services*/
+                                                 3, /* # instance attributes*/
+                                                 0xffffffff, /* instance getAttributeAll mask*/
+                                                 0, /* # instance services*/
+                                                 1, /* # instances*/
+                                                 "Ethernet Link", 1);
 
 
   /* set attributes to initial values */
   /* set attributes to initial values */
   g_ethernet_link.interface_speed = 100;
   g_ethernet_link.interface_speed = 100;
   g_ethernet_link.interface_flags = 0xF; /* successful speed and duplex neg, full duplex active link, TODO in future it should be checked if link is active */
   g_ethernet_link.interface_flags = 0xF; /* successful speed and duplex neg, full duplex active link, TODO in future it should be checked if link is active */
 
 
-  if ((ethernet_link_class = CreateCipClass(CIP_ETHERNETLINK_CLASS_CODE, 0, /* # class attributes*/
-                                            0xffffffff, /* class getAttributeAll mask*/
-                                            0, /* # class services*/
-                                            3, /* # instance attributes*/
-                                            0xffffffff, /* instance getAttributeAll mask*/
-                                            0, /* # instance services*/
-                                            1, /* # instances*/
-                                            "Ethernet Link", 1)) != 0) {
+  if (ethernet_link_class != NULL) {
 
 
-    ethernet_link_instance = GetCipInstance(ethernet_link_class, 1);
+    CipInstance *ethernet_link_instance = GetCipInstance(ethernet_link_class, 1);
     InsertAttribute(ethernet_link_instance, 1, kCipUdint,
     InsertAttribute(ethernet_link_instance, 1, kCipUdint,
                     &g_ethernet_link.interface_speed, kGetableSingleAndAll); /* bind attributes to the instance*/
                     &g_ethernet_link.interface_speed, kGetableSingleAndAll); /* bind attributes to the instance*/
     InsertAttribute(ethernet_link_instance, 2, kCipDword,
     InsertAttribute(ethernet_link_instance, 2, kCipDword,

+ 2 - 0
source/src/cip/cipethernetlink.h

@@ -13,6 +13,8 @@
 
 
 /* public functions */
 /* public functions */
 /** @brief Initialize the Ethernet Link Objects data
 /** @brief Initialize the Ethernet Link Objects data
+ *
+ *  @return kEipStatusOk if initialization was successful, otherwise kEipStatusError
  */
  */
 EipStatus CipEthernetLinkInit(void);
 EipStatus CipEthernetLinkInit(void);
 
 

+ 11 - 16
source/src/cip/cipidentity.c

@@ -25,8 +25,10 @@
  */
  */
 
 
 #include <string.h>
 #include <string.h>
-#include "opener_user_conf.h"
+
 #include "cipidentity.h"
 #include "cipidentity.h"
+
+#include "opener_user_conf.h"
 #include "cipcommon.h"
 #include "cipcommon.h"
 #include "cipmessagerouter.h"
 #include "cipmessagerouter.h"
 #include "ciperror.h"
 #include "ciperror.h"
@@ -48,18 +50,18 @@ CipShortString product_name_ = { sizeof(OPENER_DEVICE_NAME) - 1,
 /** Private functions, sets the devices serial number
 /** Private functions, sets the devices serial number
  * @param serial_number The serial number of the device
  * @param serial_number The serial number of the device
  */
  */
-void SetDeviceSerialNumber(EipUint32 serial_number) {
+void SetDeviceSerialNumber(const EipUint32 serial_number) {
   serial_number_ = serial_number;
   serial_number_ = serial_number;
 }
 }
 
 
-/** Private functions, sets the devices status
- * @param status The serial number of the deivce
+/** @brief Private function, sets the devices status
+ * @param status The serial number of the device
  */
  */
-void SetDeviceStatus(EipUint16 status) {
+void SetDeviceStatus(const EipUint16 status) {
   status_ = status;
   status_ = status;
 }
 }
 
 
-/** Reset service
+/** @brief Reset service
  *
  *
  * @param instance
  * @param instance
  * @param message_router_request
  * @param message_router_request
@@ -70,10 +72,9 @@ static EipStatus Reset(CipInstance *instance, /* pointer to instance*/
                        CipMessageRouterRequest *message_router_request, /* pointer to message router request*/
                        CipMessageRouterRequest *message_router_request, /* pointer to message router request*/
                        CipMessageRouterResponse *message_router_response) /* pointer to message router response*/
                        CipMessageRouterResponse *message_router_response) /* pointer to message router response*/
 {
 {
-  EipStatus eip_status;
   (void) instance;
   (void) instance;
 
 
-  eip_status = kEipStatusOkSend;
+  EipStatus eip_status = kEipStatusOkSend;
 
 
   message_router_response->reply_service = (0x80
   message_router_response->reply_service = (0x80
       | message_router_request->service);
       | message_router_request->service);
@@ -115,15 +116,9 @@ static EipStatus Reset(CipInstance *instance, /* pointer to instance*/
   return eip_status;
   return eip_status;
 }
 }
 
 
-/** @brief CIP Identity object constructor
- *
- * @returns EIP_ERROR if the class could not be created, otherwise EIP_OK
- */
 EipStatus CipIdentityInit() {
 EipStatus CipIdentityInit() {
-  CipClass *class;
-  CipInstance *instance;
 
 
-  class = CreateCipClass(kIdentityClassCode, 0, /* # of non-default class attributes */
+  CipClass *class = CreateCipClass(kIdentityClassCode, 0, /* # of non-default class attributes */
                          MASK4(1, 2, 6, 7), /* class getAttributeAll mask		CIP spec 5-2.3.2 */
                          MASK4(1, 2, 6, 7), /* class getAttributeAll mask		CIP spec 5-2.3.2 */
                          0, /* # of class services*/
                          0, /* # of class services*/
                          7, /* # of instance attributes*/
                          7, /* # of instance attributes*/
@@ -136,7 +131,7 @@ EipStatus CipIdentityInit() {
   if (class == 0)
   if (class == 0)
     return kEipStatusError;
     return kEipStatusError;
 
 
-  instance = GetCipInstance(class, 1);
+  CipInstance *instance = GetCipInstance(class, 1);
 
 
   InsertAttribute(instance, 1, kCipUint, &vendor_id_, kGetableSingleAndAll);
   InsertAttribute(instance, 1, kCipUint, &vendor_id_, kGetableSingleAndAll);
   InsertAttribute(instance, 2, kCipUint, &device_type_, kGetableSingleAndAll);
   InsertAttribute(instance, 2, kCipUint, &device_type_, kGetableSingleAndAll);

+ 1 - 1
source/src/cip/cipidentity.h

@@ -46,7 +46,7 @@ typedef enum {
 /* public functions */
 /* public functions */
 /** @brief CIP Identity object constructor
 /** @brief CIP Identity object constructor
  *
  *
- * @returns EipError if the class could not be created, otherwise EipOk
+ * @returns kEipStatusError if the class could not be created, otherwise kEipStatusOk
  */
  */
 EipStatus CipIdentityInit(void);
 EipStatus CipIdentityInit(void);
 
 

+ 42 - 49
source/src/cip/cipioconnection.c

@@ -18,6 +18,15 @@
 #include "trace.h"
 #include "trace.h"
 #include "endianconv.h"
 #include "endianconv.h"
 
 
+/** @brief Gives the cardinality of a connection endpoint,
+ *  either point to point or point to multipoint
+ *
+ */
+typedef enum {
+  PointToMultipoint = 1, /**< Connection is a point to multi-point connection */
+  PointToPoint = 2 /**< Connection is a point to point connection */
+} CommunicationEndpointCardinality;
+
 /*The port to be used per default for I/O messages on UDP.*/
 /*The port to be used per default for I/O messages on UDP.*/
 const int kOpenerEipIoUdpPort = 0x08AE;
 const int kOpenerEipIoUdpPort = 0x08AE;
 
 
@@ -59,7 +68,7 @@ void HandleIoConnectionTimeOut(ConnectionObject *connection_object);
 EipStatus SendConnectedData(ConnectionObject *connection_object);
 EipStatus SendConnectedData(ConnectionObject *connection_object);
 
 
 EipStatus HandleReceivedIoConnectionData(ConnectionObject *connection_object,
 EipStatus HandleReceivedIoConnectionData(ConnectionObject *connection_object,
-                                         EipUint8 *data, EipUint16 data_length);
+                                         const EipUint8 *data, EipUint16 data_length);
 
 
 /**** Global variables ****/
 /**** Global variables ****/
 EipUint8 *g_config_data_buffer = NULL; /**< buffers for the config data coming with a forward open request. */
 EipUint8 *g_config_data_buffer = NULL; /**< buffers for the config data coming with a forward open request. */
@@ -68,8 +77,8 @@ unsigned int g_config_data_length = 0;
 EipUint32 g_run_idle_state; /**< buffer for holding the run idle information. */
 EipUint32 g_run_idle_state; /**< buffer for holding the run idle information. */
 
 
 /**** Implementation ****/
 /**** Implementation ****/
-EipStatus EstablishIoConnction(ConnectionObject *connection_object,
-                         EipUint16 *extended_error) {
+EipStatus EstablishIoConnction(ConnectionObject *restrict const connection_object,
+                         EipUint16 *const extended_error) {
   int originator_to_target_connection_type,
   int originator_to_target_connection_type,
       target_to_originator_connection_type;
       target_to_originator_connection_type;
   EipStatus eip_status = kEipStatusOk;
   EipStatus eip_status = kEipStatusOk;
@@ -127,7 +136,7 @@ EipStatus EstablishIoConnction(ConnectionObject *connection_object,
     int producing_index = 0;
     int producing_index = 0;
     int data_size;
     int data_size;
     int diff_size;
     int diff_size;
-    int is_heartbeat;
+    int is_heartbeat = false;
 
 
     if ((originator_to_target_connection_type != 0)
     if ((originator_to_target_connection_type != 0)
         && (target_to_originator_connection_type != 0)) { /* we have a producing and consuming connection*/
         && (target_to_originator_connection_type != 0)) { /* we have a producing and consuming connection*/
@@ -256,20 +265,17 @@ EipStatus EstablishIoConnction(ConnectionObject *connection_object,
   return eip_status;
   return eip_status;
 }
 }
 
 
-/*   @brief Open a Point2Point connection dependent on pa_direction.
- *   @param connection_object Pointer to registered Object in ConnectionManager.
- *   @param common_packet_format_data Index of the connection object
- *   @return status
- *               0 .. success
- *              -1 .. error
+/** @brief Open a Point2Point connection dependent on pa_direction.
+ *
+ * @param connection_object Pointer to registered Object in ConnectionManager.
+ * @param common_packet_format_data Index of the connection object
+ * @return kEipStatusOk on success, otherwise kEipStatusError
  */
  */
 EipStatus OpenConsumingPointToPointConnection(
 EipStatus OpenConsumingPointToPointConnection(
     ConnectionObject *connection_object,
     ConnectionObject *connection_object,
     CipCommonPacketFormatData *common_packet_format_data) {
     CipCommonPacketFormatData *common_packet_format_data) {
   /*static EIP_UINT16 nUDPPort = 2222; TODO think on improving the udp port assigment for point to point connections */
   /*static EIP_UINT16 nUDPPort = 2222; TODO think on improving the udp port assigment for point to point connections */
   int j = 0;
   int j = 0;
-  struct sockaddr_in addr;
-  int socket;
 
 
   if (common_packet_format_data->address_info_item[0].type_id == 0) { /* it is not used yet */
   if (common_packet_format_data->address_info_item[0].type_id == 0) { /* it is not used yet */
     j = 0;
     j = 0;
@@ -277,12 +283,9 @@ EipStatus OpenConsumingPointToPointConnection(
     j = 1;
     j = 1;
   }
   }
 
 
-  addr.sin_family = AF_INET;
-  addr.sin_addr.s_addr = INADDR_ANY;
-  /*addr.in_port = htons(nUDPPort++);*/
-  addr.sin_port = htons(kOpenerEipIoUdpPort);
+  struct sockaddr_in addr = { .sin_family = PF_INET, .sin_addr.s_addr = INADDR_ANY, .sin_port = htons(kOpenerEipIoUdpPort) };
 
 
-  socket = CreateUdpSocket(kUdpCommuncationDirectionConsuming, &addr); /* the address is only needed for bind used if consuming */
+  int socket = CreateUdpSocket(kUdpCommuncationDirectionConsuming, &addr); /* the address is only needed for bind used if consuming */
   if (socket == kEipInvalidSocket) {
   if (socket == kEipInvalidSocket) {
     OPENER_TRACE_ERR(
     OPENER_TRACE_ERR(
         "cannot create UDP socket in OpenPointToPointConnection\n");
         "cannot create UDP socket in OpenPointToPointConnection\n");
@@ -310,7 +313,6 @@ EipStatus OpenConsumingPointToPointConnection(
 EipStatus OpenProducingPointToPointConnection(
 EipStatus OpenProducingPointToPointConnection(
     ConnectionObject *connection_object,
     ConnectionObject *connection_object,
     CipCommonPacketFormatData *common_packet_format_data) {
     CipCommonPacketFormatData *common_packet_format_data) {
-  int socket;
   in_port_t port = htons(kOpenerEipIoUdpPort); /* the default port to be used if no port information is part of the forward open request */
   in_port_t port = htons(kOpenerEipIoUdpPort); /* the default port to be used if no port information is part of the forward open request */
 
 
   if (kCipItemIdSocketAddressInfoTargetToOriginator
   if (kCipItemIdSocketAddressInfoTargetToOriginator
@@ -327,7 +329,7 @@ EipStatus OpenProducingPointToPointConnection(
   connection_object->remote_address.sin_addr.s_addr = 0; /* we don't know the address of the originate will be set in the IApp_CreateUDPSocket */
   connection_object->remote_address.sin_addr.s_addr = 0; /* we don't know the address of the originate will be set in the IApp_CreateUDPSocket */
   connection_object->remote_address.sin_port = port;
   connection_object->remote_address.sin_port = port;
 
 
-  socket = CreateUdpSocket(kUdpCommuncationDirectionProducing,
+  int socket = CreateUdpSocket(kUdpCommuncationDirectionProducing,
                            &connection_object->remote_address); /* the address is only needed for bind used if consuming */
                            &connection_object->remote_address); /* the address is only needed for bind used if consuming */
   if (socket == kEipInvalidSocket) {
   if (socket == kEipInvalidSocket) {
     OPENER_TRACE_ERR(
     OPENER_TRACE_ERR(
@@ -346,7 +348,6 @@ EipStatus OpenProducingMulticastConnection(
   ConnectionObject *existing_connection_object =
   ConnectionObject *existing_connection_object =
       GetExistingProducerMulticastConnection(
       GetExistingProducerMulticastConnection(
           connection_object->connection_path.connection_point[1]);
           connection_object->connection_path.connection_point[1]);
-  int j;
 
 
   if (NULL == existing_connection_object) { /* we are the first connection producing for the given Input Assembly */
   if (NULL == existing_connection_object) { /* we are the first connection producing for the given Input Assembly */
     return OpenMulticastConnection(kUdpCommuncationDirectionProducing,
     return OpenMulticastConnection(kUdpCommuncationDirectionProducing,
@@ -359,7 +360,7 @@ EipStatus OpenProducingMulticastConnection(
 
 
   /* we have a connection reuse the data and the socket */
   /* we have a connection reuse the data and the socket */
 
 
-  j = 0; /* allocate an unused sockaddr struct to use */
+  int j = 0; /* allocate an unused sockaddr struct to use */
   if (g_common_packet_format_data_item.address_info_item[0].type_id == 0) { /* it is not used yet */
   if (g_common_packet_format_data_item.address_info_item[0].type_id == 0) { /* it is not used yet */
     j = 0;
     j = 0;
   } else if (g_common_packet_format_data_item.address_info_item[1].type_id
   } else if (g_common_packet_format_data_item.address_info_item[1].type_id
@@ -395,21 +396,17 @@ EipStatus OpenProducingMulticastConnection(
   return kEipStatusOk;
   return kEipStatusOk;
 }
 }
 
 
-/**  @brief Open a Multicast connection dependent on @var direction.
+/** @brief Open a Multicast connection dependent on @var direction.
  *
  *
- *   @param direction Flag to indicate if consuming or producing.
- *   @param connection_object  pointer to registered Object in ConnectionManager.
- *   @param common_packet_format_data     received CPF Data Item.
- *   @return status
- *               0 .. success
- *              -1 .. error
+ * @param direction Flag to indicate if consuming or producing.
+ * @param connection_object  pointer to registered Object in ConnectionManager.
+ * @param common_packet_format_data     received CPF Data Item.
+ * @return kEipStatusOk on success, otherwise kEipStatusError
  */
  */
 EipStatus OpenMulticastConnection(
 EipStatus OpenMulticastConnection(
     UdpCommuncationDirection direction, ConnectionObject *connection_object,
     UdpCommuncationDirection direction, ConnectionObject *connection_object,
     CipCommonPacketFormatData *common_packet_format_data) {
     CipCommonPacketFormatData *common_packet_format_data) {
   int j = 0;
   int j = 0;
-  int socket;
-
 
 
   if (0 != g_common_packet_format_data_item.address_info_item[0].type_id) {
   if (0 != g_common_packet_format_data_item.address_info_item[0].type_id) {
     if ((kUdpCommuncationDirectionConsuming == direction)
     if ((kUdpCommuncationDirectionConsuming == direction)
@@ -457,7 +454,7 @@ EipStatus OpenMulticastConnection(
   socket_address.sin_port = common_packet_format_data->address_info_item[j]
   socket_address.sin_port = common_packet_format_data->address_info_item[j]
       .sin_port;
       .sin_port;
 
 
-  socket = CreateUdpSocket(direction, &socket_address); /* the address is only needed for bind used if consuming */
+  int socket = CreateUdpSocket(direction, &socket_address); /* the address is only needed for bind used if consuming */
   if (socket == kEipInvalidSocket) {
   if (socket == kEipInvalidSocket) {
     OPENER_TRACE_ERR("cannot create UDP socket in OpenMulticastConnection\n");
     OPENER_TRACE_ERR("cannot create UDP socket in OpenMulticastConnection\n");
     return kEipStatusError;
     return kEipStatusError;
@@ -487,14 +484,14 @@ EipUint16 HandleConfigData(CipClass *assembly_class,
     if (ConnectionWithSameConfigPointExists(
     if (ConnectionWithSameConfigPointExists(
         connection_object->connection_path.connection_point[2])) { /* there is a connected connection with the same config point
         connection_object->connection_path.connection_point[2])) { /* there is a connected connection with the same config point
          * we have to have the same data as already present in the config point*/
          * we have to have the same data as already present in the config point*/
-      CipByteArray *p = (CipByteArray *) GetCipAttribute(config_instance, 3)
+      CipByteArray *attribute_three = (CipByteArray *) GetCipAttribute(config_instance, 3)
           ->data;
           ->data;
-      if (p->length != g_config_data_length) {
+      if (attribute_three->length != g_config_data_length) {
         connection_manager_status =
         connection_manager_status =
             kConnectionManagerStatusCodeErrorOwnershipConflict;
             kConnectionManagerStatusCodeErrorOwnershipConflict;
       } else {
       } else {
         /*FIXME check if this is correct */
         /*FIXME check if this is correct */
-        if (memcmp(p->data, g_config_data_buffer, g_config_data_length)) {
+        if (memcmp(attribute_three->data, g_config_data_buffer, g_config_data_length)) {
           connection_manager_status =
           connection_manager_status =
               kConnectionManagerStatusCodeErrorOwnershipConflict;
               kConnectionManagerStatusCodeErrorOwnershipConflict;
         }
         }
@@ -604,13 +601,10 @@ void HandleIoConnectionTimeOut(ConnectionObject *connection_object) {
 }
 }
 
 
 EipStatus SendConnectedData(ConnectionObject *connection_object) {
 EipStatus SendConnectedData(ConnectionObject *connection_object) {
-  CipCommonPacketFormatData *common_packet_format_data;
-  EipUint16 reply_length;
-  EipUint8 *message_data_reply_buffer;
 
 
   /* TODO think of adding an own send buffer to each connection object in order to preset up the whole message on connection opening and just change the variable data items e.g., sequence number */
   /* TODO think of adding an own send buffer to each connection object in order to preset up the whole message on connection opening and just change the variable data items e.g., sequence number */
 
 
-  common_packet_format_data = &g_common_packet_format_data_item; /* TODO think on adding a CPF data item to the S_CIP_ConnectionObject in order to remove the code here or even better allocate memory in the connection object for storing the message to send and just change the application data*/
+  CipCommonPacketFormatData *common_packet_format_data = &g_common_packet_format_data_item; /* TODO think on adding a CPF data item to the S_CIP_ConnectionObject in order to remove the code here or even better allocate memory in the connection object for storing the message to send and just change the application data*/
 
 
   connection_object->eip_level_sequence_count_producing++;
   connection_object->eip_level_sequence_count_producing++;
 
 
@@ -645,10 +639,10 @@ EipStatus SendConnectedData(ConnectionObject *connection_object) {
   common_packet_format_data->address_info_item[0].type_id = 0;
   common_packet_format_data->address_info_item[0].type_id = 0;
   common_packet_format_data->address_info_item[1].type_id = 0;
   common_packet_format_data->address_info_item[1].type_id = 0;
 
 
-  reply_length = AssembleIOMessage(common_packet_format_data,
+  EipUint16 reply_length = AssembleIOMessage(common_packet_format_data,
                                    &g_message_data_reply_buffer[0]);
                                    &g_message_data_reply_buffer[0]);
 
 
-  message_data_reply_buffer = &g_message_data_reply_buffer[reply_length - 2];
+  EipUint8 *message_data_reply_buffer = &g_message_data_reply_buffer[reply_length - 2];
   common_packet_format_data->data_item.length = producing_instance_attributes
   common_packet_format_data->data_item.length = producing_instance_attributes
       ->length;
       ->length;
   if (kOpenerProducedDataHasRunIdleHeader) {
   if (kOpenerProducedDataHasRunIdleHeader) {
@@ -682,7 +676,7 @@ EipStatus SendConnectedData(ConnectionObject *connection_object) {
 }
 }
 
 
 EipStatus HandleReceivedIoConnectionData(ConnectionObject *connection_object,
 EipStatus HandleReceivedIoConnectionData(ConnectionObject *connection_object,
-                                         EipUint8 *data, EipUint16 data_length) {
+                                         const EipUint8 *data, EipUint16 data_length) {
 
 
   /* check class 1 sequence number*/
   /* check class 1 sequence number*/
   if ((connection_object->transport_type_class_trigger & 0x0F) == 1) {
   if ((connection_object->transport_type_class_trigger & 0x0F) == 1) {
@@ -707,7 +701,7 @@ EipStatus HandleReceivedIoConnectionData(ConnectionObject *connection_object,
     }
     }
 
 
     if (NotifyAssemblyConnectedDataReceived(
     if (NotifyAssemblyConnectedDataReceived(
-        connection_object->consuming_instance, data, data_length) != 0) {
+        connection_object->consuming_instance, (EipUint8 *const)data, data_length) != 0) {
       return kEipStatusError;
       return kEipStatusError;
     }
     }
   }
   }
@@ -721,14 +715,14 @@ EipStatus OpenCommunicationChannels(ConnectionObject *connection_object) {
   CipCommonPacketFormatData *common_packet_format_data =
   CipCommonPacketFormatData *common_packet_format_data =
       &g_common_packet_format_data_item;
       &g_common_packet_format_data_item;
 
 
-  int originator_to_target_connection_type = (connection_object
+  CommunicationEndpointCardinality originator_to_target_connection_type = (connection_object
       ->o_to_t_network_connection_parameter & 0x6000) >> 13;
       ->o_to_t_network_connection_parameter & 0x6000) >> 13;
 
 
-  int target_to_originator_connection_type = (connection_object
+  CommunicationEndpointCardinality target_to_originator_connection_type = (connection_object
       ->t_to_o_network_connection_parameter & 0x6000) >> 13;
       ->t_to_o_network_connection_parameter & 0x6000) >> 13;
 
 
   /* open a connection "point to point" or "multicast" based on the ConnectionParameter */
   /* open a connection "point to point" or "multicast" based on the ConnectionParameter */
-  if (originator_to_target_connection_type == 1) /*TODO: Fix magic number; Multicast consuming */
+  if (originator_to_target_connection_type == PointToMultipoint) /* Multicast consuming */
   {
   {
     if (OpenMulticastConnection(kUdpCommuncationDirectionConsuming,
     if (OpenMulticastConnection(kUdpCommuncationDirectionConsuming,
                                 connection_object, common_packet_format_data)
                                 connection_object, common_packet_format_data)
@@ -736,7 +730,7 @@ EipStatus OpenCommunicationChannels(ConnectionObject *connection_object) {
       OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
       OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
       return kCipErrorConnectionFailure;
       return kCipErrorConnectionFailure;
     }
     }
-  } else if (originator_to_target_connection_type == 2) /* TODO: Fix magic number; Point to Point consuming */
+  } else if (originator_to_target_connection_type == PointToPoint) /* Point to Point consuming */
   {
   {
     if (OpenConsumingPointToPointConnection(connection_object,
     if (OpenConsumingPointToPointConnection(connection_object,
                                             common_packet_format_data)
                                             common_packet_format_data)
@@ -746,7 +740,7 @@ EipStatus OpenCommunicationChannels(ConnectionObject *connection_object) {
     }
     }
   }
   }
 
 
-  if (target_to_originator_connection_type == 1) /* TODO: Fix magic number; Multicast producing */
+  if (target_to_originator_connection_type == PointToMultipoint) /* Multicast producing */
   {
   {
     if (OpenProducingMulticastConnection(connection_object,
     if (OpenProducingMulticastConnection(connection_object,
                                          common_packet_format_data)
                                          common_packet_format_data)
@@ -754,7 +748,7 @@ EipStatus OpenCommunicationChannels(ConnectionObject *connection_object) {
       OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
       OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
       return kCipErrorConnectionFailure;
       return kCipErrorConnectionFailure;
     }
     }
-  } else if (target_to_originator_connection_type == 2) /* TODO: Fix magic number; Point to Point producing */
+  } else if (target_to_originator_connection_type == PointToPoint) /* Point to Point producing */
   {
   {
 
 
     if (OpenProducingPointToPointConnection(connection_object,
     if (OpenProducingPointToPointConnection(connection_object,
@@ -764,7 +758,6 @@ EipStatus OpenCommunicationChannels(ConnectionObject *connection_object) {
       return kCipErrorConnectionFailure;
       return kCipErrorConnectionFailure;
     }
     }
   }
   }
-
   return eip_status;
   return eip_status;
 }
 }
 
 

+ 2 - 2
source/src/cip/cipioconnection.h

@@ -52,8 +52,8 @@
  *    - EIP_OK ... on success
  *    - EIP_OK ... on success
  *    - On an error the general status code to be put into the response
  *    - On an error the general status code to be put into the response
  */
  */
-EipStatus EstablishIoConnction(ConnectionObject *connection_object,
-                         EipUint16 *extended_error);
+EipStatus EstablishIoConnction(ConnectionObject *restrict const connection_object,
+                         EipUint16 *const extended_error);
 
 
 /** @brief Take the data given in the connection object structure and open the necessary communication channels
 /** @brief Take the data given in the connection object structure and open the necessary communication channels
  *
  *

+ 32 - 36
source/src/cip/cipmessagerouter.c

@@ -26,7 +26,7 @@ typedef struct cip_message_router_object {
 } CipMessageRouterObject;
 } CipMessageRouterObject;
 
 
 /** @brief Pointer to first registered object in MessageRouter*/
 /** @brief Pointer to first registered object in MessageRouter*/
-CipMessageRouterObject *g_first_object = 0;
+CipMessageRouterObject *g_first_object = NULL;
 
 
 /** @brief Register an Class to the message router
 /** @brief Register an Class to the message router
  *  @param cip_class Pointer to a class object to be registered.
  *  @param cip_class Pointer to a class object to be registered.
@@ -41,17 +41,15 @@ EipStatus RegisterCipClass(CipClass *cip_class);
  * @param data pointer to the message data received
  * @param data pointer to the message data received
  * @param data_length number of bytes in the message
  * @param data_length number of bytes in the message
  * @param message_router_request pointer to structure of MRRequest data item.
  * @param message_router_request pointer to structure of MRRequest data item.
- * @return status  0 .. success
- *                 -1 .. error
+ * @return kEipStatusOk on success. otherwise kEipStatusError
  */
  */
 CipError CreateMessageRouterRequestStructure(
 CipError CreateMessageRouterRequestStructure(
-    EipUint8 *data, EipInt16 data_length,
+    const EipUint8 *data, EipInt16 data_length,
     CipMessageRouterRequest *message_router_request);
     CipMessageRouterRequest *message_router_request);
 
 
 EipStatus CipMessageRouterInit() {
 EipStatus CipMessageRouterInit() {
-  CipClass *message_router;
 
 
-  message_router = CreateCipClass(kCipMessageRouterClassCode, /* class ID*/
+  CipClass *message_router = CreateCipClass(kCipMessageRouterClassCode, /* class ID*/
                                   0, /* # of class attributes */
                                   0, /* # of class attributes */
                                   0xffffffff, /* class getAttributeAll mask*/
                                   0xffffffff, /* class getAttributeAll mask*/
                                   0, /* # of class services*/
                                   0, /* # of class services*/
@@ -61,7 +59,7 @@ EipStatus CipMessageRouterInit() {
                                   1, /* # of instances*/
                                   1, /* # of instances*/
                                   "message router", /* class name*/
                                   "message router", /* class name*/
                                   1); /* revision */
                                   1); /* revision */
-  if (message_router == 0)
+  if (message_router == NULL)
     return kEipStatusError;
     return kEipStatusError;
 
 
   /* reserved for future use -> set to zero */
   /* reserved for future use -> set to zero */
@@ -76,7 +74,7 @@ EipStatus CipMessageRouterInit() {
  *
  *
  *  @param class_id Class code to be searched for.
  *  @param class_id Class code to be searched for.
  *  @return Pointer to registered message router object
  *  @return Pointer to registered message router object
- *      0 .. Class not registered
+ *      NULL .. Class not registered
  */
  */
 CipMessageRouterObject *GetRegisteredObject(EipUint32 class_id) {
 CipMessageRouterObject *GetRegisteredObject(EipUint32 class_id) {
   CipMessageRouterObject *object = g_first_object; /* get pointer to head of class registration list */
   CipMessageRouterObject *object = g_first_object; /* get pointer to head of class registration list */
@@ -88,25 +86,25 @@ CipMessageRouterObject *GetRegisteredObject(EipUint32 class_id) {
       return object; /* return registration node if it matches class ID*/
       return object; /* return registration node if it matches class ID*/
     object = object->next;
     object = object->next;
   }
   }
-  return 0;
+  return NULL;
 }
 }
 
 
-CipClass *GetCipClass(EipUint32 class_id) {
-  CipMessageRouterObject *p = GetRegisteredObject(class_id);
+CipClass *GetCipClass(const EipUint32 class_id) {
+  CipMessageRouterObject *message_router_object = GetRegisteredObject(class_id);
 
 
-  if (p)
-    return p->cip_class;
+  if (message_router_object)
+    return message_router_object->cip_class;
   else
   else
     return NULL;
     return NULL;
 }
 }
 
 
-CipInstance *GetCipInstance(CipClass *cip_class, EipUint32 instance_number) {
-  CipInstance *instance; /* pointer to linked list of instances from the class object*/
+CipInstance *GetCipInstance(const CipClass *restrict const cip_class, EipUint32 instance_number) {
 
 
   if (instance_number == 0)
   if (instance_number == 0)
     return (CipInstance *) cip_class; /* if the instance number is zero, return the class object itself*/
     return (CipInstance *) cip_class; /* if the instance number is zero, return the class object itself*/
 
 
-  for (instance = cip_class->instances; instance; instance = instance->next) /* follow the list*/
+  /* pointer to linked list of instances from the class object*/
+  for (CipInstance *instance = cip_class->instances; instance; instance = instance->next) /* follow the list*/
   {
   {
     if (instance->instance_number == instance_number)
     if (instance->instance_number == instance_number)
       return instance; /* if the number matches, return the instance*/
       return instance; /* if the number matches, return the instance*/
@@ -132,18 +130,18 @@ EipStatus RegisterCipClass(CipClass *cip_class) {
   return kEipStatusOk;
   return kEipStatusOk;
 }
 }
 
 
-EipStatus NotifyMR(EipUint8 *data, int data_length) {
+EipStatus NotifyMessageRouter(EipUint8 *data, int data_length) {
   EipStatus eip_status = kEipStatusOkSend;
   EipStatus eip_status = kEipStatusOkSend;
-  EipByte nStatus;
+  EipByte status = kCipErrorSuccess;
 
 
   g_message_router_response.data = g_message_data_reply_buffer; /* set reply buffer, using a fixed buffer (about 100 bytes) */
   g_message_router_response.data = g_message_data_reply_buffer; /* set reply buffer, using a fixed buffer (about 100 bytes) */
 
 
-  OPENER_TRACE_INFO("notifyMR: routing unconnected message\n");
+  OPENER_TRACE_INFO("NotifyMessageRouter: routing unconnected message\n");
   if (kCipErrorSuccess
   if (kCipErrorSuccess
-      != (nStatus = CreateMessageRouterRequestStructure(
+      != (status = CreateMessageRouterRequestStructure(
           data, data_length, &g_message_router_request))) { /* error from create MR structure*/
           data, data_length, &g_message_router_request))) { /* error from create MR structure*/
-    OPENER_TRACE_ERR("notifyMR: error from createMRRequeststructure\n");
-    g_message_router_response.general_status = nStatus;
+    OPENER_TRACE_ERR("NotifyMessageRouter: error from createMRRequeststructure\n");
+    g_message_router_response.general_status = status;
     g_message_router_response.size_of_additional_status = 0;
     g_message_router_response.size_of_additional_status = 0;
     g_message_router_response.reserved = 0;
     g_message_router_response.reserved = 0;
     g_message_router_response.data_length = 0;
     g_message_router_response.data_length = 0;
@@ -151,13 +149,11 @@ EipStatus NotifyMR(EipUint8 *data, int data_length) {
         | g_message_router_request.service);
         | g_message_router_request.service);
   } else {
   } else {
     /* forward request to appropriate Object if it is registered*/
     /* forward request to appropriate Object if it is registered*/
-    CipMessageRouterObject *registered_object;
-
-    registered_object = GetRegisteredObject(
+    CipMessageRouterObject *registered_object = GetRegisteredObject(
         g_message_router_request.request_path.class_id);
         g_message_router_request.request_path.class_id);
     if (registered_object == 0) {
     if (registered_object == 0) {
       OPENER_TRACE_ERR(
       OPENER_TRACE_ERR(
-          "notifyMR: sending CIP_ERROR_OBJECT_DOES_NOT_EXIST reply, class id 0x%x is not registered\n",
+          "NotifyMessageRouter: sending CIP_ERROR_OBJECT_DOES_NOT_EXIST reply, class id 0x%x is not registered\n",
           (unsigned ) g_message_router_request.request_path.class_id);
           (unsigned ) g_message_router_request.request_path.class_id);
       g_message_router_response.general_status =
       g_message_router_response.general_status =
           kCipErrorPathDestinationUnknown; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
           kCipErrorPathDestinationUnknown; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
@@ -171,7 +167,7 @@ EipStatus NotifyMR(EipUint8 *data, int data_length) {
        object will or will not make an reply into gMRResponse*/
        object will or will not make an reply into gMRResponse*/
       g_message_router_response.reserved = 0;
       g_message_router_response.reserved = 0;
       OPENER_ASSERT(NULL != registered_object->cip_class);
       OPENER_ASSERT(NULL != registered_object->cip_class);
-      OPENER_TRACE_INFO("notifyMR: calling notify function of class '%s'\n",
+      OPENER_TRACE_INFO("NotifyMessageRouter: calling notify function of class '%s'\n",
                         registered_object->cip_class->class_name);
                         registered_object->cip_class->class_name);
       eip_status = NotifyClass(registered_object->cip_class,
       eip_status = NotifyClass(registered_object->cip_class,
                                &g_message_router_request,
                                &g_message_router_request,
@@ -198,15 +194,14 @@ EipStatus NotifyMR(EipUint8 *data, int data_length) {
 }
 }
 
 
 CipError CreateMessageRouterRequestStructure(
 CipError CreateMessageRouterRequestStructure(
-    EipUint8 *data, EipInt16 data_length,
+    const EipUint8 *data, EipInt16 data_length,
     CipMessageRouterRequest *message_router_request) {
     CipMessageRouterRequest *message_router_request) {
-  int number_of_decoded_bytes;
 
 
   message_router_request->service = *data;
   message_router_request->service = *data;
   data++;  /*TODO: Fix for 16 bit path lengths (+1 */
   data++;  /*TODO: Fix for 16 bit path lengths (+1 */
   data_length--;
   data_length--;
 
 
-  number_of_decoded_bytes = DecodePaddedEPath(
+  int number_of_decoded_bytes = DecodePaddedEPath(
       &(message_router_request->request_path), &data);
       &(message_router_request->request_path), &data);
   if (number_of_decoded_bytes < 0) {
   if (number_of_decoded_bytes < 0) {
     return kCipErrorPathSegmentError;
     return kCipErrorPathSegmentError;
@@ -223,8 +218,9 @@ CipError CreateMessageRouterRequestStructure(
 
 
 void DeleteAllClasses(void) {
 void DeleteAllClasses(void) {
   CipMessageRouterObject *message_router_object = g_first_object; /* get pointer to head of class registration list */
   CipMessageRouterObject *message_router_object = g_first_object; /* get pointer to head of class registration list */
-  CipMessageRouterObject *message_router_object_to_delete;
-  CipInstance *instance, *instance_to_delete;
+  CipMessageRouterObject *message_router_object_to_delete = NULL;
+  CipInstance *instance = NULL;
+  CipInstance *instance_to_delete = NULL;
 
 
   while (NULL != message_router_object) {
   while (NULL != message_router_object) {
     message_router_object_to_delete = message_router_object;
     message_router_object_to_delete = message_router_object;
@@ -243,14 +239,14 @@ void DeleteAllClasses(void) {
 
 
     /*clear meta class data*/
     /*clear meta class data*/
     CipFree(
     CipFree(
-        message_router_object_to_delete->cip_class->m_stSuper.cip_class
+        message_router_object_to_delete->cip_class->class_instance.cip_class
             ->class_name);
             ->class_name);
     CipFree(
     CipFree(
-        message_router_object_to_delete->cip_class->m_stSuper.cip_class
+        message_router_object_to_delete->cip_class->class_instance.cip_class
             ->services);
             ->services);
-    CipFree(message_router_object_to_delete->cip_class->m_stSuper.cip_class);
+    CipFree(message_router_object_to_delete->cip_class->class_instance.cip_class);
     /*clear class data*/
     /*clear class data*/
-    CipFree(message_router_object_to_delete->cip_class->m_stSuper.attributes);
+    CipFree(message_router_object_to_delete->cip_class->class_instance.attributes);
     CipFree(message_router_object_to_delete->cip_class->services);
     CipFree(message_router_object_to_delete->cip_class->services);
     CipFree(message_router_object_to_delete->cip_class);
     CipFree(message_router_object_to_delete->cip_class);
     CipFree(message_router_object_to_delete);
     CipFree(message_router_object_to_delete);

+ 1 - 1
source/src/cip/cipmessagerouter.h

@@ -38,7 +38,7 @@ void DeleteAllClasses(void);
  *  @return  EIP_ERROR on fault
  *  @return  EIP_ERROR on fault
  *           EIP_OK on success           
  *           EIP_OK on success           
  */
  */
-EipStatus NotifyMR(EipUint8 *data, int data_length);
+EipStatus NotifyMessageRouter(EipUint8 *data, int data_length);
 
 
 /*! Register a class at the message router.
 /*! Register a class at the message router.
  *  In order that the message router can deliver
  *  In order that the message router can deliver

+ 23 - 23
source/src/cip/ciptcpipinterface.c

@@ -19,10 +19,10 @@ CipDword tcp_status_ = 0x1; /**< #1  TCP status with 1 we indicate that we got a
 CipDword configuration_capability_ = 0x04 | 0x20; /**< #2  This is a default value meaning that it is a DHCP client see 5-3.2.2.2 EIP specification; 0x20 indicates "Hardware Configurable" */
 CipDword configuration_capability_ = 0x04 | 0x20; /**< #2  This is a default value meaning that it is a DHCP client see 5-3.2.2.2 EIP specification; 0x20 indicates "Hardware Configurable" */
 CipDword configuration_control_ = 0; /**< #3  This is a TCP/IP object attribute. For now it is always zero and is not used for anything. */
 CipDword configuration_control_ = 0; /**< #3  This is a TCP/IP object attribute. For now it is always zero and is not used for anything. */
 CipEpath physical_link_object_ = /**< #4 */
 CipEpath physical_link_object_ = /**< #4 */
-{ 2, /**< EIP_UINT16 (UINT) PathSize in 16 Bit chunks*/
-CIP_ETHERNETLINK_CLASS_CODE, /**< EIP_UINT16 ClassID*/
+{ 2, /**< EIP_UINT16 (UINT) PathSize in 16 Bit chunks */
+CIP_ETHERNETLINK_CLASS_CODE, /**< EIP_UINT16 ClassID */
 1, /**< EIP_UINT16 InstanceNr*/
 1, /**< EIP_UINT16 InstanceNr*/
-0 /**< EIP_UINT16 AttributNr (not used as this is the EPATH the EthernetLink object)*/
+0 /**< EIP_UINT16 AttributNr (not used as this is the EPATH the EthernetLink object) */
 };
 };
 
 
 CipTcpIpNetworkInterfaceConfiguration interface_configuration_ = /**< #5 IP, network mask, gateway, name server 1 & 2, domain name*/
 CipTcpIpNetworkInterfaceConfiguration interface_configuration_ = /**< #5 IP, network mask, gateway, name server 1 & 2, domain name*/
@@ -32,7 +32,7 @@ CipTcpIpNetworkInterfaceConfiguration interface_configuration_ = /**< #5 IP, net
 0, /* NameServer */
 0, /* NameServer */
 0, /* NameServer2 */
 0, /* NameServer2 */
 { /* DomainName */
 { /* DomainName */
-0, NULL, } };
+0, NULL } };
 
 
 CipString hostname_ = /**< #6 Hostname*/
 CipString hostname_ = /**< #6 Hostname*/
 { 0, NULL };
 { 0, NULL };
@@ -62,9 +62,9 @@ EipStatus GetAttributeAllTcpIpInterface(
     CipInstance *instance, CipMessageRouterRequest *message_router_request,
     CipInstance *instance, CipMessageRouterRequest *message_router_request,
     CipMessageRouterResponse *message_router_response);
     CipMessageRouterResponse *message_router_response);
 
 
-EipStatus ConfigureNetworkInterface(const char *ip_address,
-                                    const char *subnet_mask,
-                                    const char *gateway) {
+EipStatus ConfigureNetworkInterface(const char *const ip_address,
+                                    const char *const subnet_mask,
+                                    const char *const gateway) {
 
 
   interface_configuration_.ip_address = inet_addr(ip_address);
   interface_configuration_.ip_address = inet_addr(ip_address);
   interface_configuration_.network_mask = inet_addr(subnet_mask);
   interface_configuration_.network_mask = inet_addr(subnet_mask);
@@ -82,7 +82,7 @@ EipStatus ConfigureNetworkInterface(const char *ip_address,
   return kEipStatusOk;
   return kEipStatusOk;
 }
 }
 
 
-void ConfigureDomainName(const char *domain_name) {
+void ConfigureDomainName(const char *const restrict domain_name) {
   if (NULL != interface_configuration_.domain_name.string) {
   if (NULL != interface_configuration_.domain_name.string) {
     /* if the string is already set to a value we have to free the resources
     /* if the string is already set to a value we have to free the resources
      * before we can set the new value in order to avoid memory leaks.
      * before we can set the new value in order to avoid memory leaks.
@@ -93,13 +93,13 @@ void ConfigureDomainName(const char *domain_name) {
   if (interface_configuration_.domain_name.length) {
   if (interface_configuration_.domain_name.length) {
     interface_configuration_.domain_name.string = (EipByte *) CipCalloc(
     interface_configuration_.domain_name.string = (EipByte *) CipCalloc(
         interface_configuration_.domain_name.length + 1, sizeof(EipInt8));
         interface_configuration_.domain_name.length + 1, sizeof(EipInt8));
-    strcpy(interface_configuration_.domain_name.string, domain_name);
+    strcpy((char *)(interface_configuration_.domain_name.string), domain_name);
   } else {
   } else {
     interface_configuration_.domain_name.string = NULL;
     interface_configuration_.domain_name.string = NULL;
   }
   }
 }
 }
 
 
-void ConfigureHostName(const char *hostname) {
+void ConfigureHostName(const char *const restrict hostname) {
   if (NULL != hostname_.string) {
   if (NULL != hostname_.string) {
     /* if the string is already set to a value we have to free the resources
     /* if the string is already set to a value we have to free the resources
      * before we can set the new value in order to avoid memory leaks.
      * before we can set the new value in order to avoid memory leaks.
@@ -110,7 +110,7 @@ void ConfigureHostName(const char *hostname) {
   if (hostname_.length) {
   if (hostname_.length) {
     hostname_.string = (EipByte *) CipCalloc(hostname_.length + 1,
     hostname_.string = (EipByte *) CipCalloc(hostname_.length + 1,
                                              sizeof(EipByte));
                                              sizeof(EipByte));
-    strcpy(hostname_.string, hostname);
+    strcpy((char *)(hostname_.string), hostname);
   } else {
   } else {
     hostname_.string = NULL;
     hostname_.string = NULL;
   }
   }
@@ -141,16 +141,16 @@ EipStatus SetAttributeSingleTcp(
 }
 }
 
 
 EipStatus CipTcpIpInterfaceInit() {
 EipStatus CipTcpIpInterfaceInit() {
-  CipClass *tcp_ip_class = NULL;
-
-  if ((tcp_ip_class = CreateCipClass(kCipTcpIpInterfaceClassCode, 0, /* # class attributes*/
-                                     0xffffffff, /* class getAttributeAll mask*/
-                                     0, /* # class services*/
-                                     8, /* # instance attributes*/
-                                     0xffffffff, /* instance getAttributeAll mask*/
-                                     1, /* # instance services*/
-                                     1, /* # instances*/
-                                     "TCP/IP interface", 3)) == 0) {
+  CipClass *tcp_ip_class = CreateCipClass(kCipTcpIpInterfaceClassCode, 0, /* # class attributes*/
+                                          0xffffffff, /* class getAttributeAll mask*/
+                                          0, /* # class services*/
+                                          8, /* # instance attributes*/
+                                          0xffffffff, /* instance getAttributeAll mask*/
+                                          1, /* # instance services*/
+                                          1, /* # instances*/
+                                          "TCP/IP interface", 3);
+
+  if (NULL == tcp_ip_class) {
     return kEipStatusError;
     return kEipStatusError;
   }
   }
   CipInstance *instance = GetCipInstance(tcp_ip_class, 1); /* bind attributes to the instance #1 that was created above*/
   CipInstance *instance = GetCipInstance(tcp_ip_class, 1); /* bind attributes to the instance #1 that was created above*/
@@ -200,8 +200,8 @@ void ShutdownTcpIpInterface(void) {
 }
 }
 
 
 EipStatus GetAttributeSingleTcpIpInterface(
 EipStatus GetAttributeSingleTcpIpInterface(
-    CipInstance *instance, CipMessageRouterRequest *message_router_request,
-    CipMessageRouterResponse *message_router_response) {
+    CipInstance *const restrict instance, CipMessageRouterRequest *restrict const message_router_request,
+    CipMessageRouterResponse *restrict const message_router_response) {
 
 
   EipStatus status = kEipStatusOkSend;
   EipStatus status = kEipStatusOkSend;
   EipByte *message = message_router_response->data;
   EipByte *message = message_router_response->data;

+ 2 - 0
source/src/cip/ciptcpipinterface.h

@@ -35,6 +35,8 @@ extern MulticastAddressConfiguration g_multicast_configuration; /**< Multicast c
 
 
 /* public functions */
 /* public functions */
 /** @brief Initializing the data structures of the TCP/IP interface object
 /** @brief Initializing the data structures of the TCP/IP interface object
+ *
+ * @return kEipStatusOk on success, otherwise kEipStatusError
  */
  */
 EipStatus CipTcpIpInterfaceInit(void);
 EipStatus CipTcpIpInterfaceInit(void);
 
 

+ 6 - 6
source/src/cip/ciptypes.h

@@ -224,6 +224,7 @@ typedef struct {
   CipUsint minor_revision; /**< Minor Revision */
   CipUsint minor_revision; /**< Minor Revision */
 } CipKeyData;
 } CipKeyData;
 
 
+/** @brief Struct storing the CIP revision */
 typedef struct {
 typedef struct {
   EipUint8 major_revision;
   EipUint8 major_revision;
   EipUint8 minor_revision;
   EipUint8 minor_revision;
@@ -247,7 +248,7 @@ typedef struct {
   CipUsint service;
   CipUsint service;
   CipEpath request_path;
   CipEpath request_path;
   EipInt16 data_length;
   EipInt16 data_length;
-  CipOctet *data;
+  const CipOctet *data;
 } CipMessageRouterRequest;
 } CipMessageRouterRequest;
 
 
 #define MAX_SIZE_OF_ADD_STATUS 2 /* for now we support extended status codes up to 2 16bit values there is mostly only one 16bit value used */
 #define MAX_SIZE_OF_ADD_STATUS 2 /* for now we support extended status codes up to 2 16bit values there is mostly only one 16bit value used */
@@ -266,7 +267,7 @@ typedef struct {
   EipUint16 additional_status[MAX_SIZE_OF_ADD_STATUS]; /**< Array of 16 bit words; Additional status;
   EipUint16 additional_status[MAX_SIZE_OF_ADD_STATUS]; /**< Array of 16 bit words; Additional status;
    If SizeOfAdditionalStatus is 0. there is no
    If SizeOfAdditionalStatus is 0. there is no
    Additional Status */
    Additional Status */
-  EipInt16 data_length; /* TODO: Check if this is correct */
+  EipInt16 data_length; /**< Supportative non-CIP variable, gives length of data segment */
   CipOctet *data; /**< Array of octet; Response data per object definition from
   CipOctet *data; /**< Array of octet; Response data per object definition from
    request */
    request */
 } CipMessageRouterResponse;
 } CipMessageRouterResponse;
@@ -294,8 +295,7 @@ typedef struct cip_instance {
 
 
 /** @brief Class is a subclass of Instance */
 /** @brief Class is a subclass of Instance */
 typedef struct cip_class {
 typedef struct cip_class {
-  CipInstance m_stSuper;
-
+  CipInstance class_instance;
   /* the rest of these are specific to the Class class only. */
   /* the rest of these are specific to the Class class only. */
   EipUint32 class_id; /**< class ID */
   EipUint32 class_id; /**< class ID */
   EipUint16 revision; /**< class revision*/
   EipUint16 revision; /**< class revision*/
@@ -329,8 +329,8 @@ typedef struct cip_class {
  *should be sent
  *should be sent
  */
  */
 typedef EipStatus (*CipServiceFunction)(
 typedef EipStatus (*CipServiceFunction)(
-    CipInstance *instance, CipMessageRouterRequest *message_router_request,
-    CipMessageRouterResponse *message_router_response);
+    CipInstance *const instance, CipMessageRouterRequest *const message_router_request,
+    CipMessageRouterResponse *const message_router_response);
 
 
 /** @brief Service descriptor. These are stored in an array */
 /** @brief Service descriptor. These are stored in an array */
 typedef struct cip_service_struct {
 typedef struct cip_service_struct {

+ 149 - 27
source/src/enet_encap/cpf.c

@@ -15,9 +15,14 @@
 #include "cipconnectionmanager.h"
 #include "cipconnectionmanager.h"
 #include "trace.h"
 #include "trace.h"
 
 
+const size_t item_count_field_size = 2; /**< The size of the item count field in the message */
+const size_t item_data_type_id_field_length = 2; /**< The size of the item count field in the message */
+
+const size_t sequenced_address_item_length = 8;
+
 CipCommonPacketFormatData g_common_packet_format_data_item; /**< CPF global data items */
 CipCommonPacketFormatData g_common_packet_format_data_item; /**< CPF global data items */
 
 
-int NotifyCommonPacketFormat(EncapsulationData *receive_data,
+int NotifyCommonPacketFormat(EncapsulationData *const receive_data,
                              EipUint8 *reply_buffer) {
                              EipUint8 *reply_buffer) {
   int return_value = kEipStatusError;
   int return_value = kEipStatusError;
 
 
@@ -33,7 +38,7 @@ int NotifyCommonPacketFormat(EncapsulationData *receive_data,
         { /* found null address item*/
         { /* found null address item*/
       if (g_common_packet_format_data_item.data_item.type_id
       if (g_common_packet_format_data_item.data_item.type_id
           == kCipItemIdUnconnectedDataItem) { /* unconnected data item received*/
           == kCipItemIdUnconnectedDataItem) { /* unconnected data item received*/
-        return_value = NotifyMR(
+        return_value = NotifyMessageRouter(
             g_common_packet_format_data_item.data_item.data,
             g_common_packet_format_data_item.data_item.data,
             g_common_packet_format_data_item.data_item.length);
             g_common_packet_format_data_item.data_item.length);
         if (return_value != kEipStatusError) {
         if (return_value != kEipStatusError) {
@@ -82,11 +87,11 @@ int NotifyConnectedCommonPacketFormat(EncapsulationData *received_data,
         /*TODO check connection id  and sequence count    */
         /*TODO check connection id  and sequence count    */
         if (g_common_packet_format_data_item.data_item.type_id
         if (g_common_packet_format_data_item.data_item.type_id
             == kCipItemIdConnectedDataItem) { /* connected data item received*/
             == kCipItemIdConnectedDataItem) { /* connected data item received*/
-          EipUint8 *pnBuf = g_common_packet_format_data_item.data_item.data;
+          EipUint8 *buffer = g_common_packet_format_data_item.data_item.data;
           g_common_packet_format_data_item.address_item.data.sequence_number =
           g_common_packet_format_data_item.address_item.data.sequence_number =
-              (EipUint32) GetIntFromMessage(&pnBuf);
-          return_value = NotifyMR(
-              pnBuf, g_common_packet_format_data_item.data_item.length - 2);
+              (EipUint32) GetIntFromMessage((const EipUint8 ** const)&buffer);
+          return_value = NotifyMessageRouter(
+              buffer, g_common_packet_format_data_item.data_item.length - 2);
 
 
           if (return_value != kEipStatusError) {
           if (return_value != kEipStatusError) {
             g_common_packet_format_data_item.address_item.data
             g_common_packet_format_data_item.address_item.data
@@ -123,7 +128,7 @@ int NotifyConnectedCommonPacketFormat(EncapsulationData *received_data,
  * 	       kEipStatusError .. error
  * 	       kEipStatusError .. error
  */
  */
 EipStatus CreateCommonPacketFormatStructure(
 EipStatus CreateCommonPacketFormatStructure(
-    EipUint8 *data, int data_length,
+    const EipUint8 *data, int data_length,
     CipCommonPacketFormatData *common_packet_format_data) {
     CipCommonPacketFormatData *common_packet_format_data) {
 
 
   common_packet_format_data->address_info_item[0].type_id = 0;
   common_packet_format_data->address_info_item[0].type_id = 0;
@@ -150,7 +155,7 @@ EipStatus CreateCommonPacketFormatStructure(
   if (common_packet_format_data->item_count >= 2) {
   if (common_packet_format_data->item_count >= 2) {
     common_packet_format_data->data_item.type_id = GetIntFromMessage(&data);
     common_packet_format_data->data_item.type_id = GetIntFromMessage(&data);
     common_packet_format_data->data_item.length = GetIntFromMessage(&data);
     common_packet_format_data->data_item.length = GetIntFromMessage(&data);
-    common_packet_format_data->data_item.data = data;
+    common_packet_format_data->data_item.data = (EipUint8 *)data;
     data += common_packet_format_data->data_item.length;
     data += common_packet_format_data->data_item.length;
     length_count += (4 + common_packet_format_data->data_item.length);
     length_count += (4 + common_packet_format_data->data_item.length);
   }
   }
@@ -202,22 +207,20 @@ EipStatus CreateCommonPacketFormatStructure(
   }
   }
 }
 }
 
 
-/* null address item -> address length set to 0 */
 /**
 /**
- * Encodes a Null Address Item into the message frame
+ * @brief Encodes a Null Address Item into the message frame
  * @param message The message frame
  * @param message The message frame
  * @param size The actual size of the message frame
  * @param size The actual size of the message frame
  *
  *
  * @return The new size of the message frame after encoding
  * @return The new size of the message frame after encoding
  */
  */
 int EncodeNullAddressItem(EipUint8** message, int size) {
 int EncodeNullAddressItem(EipUint8** message, int size) {
-  /* null address item -> address length set to 0 */
   size += AddIntToMessage(kCipItemIdNullAddress, message);
   size += AddIntToMessage(kCipItemIdNullAddress, message);
+  /* null address item -> address length set to 0 */
   size += AddIntToMessage(0, message);
   size += AddIntToMessage(0, message);
   return size;
   return size;
 }
 }
 
 
-/* connected data item -> address length set to 4 and copy ConnectionIdentifier */
 /**
 /**
  * Encodes a Connected Address Item into the message frame
  * Encodes a Connected Address Item into the message frame
  * @param message The message frame
  * @param message The message frame
@@ -238,15 +241,21 @@ int EncodeConnectedAddressItem(
   return size;
   return size;
 }
 }
 
 
-/* TODO: Add doxygen documentation */
-/* sequenced address item -> address length set to 8 and copy ConnectionIdentifier and SequenceNumber */
-/* sequence number????? */
+/**
+ * @brief Encodes a sequenced address item into the message
+ *
+ * @param message Pointer to the message memory start
+ * @param common_packet_format_data_item Common Packet Format item which is used in the encoding
+ * @param size Size of the message at the start of the function
+ *
+ * @return New message size after encoding
+ */
 int EncodeSequencedAddressItem(
 int EncodeSequencedAddressItem(
     EipUint8** message,
     EipUint8** message,
     CipCommonPacketFormatData* common_packet_format_data_item, int size) {
     CipCommonPacketFormatData* common_packet_format_data_item, int size) {
   /* sequenced address item -> address length set to 8 and copy ConnectionIdentifier and SequenceNumber */
   /* sequenced address item -> address length set to 8 and copy ConnectionIdentifier and SequenceNumber */
   size += AddIntToMessage(kCipItemIdSequencedAddressItem, message);
   size += AddIntToMessage(kCipItemIdSequencedAddressItem, message);
-  size += AddIntToMessage(8, message);
+  size += AddIntToMessage(sequenced_address_item_length, message);
   size += AddDintToMessage(
   size += AddDintToMessage(
       common_packet_format_data_item->address_item.data.connection_identifier,
       common_packet_format_data_item->address_item.data.connection_identifier,
       message);
       message);
@@ -257,7 +266,7 @@ int EncodeSequencedAddressItem(
 }
 }
 
 
 /**
 /**
- * Adds the item count to the message frame
+ * @brief Adds the item count to the message frame
  *
  *
  * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
  * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
  * @param message The message frame
  * @param message The message frame
@@ -309,7 +318,7 @@ int EncodeDataItemLength(
  * Adds the data items to the message frame
  * Adds the data items to the message frame
  *
  *
  * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
  * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
- * @param message The message frame
+ * @param message Message frame to which the data is added
  * @param size The actual size of the message frame
  * @param size The actual size of the message frame
  *
  *
  * @return The new size of the message frame after encoding
  * @return The new size of the message frame after encoding
@@ -324,20 +333,39 @@ int EncodeDataItemData(
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the Connected Data item length
+ *
+ * @param message_router_response The Router Response message which shall be answered
+ * @param message Message frame to which the data is added
+ * @param size Current size of the message buffer
+ *
+ * @return The new size of the message buffer
+ */
+
 int EncodeConnectedDataItemLength(
 int EncodeConnectedDataItemLength(
     CipMessageRouterResponse* message_router_response, EipUint8** message,
     CipMessageRouterResponse* message_router_response, EipUint8** message,
     int size) {
     int size) {
   size += AddIntToMessage(
   size += AddIntToMessage(
-      (EipUint16) (message_router_response->data_length + 4 + 2
+      (EipUint16) (message_router_response->data_length + 4 + 2 /* TODO: Magic numbers */
           + (2 * message_router_response->size_of_additional_status)),
           + (2 * message_router_response->size_of_additional_status)),
       message);
       message);
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes a sequence number into the message
+ *
+ * @param size The current size of the message buffer
+ * @param common_packet_format_data_item
+ * @param message Message frame to which the data is added
+ *
+ * @return The new size of the message buffer
+ *
+ */
 int EncodeSequenceNumber(
 int EncodeSequenceNumber(
     int size, const CipCommonPacketFormatData* common_packet_format_data_item,
     int size, const CipCommonPacketFormatData* common_packet_format_data_item,
     EipUint8** message) {
     EipUint8** message) {
-  /* 2 bytes*/
   size += AddIntToMessage(
   size += AddIntToMessage(
       (EipUint16) common_packet_format_data_item->address_item.data
       (EipUint16) common_packet_format_data_item->address_item.data
           .sequence_number,
           .sequence_number,
@@ -345,25 +373,62 @@ int EncodeSequenceNumber(
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the reply service code for the requested service
+ *
+ * @param size The current size of the message buffer
+ * @param message Message frame to which the data is added
+ * @param message_rounter_response The router response message data structure to be processed
+ *
+ * @return The new size of the message buffer
+ */
 int EncodeReplyService(int size, EipUint8** message,
 int EncodeReplyService(int size, EipUint8** message,
                        CipMessageRouterResponse* message_router_response) {
                        CipMessageRouterResponse* message_router_response) {
   size += AddSintToMessage(message_router_response->reply_service, message);
   size += AddSintToMessage(message_router_response->reply_service, message);
   return size;
   return size;
 }
 }
 
 
-int EnocdeReservedFieldOfLengthByte(
+/**
+ * @brief Encodes the reserved byte in the message router response
+ *
+ * @param size Current size of the message buffer
+ * @param message Message frame to which the data is added
+ * @param message_router_response Router Response message to be processed
+ *
+ * @return New size of the message buffer
+ */
+int EncodeReservedFieldOfLengthByte(
     int size, EipUint8** message,
     int size, EipUint8** message,
     CipMessageRouterResponse* message_router_response) {
     CipMessageRouterResponse* message_router_response) {
   size += AddSintToMessage(message_router_response->reserved, message);
   size += AddSintToMessage(message_router_response->reserved, message);
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the general status of a Router Response
+ *
+ * @param size Current size of the message buffer
+ * @param message Message frame to which the data is added
+ * @param message_router_response Router Response message to be processed
+ *
+ * @return New size of the message buffer
+ */
 int EncodeGeneralStatus(int size, EipUint8** message,
 int EncodeGeneralStatus(int size, EipUint8** message,
                         CipMessageRouterResponse* message_router_response) {
                         CipMessageRouterResponse* message_router_response) {
   size += AddSintToMessage(message_router_response->general_status, message);
   size += AddSintToMessage(message_router_response->general_status, message);
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the length of the extended status data part
+ *
+ * @param size Current size of the message buffer
+ * @param message Message frame to which the data is added
+ * @param message_router_response Router Response message to be processed
+ *
+ * @return New size of the message buffer
+ */
+
 int EncodeExtendedStatusLength(
 int EncodeExtendedStatusLength(
     int size, EipUint8** message,
     int size, EipUint8** message,
     CipMessageRouterResponse* message_router_response) {
     CipMessageRouterResponse* message_router_response) {
@@ -372,6 +437,15 @@ int EncodeExtendedStatusLength(
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the extended status data items
+ *
+ * @param size Current size of the message buffer
+ * @param message_router_response Router Response message to be processed
+ * @param message Message frame to which the data is added
+ *
+ * @return New size of the message buffer
+ */
 int EncodeExtendedStatusDataItems(
 int EncodeExtendedStatusDataItems(
     int size, CipMessageRouterResponse* message_router_response,
     int size, CipMessageRouterResponse* message_router_response,
     EipUint8** message) {
     EipUint8** message) {
@@ -382,6 +456,19 @@ int EncodeExtendedStatusDataItems(
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the extended status (length and data) into the message
+ *
+ * This function uses EncodeExtendedStatusLength and EncodeExtendedStatusDataItems
+ * to encode the complete extended status information into the message
+ *
+ * @param size Current size of the message buffer
+ * @param message Message frame to which the data is added
+ * @param message_router_response Router Response message to be processed
+ *
+ * @return New size of the message buffer
+ */
+
 int EncodeExtendedStatus(int size, EipUint8** message,
 int EncodeExtendedStatus(int size, EipUint8** message,
                          CipMessageRouterResponse* message_router_response) {
                          CipMessageRouterResponse* message_router_response) {
   size = EncodeExtendedStatusLength(size, message, message_router_response);
   size = EncodeExtendedStatusLength(size, message, message_router_response);
@@ -390,17 +477,32 @@ int EncodeExtendedStatus(int size, EipUint8** message,
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encode the data item length of the unconnected data segment
+ *
+ * @param size Current size of the message buffer
+ * @param message_router_response Router Response message to be processed
+ * @param message Message frame to which the data is added
+ *
+ * @return New size of the message buffer
+ */
 int EncodeUnconnectedDataItemLength(
 int EncodeUnconnectedDataItemLength(
     int size, CipMessageRouterResponse* message_router_response,
     int size, CipMessageRouterResponse* message_router_response,
     EipUint8** message) {
     EipUint8** message) {
-  /* Unconnected Item */
   size += AddIntToMessage(
   size += AddIntToMessage(
-      (EipUint16) (message_router_response->data_length + 4
+      (EipUint16) (message_router_response->data_length + 4 /* TODO: Magic number */
           + (2 * message_router_response->size_of_additional_status)),
           + (2 * message_router_response->size_of_additional_status)),
       message);
       message);
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the Message Router Response data
+ *
+ * @param size Current size of the message buffer
+ * @param message_router_response Router Response message to be processed
+ * @param message Message frame to which the data is added
+ */
 int EncodeMessageRouterResponseData(
 int EncodeMessageRouterResponseData(
     int size, CipMessageRouterResponse* message_router_response,
     int size, CipMessageRouterResponse* message_router_response,
     EipUint8** message) {
     EipUint8** message) {
@@ -410,6 +512,16 @@ int EncodeMessageRouterResponseData(
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the sockaddr info type id into the message
+ *
+ * @param size Current size of the message buffer
+ * @param item_type
+ * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
+ * @param message Message frame to which the encoded data is added
+ *
+ * @return New size of the message buffer
+ */
 int EncodeSockaddrInfoItemTypeId(
 int EncodeSockaddrInfoItemTypeId(
     int size, int item_type,
     int size, int item_type,
     CipCommonPacketFormatData* common_packet_format_data_item,
     CipCommonPacketFormatData* common_packet_format_data_item,
@@ -422,11 +534,21 @@ int EncodeSockaddrInfoItemTypeId(
   return size;
   return size;
 }
 }
 
 
+/**
+ * @brief Encodes the sockaddr info length into the message
+ *
+ * @param size Current size of the message buffer
+ * @param item_type
+ * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
+ * @param message Message frame to which the encoded data is added
+ *
+ * @return New size of the message buffer
+ */
 int EncodeSockaddrInfoLength(
 int EncodeSockaddrInfoLength(
-    int size, int j, CipCommonPacketFormatData* common_packet_format_data_item,
+    int size, int item_type, CipCommonPacketFormatData* common_packet_format_data_item,
     EipUint8** message) {
     EipUint8** message) {
   size += AddIntToMessage(
   size += AddIntToMessage(
-      common_packet_format_data_item->address_info_item[j].length, message);
+      common_packet_format_data_item->address_info_item[item_type].length, message);
   return size;
   return size;
 }
 }
 
 
@@ -444,7 +566,7 @@ int AssembleLinearMessage(
     CipCommonPacketFormatData *common_packet_format_data_item,
     CipCommonPacketFormatData *common_packet_format_data_item,
     EipUint8 *message) {
     EipUint8 *message) {
 
 
-  int message_size = 0;
+  size_t message_size = 0;
 
 
   if (message_router_response) {
   if (message_router_response) {
     /* add Interface Handle and Timeout = 0 -> only for SendRRData and SendUnitData necessary */
     /* add Interface Handle and Timeout = 0 -> only for SendRRData and SendUnitData necessary */
@@ -503,7 +625,7 @@ int AssembleLinearMessage(
       /* write message router response into linear memory */
       /* write message router response into linear memory */
       message_size = EncodeReplyService(message_size, &message,
       message_size = EncodeReplyService(message_size, &message,
                                         message_router_response);
                                         message_router_response);
-      message_size = EnocdeReservedFieldOfLengthByte(message_size, &message,
+      message_size = EncodeReservedFieldOfLengthByte(message_size, &message,
                                                      message_router_response);
                                                      message_router_response);
       message_size = EncodeGeneralStatus(message_size, &message,
       message_size = EncodeGeneralStatus(message_size, &message,
                                          message_router_response);
                                          message_router_response);

+ 3 - 3
source/src/enet_encap/cpf.h

@@ -76,8 +76,8 @@ typedef struct {
  * @param  reply_buffer reply buffer
  * @param  reply_buffer reply buffer
  * @return number of bytes to be sent back. < 0 if nothing should be sent
  * @return number of bytes to be sent back. < 0 if nothing should be sent
  */
  */
-int NotifyCommonPacketFormat(EncapsulationData *received_data,
-                             EipUint8 *reply_buffer);
+int NotifyCommonPacketFormat(EncapsulationData *const received_data,
+                             EipUint8 *const reply_buffer);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP
  * Parse the CPF data from a received connected explicit message, check
  * Parse the CPF data from a received connected explicit message, check
@@ -101,7 +101,7 @@ int NotifyConnectedCommonPacketFormat(EncapsulationData *received_data,
  * 	       EIP_ERROR .. error
  * 	       EIP_ERROR .. error
  */
  */
 EipStatus CreateCommonPacketFormatStructure(
 EipStatus CreateCommonPacketFormatStructure(
-    EipUint8 *data, int data_length,
+    const EipUint8 *data, int data_length,
     CipCommonPacketFormatData *common_packet_format_data);
     CipCommonPacketFormatData *common_packet_format_data);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP

+ 40 - 29
source/src/enet_encap/encap.c

@@ -6,9 +6,10 @@
 #include <string.h>
 #include <string.h>
 #include <stdlib.h>
 #include <stdlib.h>
 
 
+#include "encap.h"
+
 #include "opener_api.h"
 #include "opener_api.h"
 #include "cpf.h"
 #include "cpf.h"
-#include "encap.h"
 #include "endianconv.h"
 #include "endianconv.h"
 #include "cipcommon.h"
 #include "cipcommon.h"
 #include "cipmessagerouter.h"
 #include "cipmessagerouter.h"
@@ -107,7 +108,7 @@ EipStatus HandleReceivedSendRequestResponseDataCommand(
 
 
 int GetFreeSessionIndex(void);
 int GetFreeSessionIndex(void);
 
 
-EipInt16 CreateEncapsulationStructure(EipUint8 *receive_buffer,
+EipInt16 CreateEncapsulationStructure(const EipUint8 *receive_buffer,
                                       int receive_buffer_length,
                                       int receive_buffer_length,
                                       EncapsulationData *encapsulation_data);
                                       EncapsulationData *encapsulation_data);
 
 
@@ -150,7 +151,8 @@ void EncapsulationInit(void) {
 
 
 int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
 int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
                                  unsigned int length, int *remaining_bytes) {
                                  unsigned int length, int *remaining_bytes) {
-  EipStatus return_value = kEipStatusOk;
+  int return_value = 0;
+  EipStatus status = kEipStatusOk;
   EncapsulationData encapsulation_data;
   EncapsulationData encapsulation_data;
   /* eat the encapsulation header*/
   /* eat the encapsulation header*/
   /* the structure contains a pointer to the encapsulated data*/
   /* the structure contains a pointer to the encapsulated data*/
@@ -164,12 +166,12 @@ int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
     {
     {
       /* full package or more received */
       /* full package or more received */
       encapsulation_data.status = kEncapsulationProtocolSuccess;
       encapsulation_data.status = kEncapsulationProtocolSuccess;
-      return_value = kEipStatusOkSend;
+	  status = kEipStatusOkSend;
       /* most of these functions need a reply to be send */
       /* most of these functions need a reply to be send */
       switch (encapsulation_data.command_code) {
       switch (encapsulation_data.command_code) {
         case (kEncapsulationCommandNoOperation):
         case (kEncapsulationCommandNoOperation):
           /* NOP needs no reply and does nothing */
           /* NOP needs no reply and does nothing */
-          return_value = kEipStatusOk;
+          status = kEipStatusOk;
           break;
           break;
 
 
         case (kEncapsulationCommandListServices):
         case (kEncapsulationCommandListServices):
@@ -189,17 +191,17 @@ int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
           break;
           break;
 
 
         case (kEncapsulationCommandUnregisterSession):
         case (kEncapsulationCommandUnregisterSession):
-          return_value = HandleReceivedUnregisterSessionCommand(
+          status = HandleReceivedUnregisterSessionCommand(
               &encapsulation_data);
               &encapsulation_data);
           break;
           break;
 
 
         case (kEncapsulationCommandSendRequestReplyData):
         case (kEncapsulationCommandSendRequestReplyData):
-          return_value = HandleReceivedSendRequestResponseDataCommand(
+          status = HandleReceivedSendRequestResponseDataCommand(
               &encapsulation_data);
               &encapsulation_data);
           break;
           break;
 
 
         case (kEncapsulationCommandSendUnitData):
         case (kEncapsulationCommandSendUnitData):
-          return_value = HandleReceivedSendUnitDataCommand(&encapsulation_data);
+          status = HandleReceivedSendUnitDataCommand(&encapsulation_data);
           break;
           break;
 
 
         default:
         default:
@@ -207,9 +209,13 @@ int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
           encapsulation_data.data_length = 0;
           encapsulation_data.data_length = 0;
           break;
           break;
       }
       }
-      /* if nRetVal is greater than 0 data has to be sent */
-      if (kEipStatusOk < return_value) {
+      
+      if (kEipStatusOk < status) {
+        /* if status is greater than 0 data has to be sent */
         return_value = EncapsulateData(&encapsulation_data);
         return_value = EncapsulateData(&encapsulation_data);
+      } else if (kEipStatusError == status) {
+        /* Report error state with negative return value */
+        return_value = -1;
       }
       }
     }
     }
   }
   }
@@ -220,6 +226,7 @@ int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
 int HandleReceivedExplictUdpData(int socket, struct sockaddr_in *from_address,
 int HandleReceivedExplictUdpData(int socket, struct sockaddr_in *from_address,
                                  EipUint8 *buffer, unsigned int buffer_length,
                                  EipUint8 *buffer, unsigned int buffer_length,
                                  int *number_of_remaining_bytes, int unicast) {
                                  int *number_of_remaining_bytes, int unicast) {
+  int return_value = 0;
   EipStatus status = kEipStatusOk;
   EipStatus status = kEipStatusOk;
   EncapsulationData encapsulation_data;
   EncapsulationData encapsulation_data;
   /* eat the encapsulation header*/
   /* eat the encapsulation header*/
@@ -267,13 +274,17 @@ int HandleReceivedExplictUdpData(int socket, struct sockaddr_in *from_address,
           encapsulation_data.data_length = 0;
           encapsulation_data.data_length = 0;
           break;
           break;
       }
       }
-      /* if nRetVal is greater than 0 data has to be sent */
-      if (0 < status) {
-        status = EncapsulateData(&encapsulation_data);
+      
+      if (kEipStatusOk < status) {
+        /* if status is greater than 0 data has to be sent */
+        return_value = EncapsulateData(&encapsulation_data);
+      } else if (kEipStatusError == status) {
+        /* Report error state with negative return value */
+        return_value = -1;  
       }
       }
     }
     }
   }
   }
-  return status;
+  return return_value;
 }
 }
 
 
 int EncapsulateData(const EncapsulationData *const send_data) {
 int EncapsulateData(const EncapsulationData *const send_data) {
@@ -397,7 +408,7 @@ void DetermineDelayTime(EipByte *buffer_start,
                         DelayedEncapsulationMessage *delayed_message_buffer) {
                         DelayedEncapsulationMessage *delayed_message_buffer) {
 
 
   buffer_start += 12; /* start of the sender context */
   buffer_start += 12; /* start of the sender context */
-  EipUint16 maximum_delay_time = GetIntFromMessage(&buffer_start);
+  EipUint16 maximum_delay_time = GetIntFromMessage((const EipUint8 **const)&buffer_start);
 
 
   if (0 == maximum_delay_time) {
   if (0 == maximum_delay_time) {
     maximum_delay_time = kListIdentityDefaultDelayTime;
     maximum_delay_time = kListIdentityDefaultDelayTime;
@@ -414,11 +425,11 @@ void DetermineDelayTime(EipByte *buffer_start,
 void HandleReceivedRegisterSessionCommand(int socket,
 void HandleReceivedRegisterSessionCommand(int socket,
                                           EncapsulationData *receive_data) {
                                           EncapsulationData *receive_data) {
   int session_index = 0;
   int session_index = 0;
-  EipUint8 *receive_data_buffer;
+  const EipUint8 *receive_data_buffer = NULL;
   EipUint16 protocol_version = GetIntFromMessage(
   EipUint16 protocol_version = GetIntFromMessage(
-      &receive_data->current_communication_buffer_position);
+      (const EipUint8 **const)&receive_data->current_communication_buffer_position);
   EipUint16 nOptionFlag = GetIntFromMessage(
   EipUint16 nOptionFlag = GetIntFromMessage(
-      &receive_data->current_communication_buffer_position);
+      (const EipUint8 **const)&receive_data->current_communication_buffer_position);
 
 
   /* check if requested protocol version is supported and the register session option flag is zero*/
   /* check if requested protocol version is supported and the register session option flag is zero*/
   if ((0 < protocol_version) && (protocol_version <= kSupportedProtocolVersion)
   if ((0 < protocol_version) && (protocol_version <= kSupportedProtocolVersion)
@@ -432,7 +443,7 @@ void HandleReceivedRegisterSessionCommand(int socket,
         session_index = kSessionStatusInvalid;
         session_index = kSessionStatusInvalid;
         receive_data_buffer =
         receive_data_buffer =
             &receive_data->communication_buffer_start[kEncapsulationHeaderSessionHandlePosition];
             &receive_data->communication_buffer_start[kEncapsulationHeaderSessionHandlePosition];
-        AddDintToMessage(receive_data->session_handle, &receive_data_buffer); /*EncapsulateData will not update the session handle so we have to do it here by hand*/
+        AddDintToMessage(receive_data->session_handle, (EipUint8 **const)&receive_data_buffer); /*EncapsulateData will not update the session handle so we have to do it here by hand*/
         break;
         break;
       }
       }
     }
     }
@@ -448,7 +459,7 @@ void HandleReceivedRegisterSessionCommand(int socket,
         receive_data->status = kEncapsulationProtocolSuccess;
         receive_data->status = kEncapsulationProtocolSuccess;
         receive_data_buffer =
         receive_data_buffer =
             &receive_data->communication_buffer_start[kEncapsulationHeaderSessionHandlePosition];
             &receive_data->communication_buffer_start[kEncapsulationHeaderSessionHandlePosition];
-        AddDintToMessage(receive_data->session_handle, &receive_data_buffer); /*EncapsulateData will not update the session handle so we have to do it here by hand*/
+        AddDintToMessage(receive_data->session_handle, (EipUint8 **const)&receive_data_buffer); /*EncapsulateData will not update the session handle so we have to do it here by hand*/
       }
       }
     }
     }
   } else { /* protocol not supported */
   } else { /* protocol not supported */
@@ -492,8 +503,8 @@ EipStatus HandleReceivedSendUnitDataCommand(EncapsulationData *receive_data) {
   if (receive_data->data_length >= 6) {
   if (receive_data->data_length >= 6) {
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* don't use the data yet */
     /* don't use the data yet */
-    GetDintFromMessage(&receive_data->current_communication_buffer_position); /* skip over null interface handle*/
-    GetIntFromMessage(&receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
+    GetDintFromMessage((const EipUint8 **const)&receive_data->current_communication_buffer_position); /* skip over null interface handle*/
+    GetIntFromMessage((const EipUint8 **const)&receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
     receive_data->data_length -= 6; /* the rest is in CPF format*/
     receive_data->data_length -= 6; /* the rest is in CPF format*/
 
 
     if (kSessionStatusValid == CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
     if (kSessionStatusValid == CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
@@ -523,14 +534,14 @@ EipStatus HandleReceivedSendUnitDataCommand(EncapsulationData *receive_data) {
  */
  */
 EipStatus HandleReceivedSendRequestResponseDataCommand(
 EipStatus HandleReceivedSendRequestResponseDataCommand(
     EncapsulationData *receive_data) {
     EncapsulationData *receive_data) {
-  EipInt16 send_size;
+  EipInt16 send_size = 0;
   EipStatus return_value = kEipStatusOkSend;
   EipStatus return_value = kEipStatusOkSend;
 
 
   if (receive_data->data_length >= 6) {
   if (receive_data->data_length >= 6) {
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* don't use the data yet */
     /* don't use the data yet */
-    GetDintFromMessage(&receive_data->current_communication_buffer_position); /* skip over null interface handle*/
-    GetIntFromMessage(&receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
+    GetDintFromMessage((const EipUint8 **const)&receive_data->current_communication_buffer_position); /* skip over null interface handle*/
+    GetIntFromMessage((const EipUint8 **const)&receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
     receive_data->data_length -= 6; /* the rest is in CPF format*/
     receive_data->data_length -= 6; /* the rest is in CPF format*/
 
 
     if (kSessionStatusValid == CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
     if (kSessionStatusValid == CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
@@ -575,10 +586,10 @@ int GetFreeSessionIndex(void) {
  * 			>0 .. more than one packet received
  * 			>0 .. more than one packet received
  * 			<0 .. only fragment of data portion received
  * 			<0 .. only fragment of data portion received
  */
  */
-EipInt16 CreateEncapsulationStructure(EipUint8 *receive_buffer,
+EipInt16 CreateEncapsulationStructure(const EipUint8 *receive_buffer,
                                       int receive_buffer_length,
                                       int receive_buffer_length,
                                       EncapsulationData *encapsulation_data) {
                                       EncapsulationData *encapsulation_data) {
-  encapsulation_data->communication_buffer_start = receive_buffer;
+  encapsulation_data->communication_buffer_start = (EipUint8 *)receive_buffer;
   encapsulation_data->command_code = GetIntFromMessage(&receive_buffer);
   encapsulation_data->command_code = GetIntFromMessage(&receive_buffer);
   encapsulation_data->data_length = GetIntFromMessage(&receive_buffer);
   encapsulation_data->data_length = GetIntFromMessage(&receive_buffer);
   encapsulation_data->session_handle = GetDintFromMessage(&receive_buffer);
   encapsulation_data->session_handle = GetDintFromMessage(&receive_buffer);
@@ -586,7 +597,7 @@ EipInt16 CreateEncapsulationStructure(EipUint8 *receive_buffer,
 
 
   receive_buffer += kSenderContextSize;
   receive_buffer += kSenderContextSize;
   encapsulation_data->options = GetDintFromMessage(&receive_buffer);
   encapsulation_data->options = GetDintFromMessage(&receive_buffer);
-  encapsulation_data->current_communication_buffer_position = receive_buffer;
+  encapsulation_data->current_communication_buffer_position = (EipUint8 *)receive_buffer;
   return (receive_buffer_length - ENCAPSULATION_HEADER_LENGTH
   return (receive_buffer_length - ENCAPSULATION_HEADER_LENGTH
       - encapsulation_data->data_length);
       - encapsulation_data->data_length);
 }
 }
@@ -627,7 +638,7 @@ void EncapsulationShutDown(void) {
   }
   }
 }
 }
 
 
-void ManageEncapsulationMessages(MilliSeconds elapsed_time) {
+void ManageEncapsulationMessages(const MilliSeconds elapsed_time) {
   for (unsigned int i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
   for (unsigned int i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
     if (kEipInvalidSocket != g_delayed_encapsulation_messages[i].socket) {
     if (kEipInvalidSocket != g_delayed_encapsulation_messages[i].socket) {
       g_delayed_encapsulation_messages[i].time_out -=
       g_delayed_encapsulation_messages[i].time_out -=

+ 1 - 1
source/src/enet_encap/encap.h

@@ -78,6 +78,6 @@ void EncapsulationShutDown(void);
  * message. This functions checks if messages need to be sent and performs the
  * message. This functions checks if messages need to be sent and performs the
  * sending.
  * sending.
  */
  */
-void ManageEncapsulationMessages(MilliSeconds elapsed_time);
+void ManageEncapsulationMessages(const MilliSeconds elapsed_time);
 
 
 #endif /* OPENER_ENCAP_H_ */
 #endif /* OPENER_ENCAP_H_ */

+ 13 - 13
source/src/enet_encap/endianconv.c

@@ -26,8 +26,8 @@ OpenerEndianess g_opener_platform_endianess = kOpenerEndianessUnknown;
  *   @param buffer pointer where data should be reed.
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT8 data value
  *   @return EIP_UINT8 data value
  */
  */
-EipUint8 GetSintFromMessage(EipUint8** buffer) {
-  unsigned char *buffer_address = (unsigned char *) *buffer;
+EipUint8 GetSintFromMessage(const EipUint8 **const  buffer) {
+  const unsigned char *const buffer_address = (unsigned char *) *buffer;
   EipUint16 data = buffer_address[0];
   EipUint16 data = buffer_address[0];
   *buffer += 1;
   *buffer += 1;
   return data;
   return data;
@@ -40,8 +40,8 @@ EipUint8 GetSintFromMessage(EipUint8** buffer) {
  *   @param buffer pointer where data should be reed.
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT16 data value
  *   @return EIP_UINT16 data value
  */
  */
-EipUint16 GetIntFromMessage(EipUint8** buffer) {
-  unsigned char *buffer_address = (unsigned char *) *buffer;
+EipUint16 GetIntFromMessage(const EipUint8 **const buffer) {
+  const unsigned char *const buffer_address = (unsigned char *) *buffer;
   EipUint16 data = buffer_address[0] | buffer_address[1] << 8;
   EipUint16 data = buffer_address[0] | buffer_address[1] << 8;
   *buffer += 2;
   *buffer += 2;
   return data;
   return data;
@@ -52,8 +52,8 @@ EipUint16 GetIntFromMessage(EipUint8** buffer) {
  *   @param buffer pointer where data should be reed.
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UNÍT32 value
  *   @return EIP_UNÍT32 value
  */
  */
-EipUint32 GetDintFromMessage(EipUint8** buffer) {
-  unsigned char *p = (unsigned char *) *buffer;
+EipUint32 GetDintFromMessage(const EipUint8 **const buffer) {
+  const unsigned char *p = (unsigned char *) *buffer;
   EipUint32 data = p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24;
   EipUint32 data = p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24;
   *buffer += 4;
   *buffer += 4;
   return data;
   return data;
@@ -64,7 +64,7 @@ EipUint32 GetDintFromMessage(EipUint8** buffer) {
  * @param data value to be written
  * @param data value to be written
  * @param buffer pointer where data should be written.
  * @param buffer pointer where data should be written.
  */
  */
-int AddSintToMessage(EipUint8 data, EipUint8 **buffer) {
+int AddSintToMessage(const EipUint8 data, EipUint8 **const buffer) {
   unsigned char *p = (unsigned char *) *buffer;
   unsigned char *p = (unsigned char *) *buffer;
 
 
   p[0] = (unsigned char) data;
   p[0] = (unsigned char) data;
@@ -77,7 +77,7 @@ int AddSintToMessage(EipUint8 data, EipUint8 **buffer) {
  * @param data value to be written
  * @param data value to be written
  * @param buffer pointer where data should be written.
  * @param buffer pointer where data should be written.
  */
  */
-int AddIntToMessage(EipUint16 data, EipUint8 **buffer) {
+int AddIntToMessage(const EipUint16 data, EipUint8 **const buffer) {
   unsigned char *p = (unsigned char *) *buffer;
   unsigned char *p = (unsigned char *) *buffer;
 
 
   p[0] = (unsigned char) data;
   p[0] = (unsigned char) data;
@@ -91,7 +91,7 @@ int AddIntToMessage(EipUint16 data, EipUint8 **buffer) {
  * @param data value to be written
  * @param data value to be written
  * @param buffer pointer where data should be written.
  * @param buffer pointer where data should be written.
  */
  */
-int AddDintToMessage(EipUint32 data, EipUint8** buffer) {
+int AddDintToMessage(const EipUint32 data, EipUint8 **const buffer) {
   unsigned char *p = (unsigned char *) *buffer;
   unsigned char *p = (unsigned char *) *buffer;
 
 
   p[0] = (unsigned char) data;
   p[0] = (unsigned char) data;
@@ -110,8 +110,8 @@ int AddDintToMessage(EipUint32 data, EipUint8** buffer) {
  *   @param pa_buf pointer where data should be reed.
  *   @param pa_buf pointer where data should be reed.
  *   @return EipUint64 value
  *   @return EipUint64 value
  */
  */
-EipUint64 GetLintFromMessage(EipUint8 **buffer) {
-  EipUint8 *buffer_address = *buffer;
+EipUint64 GetLintFromMessage(const EipUint8 **const buffer) {
+  const EipUint8 *buffer_address = *buffer;
   EipUint64 data = ((((EipUint64) buffer_address[0]) << 56)
   EipUint64 data = ((((EipUint64) buffer_address[0]) << 56)
       & 0xFF00000000000000LL)
       & 0xFF00000000000000LL)
       + ((((EipUint64) buffer_address[1]) << 48) & 0x00FF000000000000LL)
       + ((((EipUint64) buffer_address[1]) << 48) & 0x00FF000000000000LL)
@@ -121,7 +121,7 @@ EipUint64 GetLintFromMessage(EipUint8 **buffer) {
       + ((((EipUint64) buffer_address[5]) << 16) & 0x0000000000FF0000)
       + ((((EipUint64) buffer_address[5]) << 16) & 0x0000000000FF0000)
       + ((((EipUint64) buffer_address[6]) << 8) & 0x000000000000FF00)
       + ((((EipUint64) buffer_address[6]) << 8) & 0x000000000000FF00)
       + (((EipUint64) buffer_address[7]) & 0x00000000000000FF);
       + (((EipUint64) buffer_address[7]) & 0x00000000000000FF);
-  (*buffer) += 8;
+  *buffer += 8;
   return data;
   return data;
 }
 }
 
 
@@ -130,7 +130,7 @@ EipUint64 GetLintFromMessage(EipUint8 **buffer) {
  * @param data value to be written
  * @param data value to be written
  * @param buffer pointer where data should be written.
  * @param buffer pointer where data should be written.
  */
  */
-int AddLintToMessage(EipUint64 data, EipUint8 **buffer) {
+int AddLintToMessage(const EipUint64 data, EipUint8 **const buffer) {
   EipUint8 *buffer_address = *buffer;
   EipUint8 *buffer_address = *buffer;
   buffer_address[0] = (EipUint8) (data >> 56) & 0xFF;
   buffer_address[0] = (EipUint8) (data >> 56) & 0xFF;
   buffer_address[1] = (EipUint8) (data >> 48) & 0xFF;
   buffer_address[1] = (EipUint8) (data >> 48) & 0xFF;

+ 8 - 8
source/src/enet_encap/endianconv.h

@@ -23,7 +23,7 @@ typedef enum {
  *   @param buffer pointer where data should be reed.
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT8 data value
  *   @return EIP_UINT8 data value
  */
  */
-EipUint8 GetSintFromMessage(EipUint8** buffer);
+EipUint8 GetSintFromMessage(const EipUint8 **const buffer);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP
  *
  *
@@ -31,7 +31,7 @@ EipUint8 GetSintFromMessage(EipUint8** buffer);
  * @param buffer Pointer to the network buffer array. This pointer will be incremented by 2!
  * @param buffer Pointer to the network buffer array. This pointer will be incremented by 2!
  * @return Extracted 16 bit integer value
  * @return Extracted 16 bit integer value
  */
  */
-EipUint16 GetIntFromMessage(EipUint8 **buffer);
+EipUint16 GetIntFromMessage(const EipUint8 **const buffer);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP
  *
  *
@@ -39,7 +39,7 @@ EipUint16 GetIntFromMessage(EipUint8 **buffer);
  * @param buffer pointer to the network buffer array. This pointer will be incremented by 4!
  * @param buffer pointer to the network buffer array. This pointer will be incremented by 4!
  * @return Extracted 32 bit integer value
  * @return Extracted 32 bit integer value
  */
  */
-EipUint32 GetDintFromMessage(EipUint8 **buffer);
+EipUint32 GetDintFromMessage(const EipUint8 **const buffer);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP
  *
  *
@@ -47,7 +47,7 @@ EipUint32 GetDintFromMessage(EipUint8 **buffer);
  * @param data value to be written
  * @param data value to be written
  * @param buffer pointer where data should be written.
  * @param buffer pointer where data should be written.
  */
  */
-int AddSintToMessage(EipUint8 data, EipUint8 **buffer);
+int AddSintToMessage(const EipUint8 data, EipUint8 **const buffer);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP
  *
  *
@@ -57,7 +57,7 @@ int AddSintToMessage(EipUint8 data, EipUint8 **buffer);
  *
  *
  * @return Length in bytes of the encoded message
  * @return Length in bytes of the encoded message
  */
  */
-int AddIntToMessage(EipUint16 data, EipUint8 **buffer);
+int AddIntToMessage(const EipUint16 data, EipUint8 **const buffer);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP
  *
  *
@@ -67,11 +67,11 @@ int AddIntToMessage(EipUint16 data, EipUint8 **buffer);
  *
  *
  * @return Length in bytes of the encoded message
  * @return Length in bytes of the encoded message
  */
  */
-int AddDintToMessage(EipUint32 data, EipUint8 **buffer);
+int AddDintToMessage(const EipUint32 data, EipUint8 **const buffer);
 
 
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 
 
-EipUint64 GetLintFromMessage(EipUint8 **buffer);
+EipUint64 GetLintFromMessage(const EipUint8 **const buffer);
 
 
 /** @ingroup ENCAP
 /** @ingroup ENCAP
  *
  *
@@ -81,7 +81,7 @@ EipUint64 GetLintFromMessage(EipUint8 **buffer);
  *
  *
  * @return Length in bytes of the encoded message
  * @return Length in bytes of the encoded message
  */
  */
-int AddLintToMessage(EipUint64 pa_unData, EipUint8 **buffer);
+int AddLintToMessage(const EipUint64 pa_unData, EipUint8 **const buffer);
 
 
 #endif
 #endif
 
 

+ 46 - 46
source/src/opener_api.h

@@ -30,41 +30,41 @@
  *  @return EIP_OK if the configuring worked otherwise EIP_ERROR
  *  @return EIP_OK if the configuring worked otherwise EIP_ERROR
  */
  */
 EipStatus
 EipStatus
-ConfigureNetworkInterface(const char *ip_address, const char *subnet_mask,
-                          const char *gateway_address);
+ConfigureNetworkInterface(const char *const ip_address, const char *const subnet_mask,
+                          const char *const gateway_address);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Configure the MAC address of the device
  * @brief Configure the MAC address of the device
  *
  *
  *  @param mac_address  the hardware MAC address of the network interface
  *  @param mac_address  the hardware MAC address of the network interface
  */
  */
-void ConfigureMacAddress(const EipUint8 *mac_address);
+void ConfigureMacAddress(const EipUint8 *const mac_address);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Configure the domain name of the device
  * @brief Configure the domain name of the device
  * @param domain_name the domain name to be used
  * @param domain_name the domain name to be used
  */
  */
-void ConfigureDomainName(const char *domain_name);
+void ConfigureDomainName(const char *const restrict domain_name);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Configure the host name of the device
  * @brief Configure the host name of the device
  * @param host_name the host name to be used
  * @param host_name the host name to be used
  */
  */
-void ConfigureHostName(const char *host_name);
+void ConfigureHostName(const char *const restrict host_name);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Set the serial number of the device's identity object.
  * @brief Set the serial number of the device's identity object.
  *
  *
  * @param serial_number unique 32 bit number identifying the device
  * @param serial_number unique 32 bit number identifying the device
  */
  */
-void SetDeviceSerialNumber(EipUint32 serial_number);
+void SetDeviceSerialNumber(const EipUint32 serial_number);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Set the current status of the device.
  * @brief Set the current status of the device.
  *
  *
  * @param device_status the new status value
  * @param device_status the new status value
  */
  */
-void SetDeviceStatus(EipUint16 device_status);
+void SetDeviceStatus(const EipUint16 device_status);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Initialize and setup the CIP-stack
  * @brief Initialize and setup the CIP-stack
@@ -72,7 +72,7 @@ void SetDeviceStatus(EipUint16 device_status);
  * @param unique_connection_id value passed to Connection_Manager_Init() to form
  * @param unique_connection_id value passed to Connection_Manager_Init() to form
  * a "per boot" unique connection ID.
  * a "per boot" unique connection ID.
  */
  */
-void CipStackInit(EipUint16 unique_connection_id);
+void CipStackInit(const EipUint16 unique_connection_id);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Shutdown of the CIP stack
  * @brief Shutdown of the CIP stack
@@ -94,7 +94,7 @@ void ShutdownCipStack(void);
  * @return pointer to CIP Object
  * @return pointer to CIP Object
  *          0 if object is not present in the stack
  *          0 if object is not present in the stack
  */
  */
-CipClass *GetCipClass(EipUint32 class_id);
+CipClass *GetCipClass(const EipUint32 class_id);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Get a pointer to an instance
  * @brief Get a pointer to an instance
@@ -104,7 +104,7 @@ CipClass *GetCipClass(EipUint32 class_id);
  * @return pointer to CIP Instance
  * @return pointer to CIP Instance
  *          0 if instance is not in the object
  *          0 if instance is not in the object
  */
  */
-CipInstance *GetCipInstance(CipClass *cip_object, EipUint32 instance_number);
+CipInstance *GetCipInstance(const CipClass *restrict const cip_object, const EipUint32 instance_number);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Get a pointer to an instance's attribute
  * @brief Get a pointer to an instance's attribute
@@ -116,8 +116,8 @@ CipInstance *GetCipInstance(CipClass *cip_object, EipUint32 instance_number);
  * @return pointer to attribute
  * @return pointer to attribute
  *          0 if instance is not in the object
  *          0 if instance is not in the object
  */
  */
-CipAttributeStruct *GetCipAttribute(CipInstance *cip_instance,
-                                    EipUint16 attribute_number);
+CipAttributeStruct *GetCipAttribute(const CipInstance *const cip_instance,
+                                    const EipUint16 attribute_number);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Allocate memory for new CIP Class and attributes
  * @brief Allocate memory for new CIP Class and attributes
@@ -144,14 +144,14 @@ CipAttributeStruct *GetCipAttribute(CipInstance *cip_instance,
  *  @return pointer to new class object
  *  @return pointer to new class object
  *      0 on error
  *      0 on error
  */
  */
-CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
-                         EipUint32 class_attributes_get_attribute_all_mask,
-                         int number_of_class_services,
-                         int number_of_instance_attributes,
-                         EipUint32 instance_attributes_get_attributes_all_mask,
-                         int number_of_instance_services,
-                         int number_of_instances, char *class_name,
-                         EipUint16 class_revision);
+CipClass *CreateCipClass(const EipUint32 class_id, const int number_of_class_attributes,
+                         const EipUint32 class_attributes_get_attribute_all_mask,
+                         const int number_of_class_services,
+                         const int number_of_instance_attributes,
+                         const EipUint32 instance_attributes_get_attributes_all_mask,
+                         const int number_of_instance_services,
+                         const int number_of_instances, char *class_name,
+                         const EipUint16 class_revision);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Add a number of CIP instances to a given CIP class
  * @brief Add a number of CIP instances to a given CIP class
@@ -171,8 +171,8 @@ CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
  * @return pointer to the first of the new instances
  * @return pointer to the first of the new instances
  *              0 on error
  *              0 on error
  */
  */
-CipInstance *AddCipInstances(CipClass *cip_object_to_add_instances,
-                             int number_of_instances);
+CipInstance *AddCipInstances(CipClass *restrict const cip_object_to_add_instances,
+                             const int number_of_instances);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Create one instance of a given class with a certain instance number
  * @brief Create one instance of a given class with a certain instance number
@@ -184,8 +184,8 @@ CipInstance *AddCipInstances(CipClass *cip_object_to_add_instances,
  *         already exists the existing is returned an no new instance is created
  *         already exists the existing is returned an no new instance is created
  *
  *
  */
  */
-CipInstance *AddCIPInstance(CipClass *cip_class_to_add_instance,
-                            EipUint32 pa_nInstanceId);
+CipInstance *AddCIPInstance(CipClass *restrict const cip_class_to_add_instance,
+                            const EipUint32 instance_id);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Insert an attribute in an instance of a CIP class
  * @brief Insert an attribute in an instance of a CIP class
@@ -200,8 +200,8 @@ CipInstance *AddCIPInstance(CipClass *cip_class_to_add_instance,
  *  @param cip_data pointer to data of attribute.
  *  @param cip_data pointer to data of attribute.
  *  @param cip_flags flags to indicate set-ability and get-ability of attribute.
  *  @param cip_flags flags to indicate set-ability and get-ability of attribute.
  */
  */
-void InsertAttribute(CipInstance *cip_instance, EipUint16 attribute_number,
-                     EipUint8 cip_data_type, void *cip_data, EipByte cip_flags);
+void InsertAttribute(CipInstance *const cip_instance, const EipUint16 attribute_number,
+                     const EipUint8 cip_data_type, void *const cip_data, const EipByte cip_flags);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Insert a service in an instance of a CIP object
  * @brief Insert a service in an instance of a CIP object
@@ -216,8 +216,8 @@ void InsertAttribute(CipInstance *cip_instance, EipUint16 attribute_number,
  * @param service_function pointer to function which represents the service.
  * @param service_function pointer to function which represents the service.
  * @param service_name name of the service
  * @param service_name name of the service
  */
  */
-void InsertService(CipClass *cip_class_to_add_service, EipUint8 service_code,
-                   CipServiceFunction service_function, char *service_name);
+void InsertService(const CipClass *const cip_class_to_add_service, const EipUint8 service_code,
+                   const CipServiceFunction service_function, char *const service_name);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Produce the data according to CIP encoding onto the message buffer.
  * @brief Produce the data according to CIP encoding onto the message buffer.
@@ -230,7 +230,7 @@ void InsertService(CipClass *cip_class_to_add_service, EipUint8 service_code,
  *  @return length of attribute in bytes
  *  @return length of attribute in bytes
  *          -1 .. error
  *          -1 .. error
  */
  */
-int EncodeData(EipUint8 cip_data_type, void *cip_data, EipUint8 **cip_message);
+int EncodeData(const EipUint8 cip_data_type, const void *const cip_data, EipUint8 **cip_message);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Retrieve the given data according to CIP encoding from the message
  * @brief Retrieve the given data according to CIP encoding from the message
@@ -244,7 +244,7 @@ int EncodeData(EipUint8 cip_data_type, void *cip_data, EipUint8 **cip_message);
  *  @return length of taken bytes
  *  @return length of taken bytes
  *          -1 .. error
  *          -1 .. error
  */
  */
-int DecodeData(EipUint8 cip_data_type, void *cip_data, EipUint8 **cip_message);
+int DecodeData(const EipUint8 cip_type, void *const data, const EipUint8 **const message);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Create an instance of an assembly object
  * @brief Create an instance of an assembly object
@@ -263,10 +263,10 @@ int DecodeData(EipUint8 cip_data_type, void *cip_data, EipUint8 **cip_message);
  * The notification on received configuration data is handled with the
  * The notification on received configuration data is handled with the
  * IApp_after_receive function.
  * IApp_after_receive function.
  */
  */
-CipInstance *CreateAssemblyObject(EipUint32 instance_number, EipByte *data,
-                                  EipUint16 data_length);
+CipInstance *CreateAssemblyObject(const EipUint32 instance_number, EipByte *const data,
+                                  const EipUint16 data_length);
 
 
-struct connection_object;
+typedef struct connection_object ConnectionObject;
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Function prototype for handling the opening of connections
  * @brief Function prototype for handling the opening of connections
@@ -278,7 +278,7 @@ struct connection_object;
  * @return CIP error code
  * @return CIP error code
  */
  */
 typedef EipStatus (*OpenConnectionFunction)(
 typedef EipStatus (*OpenConnectionFunction)(
-    struct connection_object *connection_object, EipUint16 *extended_error_code);
+    ConnectionObject *restrict const connection_object, EipUint16 *const extended_error_code);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Function prototype for handling the closing of connections
  * @brief Function prototype for handling the closing of connections
@@ -317,8 +317,8 @@ typedef EipStatus (*ConnectionSendDataFunction)(
  * @return Stack status
  * @return Stack status
  */
  */
 typedef EipStatus (*ConnectionReceiveDataFunction)(
 typedef EipStatus (*ConnectionReceiveDataFunction)(
-    struct connection_object *connection_object, EipUint8 *data,
-    EipUint16 data_length);
+    struct connection_object *connection_object, const EipUint8 *data,
+    const EipUint16 data_length);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief register open functions for an specific object.
  * @brief register open functions for an specific object.
@@ -348,8 +348,8 @@ AddConnectableObject(EipUint32 class_id,
  * this connection
  * this connection
  */
  */
 void ConfigureExclusiveOwnerConnectionPoint(
 void ConfigureExclusiveOwnerConnectionPoint(
-    unsigned int connection_number, unsigned int output_assembly_id,
-    unsigned int input_assembly_id, unsigned int configuration_assembly_id);
+    const unsigned int connection_number, const unsigned int output_assembly_id,
+    const unsigned int input_assembly_id, const unsigned int configuration_assembly_id);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Configures the connection point for an input only connection.
  * @brief Configures the connection point for an input only connection.
@@ -364,10 +364,10 @@ void ConfigureExclusiveOwnerConnectionPoint(
  * @param configuration_assembly_id ID of the configuration point to be used for
  * @param configuration_assembly_id ID of the configuration point to be used for
  *this connection
  *this connection
  */
  */
-void ConfigureInputOnlyConnectionPoint(unsigned int connection_number,
-                                       unsigned int output_assembly_id,
-                                       unsigned int input_assembly_id,
-                                       unsigned int configuration_assembly_id);
+void ConfigureInputOnlyConnectionPoint(const unsigned int connection_number,
+                                       const unsigned int output_assembly_id,
+                                       const unsigned int input_assembly_id,
+                                       const unsigned int configuration_assembly_id);
 
 
 /** \ingroup CIP_API
 /** \ingroup CIP_API
  * \brief Configures the connection point for a listen only connection.
  * \brief Configures the connection point for a listen only connection.
@@ -382,10 +382,10 @@ void ConfigureInputOnlyConnectionPoint(unsigned int connection_number,
  * @param configuration_assembly_id ID of the configuration point to be used for
  * @param configuration_assembly_id ID of the configuration point to be used for
  * this connection
  * this connection
  */
  */
-void ConfigureListenOnlyConnectionPoint(unsigned int connection_number,
-                                        unsigned int output_assembly_id,
-                                        unsigned int input_assembly_id,
-                                        unsigned int configuration_assembly_id);
+void ConfigureListenOnlyConnectionPoint(const unsigned int connection_number,
+                                        const unsigned int output_assembly_id,
+                                        const unsigned int input_assembly_id,
+                                        const unsigned int configuration_assembly_id);
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
  * @brief Notify the encapsulation layer that an explicit message has been
  * @brief Notify the encapsulation layer that an explicit message has been

+ 1 - 1
source/src/ports/POSIX/CMakeLists.txt

@@ -1,6 +1,6 @@
 add_subdirectory(sample_application)
 add_subdirectory(sample_application)
 
 
-set( PLATFORM_SPEC_SRC networkhandler.c)
+set( PLATFORM_SPEC_SRC networkhandler.c opener_error.c)
 
 
 #######################################
 #######################################
 # Add common includes                 #
 # Add common includes                 #

+ 31 - 0
source/src/ports/POSIX/opener_error.c

@@ -0,0 +1,31 @@
+/*******************************************************************************
+ * Copyright (c) 2009, Rockwell Automation, Inc.
+ * All rights reserved.
+ *
+ ******************************************************************************/
+
+/** @file opener_error.c
+ *  @author Martin Melik Merkumians
+ *  @brief This file includes the prototypes for error resolution functions like strerror or WSAGetLastError
+ *
+ */
+
+#include <errno.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "opener_error.h"
+
+const int error_message_buffer_size = 255;
+
+int GetSocketErrorNumber() {
+  return errno;
+}
+
+char *GetErrorMessage(int error_number) {
+  char *error_message = malloc(error_message_buffer_size);
+  strerror_r(error_number, error_message, error_message_buffer_size);
+  return error_message;
+}
+

+ 10 - 10
source/src/ports/POSIX/sample_application/sampleapplication.c

@@ -11,8 +11,8 @@
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
-#define DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM  152 //0x098
-#define DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM 153 //0x099
+#define DEMO_APP_HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM  152 //0x098
+#define DEMO_APP_HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM 153 //0x099
 #define DEMO_APP_EXPLICT_ASSEMBLY_NUM              154 //0x09A
 #define DEMO_APP_EXPLICT_ASSEMBLY_NUM              154 //0x09A
 
 
 /* global variables for demo application (4 assembly data fields)  ************/
 /* global variables for demo application (4 assembly data fields)  ************/
@@ -25,36 +25,36 @@ EipUint8 g_assembly_data09A[32]; /* Explicit */
 EipStatus ApplicationInitialization(void) {
 EipStatus ApplicationInitialization(void) {
   /* create 3 assembly object instances*/
   /* create 3 assembly object instances*/
   /*INPUT*/
   /*INPUT*/
-  CreateAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, &g_assembly_data064[0],
+  CreateAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, g_assembly_data064,
                        sizeof(g_assembly_data064));
                        sizeof(g_assembly_data064));
 
 
   /*OUTPUT*/
   /*OUTPUT*/
-  CreateAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, &g_assembly_data096[0],
+  CreateAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, g_assembly_data096,
                        sizeof(g_assembly_data096));
                        sizeof(g_assembly_data096));
 
 
   /*CONFIG*/
   /*CONFIG*/
-  CreateAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, &g_assembly_data097[0],
+  CreateAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, g_assembly_data097,
                        sizeof(g_assembly_data097));
                        sizeof(g_assembly_data097));
 
 
   /*Heart-beat output assembly for Input only connections */
   /*Heart-beat output assembly for Input only connections */
-  CreateAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM, NULL, 0);
 
 
   /*Heart-beat output assembly for Listen only connections */
   /*Heart-beat output assembly for Listen only connections */
-  CreateAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM, NULL, 0);
 
 
   /* assembly for explicit messaging */
   /* assembly for explicit messaging */
-  CreateAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assembly_data09A[0],
+  CreateAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, g_assembly_data09A,
                        sizeof(g_assembly_data09A));
                        sizeof(g_assembly_data09A));
 
 
   ConfigureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM,
   ConfigureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM,
   DEMO_APP_INPUT_ASSEMBLY_NUM,
   DEMO_APP_INPUT_ASSEMBLY_NUM,
                                          DEMO_APP_CONFIG_ASSEMBLY_NUM);
                                          DEMO_APP_CONFIG_ASSEMBLY_NUM);
   ConfigureInputOnlyConnectionPoint(0,
   ConfigureInputOnlyConnectionPoint(0,
-  DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM,
+  DEMO_APP_HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM,
                                     DEMO_APP_INPUT_ASSEMBLY_NUM,
                                     DEMO_APP_INPUT_ASSEMBLY_NUM,
                                     DEMO_APP_CONFIG_ASSEMBLY_NUM);
                                     DEMO_APP_CONFIG_ASSEMBLY_NUM);
   ConfigureListenOnlyConnectionPoint(0,
   ConfigureListenOnlyConnectionPoint(0,
-  DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM,
+  DEMO_APP_HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM,
                                      DEMO_APP_INPUT_ASSEMBLY_NUM,
                                      DEMO_APP_INPUT_ASSEMBLY_NUM,
                                      DEMO_APP_CONFIG_ASSEMBLY_NUM);
                                      DEMO_APP_CONFIG_ASSEMBLY_NUM);
 
 

+ 1 - 1
source/src/ports/WIN32/CMakeLists.txt

@@ -1,6 +1,6 @@
 add_subdirectory(sample_application)
 add_subdirectory(sample_application)
 
 
-set( PLATFORM_SPEC_SRC networkhandler.c)
+set( PLATFORM_SPEC_SRC networkhandler.c opener_error.c)
 
 
 #######################################
 #######################################
 # Add common includes                 #
 # Add common includes                 #

+ 26 - 0
source/src/ports/WIN32/opener_error.c

@@ -0,0 +1,26 @@
+/*******************************************************************************
+ * Copyright (c) 2009, Rockwell Automation, Inc.
+ * All rights reserved.
+ *
+ ******************************************************************************/
+
+/** @file opener_error.c
+ *  @author Martin Melik Merkumians
+ *  @brief This file includes the prototypes for error resolution functions like strerror or WSAGetLastError
+ *
+ */
+
+ #include <windows.h>
+
+ #include "opener_error.h"
+
+int GetSocketErrorNumber() {
+	return WSAGetLastError();
+}
+
+char *GetErrorMessage(int error_number) {
+  	char *error_message = NULL;
+  	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error_number, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+               &error_message, 0, NULL);
+  	return error_message;
+  }

+ 6 - 6
source/src/ports/WIN32/sample_application/sampleapplication.c

@@ -11,8 +11,8 @@
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
-#define DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM  152 //0x098
-#define DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM 153 //0x099
+#define DEMO_APP_HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM  152 //0x098
+#define DEMO_APP_HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM 153 //0x099
 #define DEMO_APP_EXPLICT_ASSEMBLY_NUM              154 //0x09A
 #define DEMO_APP_EXPLICT_ASSEMBLY_NUM              154 //0x09A
 
 
 /* global variables for demo application (4 assembly data fields)  ************/
 /* global variables for demo application (4 assembly data fields)  ************/
@@ -37,10 +37,10 @@ EipStatus ApplicationInitialization(void) {
                        sizeof(g_assembly_data097));
                        sizeof(g_assembly_data097));
 
 
   /*Heart-beat output assembly for Input only connections */
   /*Heart-beat output assembly for Input only connections */
-  CreateAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /*Heart-beat output assembly for Listen only connections */
   /*Heart-beat output assembly for Listen only connections */
-  CreateAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /* assembly for explicit messaging */
   /* assembly for explicit messaging */
   CreateAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assembly_data09A[0],
   CreateAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assembly_data09A[0],
@@ -50,11 +50,11 @@ EipStatus ApplicationInitialization(void) {
   DEMO_APP_INPUT_ASSEMBLY_NUM,
   DEMO_APP_INPUT_ASSEMBLY_NUM,
                                          DEMO_APP_CONFIG_ASSEMBLY_NUM);
                                          DEMO_APP_CONFIG_ASSEMBLY_NUM);
   ConfigureInputOnlyConnectionPoint(0,
   ConfigureInputOnlyConnectionPoint(0,
-  DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM,
+  DEMO_APP_HEARTBEAT_INPUT_ONLY_ASSEMBLY_NUM,
                                     DEMO_APP_INPUT_ASSEMBLY_NUM,
                                     DEMO_APP_INPUT_ASSEMBLY_NUM,
                                     DEMO_APP_CONFIG_ASSEMBLY_NUM);
                                     DEMO_APP_CONFIG_ASSEMBLY_NUM);
   ConfigureListenOnlyConnectionPoint(0,
   ConfigureListenOnlyConnectionPoint(0,
-  DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM,
+  DEMO_APP_HEARTBEAT_LISTEN_ONLY_ASSEMBLY_NUM,
                                      DEMO_APP_INPUT_ASSEMBLY_NUM,
                                      DEMO_APP_INPUT_ASSEMBLY_NUM,
                                      DEMO_APP_CONFIG_ASSEMBLY_NUM);
                                      DEMO_APP_CONFIG_ASSEMBLY_NUM);
 
 

+ 118 - 49
source/src/ports/generic_networkhandler.c

@@ -11,11 +11,13 @@
  *  The generic network handler delegates platform-dependent tasks to the platform network handler
  *  The generic network handler delegates platform-dependent tasks to the platform network handler
  */
  */
 
 
+#include <assert.h>
+
 #include "generic_networkhandler.h"
 #include "generic_networkhandler.h"
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 #include "trace.h"
 #include "trace.h"
-
+#include "opener_error.h"
 #include "encap.h"
 #include "encap.h"
 #include "ciptcpipinterface.h"
 #include "ciptcpipinterface.h"
 
 
@@ -29,7 +31,7 @@ void CheckAndHandleTcpListenerSocket(void);
  */
  */
 void CheckAndHandleUdpUnicastSocket(void);
 void CheckAndHandleUdpUnicastSocket(void);
 
 
-/** @brief TODO: FILL IN!
+/** @brief Checks and handles incoming messages via UDP broadcast
  *
  *
  */
  */
 void CheckAndHandleUdpGlobalBroadcastSocket(void);
 void CheckAndHandleUdpGlobalBroadcastSocket(void);
@@ -39,11 +41,17 @@ void CheckAndHandleUdpGlobalBroadcastSocket(void);
  */
  */
 void CheckAndHandleConsumingUdpSockets(void);
 void CheckAndHandleConsumingUdpSockets(void);
 
 
-/** @brief TODO: FILL IN!
+/** @brief Handles data on an established TCP connection, processed connection is given by socket
  *
  *
+ *  @param socket The socket to be processed
+ *  @return kEipStatusOk on success, or kEipStatusError on failure
  */
  */
 EipStatus HandleDataOnTcpSocket(int socket);
 EipStatus HandleDataOnTcpSocket(int socket);
 
 
+/*************************************************
+ * Function implementations from now on
+ *************************************************/
+
 EipStatus NetworkHandlerInitialize(void) {
 EipStatus NetworkHandlerInitialize(void) {
 
 
   if(kEipStatusOk != NetworkHandlerInitializePlatform()) {
   if(kEipStatusOk != NetworkHandlerInitializePlatform()) {
@@ -57,7 +65,10 @@ EipStatus NetworkHandlerInitialize(void) {
   /* create a new TCP socket */
   /* create a new TCP socket */
   if ((g_network_status.tcp_listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))
   if ((g_network_status.tcp_listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))
       == -1) {
       == -1) {
-    OPENER_TRACE_ERR("error allocating socket stream listener, %d\n", errno);
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("error allocating socket stream listener, %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
@@ -76,16 +87,22 @@ EipStatus NetworkHandlerInitialize(void) {
                                                                SOCK_DGRAM,
                                                                SOCK_DGRAM,
                                                                IPPROTO_UDP))
                                                                IPPROTO_UDP))
       == -1) {
       == -1) {
-    OPENER_TRACE_ERR("error allocating UDP global broadcast listener socket, %d\n",
-                     errno);
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("error allocating UDP global broadcast listener socket, %d - %s\n",
+                     error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
   /* create a new UDP socket */
   /* create a new UDP socket */
   if ((g_network_status.udp_unicast_listener = socket(AF_INET, SOCK_DGRAM,
   if ((g_network_status.udp_unicast_listener = socket(AF_INET, SOCK_DGRAM,
                                                       IPPROTO_UDP)) == -1) {
                                                       IPPROTO_UDP)) == -1) {
-    OPENER_TRACE_ERR("error allocating UDP unicast listener socket, %d\n",
-                     errno);
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("error allocating UDP unicast listener socket, %d - %s\n",
+		error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
@@ -114,13 +131,19 @@ EipStatus NetworkHandlerInitialize(void) {
   /* bind the new socket to port 0xAF12 (CIP) */
   /* bind the new socket to port 0xAF12 (CIP) */
   if ((bind(g_network_status.tcp_listener, (struct sockaddr *) &my_address,
   if ((bind(g_network_status.tcp_listener, (struct sockaddr *) &my_address,
             sizeof(struct sockaddr))) == -1) {
             sizeof(struct sockaddr))) == -1) {
-    OPENER_TRACE_ERR("error with TCP bind: %s\n", strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("error with TCP bind: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
   if ((bind(g_network_status.udp_unicast_listener,
   if ((bind(g_network_status.udp_unicast_listener,
             (struct sockaddr *) &my_address, sizeof(struct sockaddr))) == -1) {
             (struct sockaddr *) &my_address, sizeof(struct sockaddr))) == -1) {
-    OPENER_TRACE_ERR("error with UDP unicast bind: %s\n", strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("error with UDP unicast bind: %d - %s\n", error_code, GetErrorMessage(error_code));
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
@@ -131,23 +154,31 @@ EipStatus NetworkHandlerInitialize(void) {
    if (0
    if (0
        > setsockopt(g_network_status.udp_global_broadcast_listener, SOL_SOCKET, SO_BROADCAST,
        > setsockopt(g_network_status.udp_global_broadcast_listener, SOL_SOCKET, SO_BROADCAST,
                     (char *) &set_socket_option_value, sizeof(int))) {
                     (char *) &set_socket_option_value, sizeof(int))) {
+	 int error_code = GetSocketErrorNumber();
+	 char* error_message = GetErrorMessage(error_code);
      OPENER_TRACE_ERR(
      OPENER_TRACE_ERR(
-         "error with setting broadcast receive for UDP socket: %s\n",
-         strerror(errno));
+         "error with setting broadcast receive for UDP socket: %d - %s\n",
+         error_code, error_message);
+	 free(error_message);
      return kEipStatusError;
      return kEipStatusError;
    }
    }
 
 
   if ((bind(g_network_status.udp_global_broadcast_listener,
   if ((bind(g_network_status.udp_global_broadcast_listener,
             (struct sockaddr *) &global_broadcast_address,
             (struct sockaddr *) &global_broadcast_address,
             sizeof(struct sockaddr))) == -1) {
             sizeof(struct sockaddr))) == -1) {
-    OPENER_TRACE_ERR("error with global broadcast UDP bind: %s\n", strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("error with global broadcast UDP bind: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
   /* switch socket in listen mode */
   /* switch socket in listen mode */
   if ((listen(g_network_status.tcp_listener, MAX_NO_OF_TCP_SOCKETS)) == -1) {
   if ((listen(g_network_status.tcp_listener, MAX_NO_OF_TCP_SOCKETS)) == -1) {
-    OPENER_TRACE_ERR("networkhandler: error with listen: %s\n",
-                     strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("networkhandler: error with listen: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
@@ -199,8 +230,11 @@ void CheckAndHandleTcpListenerSocket(void) {
 
 
     new_socket = accept(g_network_status.tcp_listener, NULL, NULL);
     new_socket = accept(g_network_status.tcp_listener, NULL, NULL);
     if (new_socket == -1) {
     if (new_socket == -1) {
-      OPENER_TRACE_ERR("networkhandler: error on accept: %s\n",
-                       strerror(errno));
+	  int error_code = GetSocketErrorNumber();
+	  char* error_message = GetErrorMessage(error_code);
+      OPENER_TRACE_ERR("networkhandler: error on accept: %d - %s\n",
+                       error_code, error_message);
+	  free(error_message);
       return;
       return;
     }
     }
 
 
@@ -233,8 +267,10 @@ EipStatus NetworkHandlerProcessOnce(void) {
     {
     {
       return kEipStatusOk;
       return kEipStatusOk;
     } else {
     } else {
-      OPENER_TRACE_ERR("networkhandler: error with select: %s\n",
-                       strerror(errno));
+	  int error_code = GetSocketErrorNumber();
+	  char* error_message = GetErrorMessage(error_code);
+      OPENER_TRACE_ERR("networkhandler: error with select: %d - %s\n", error_code, error_message);
+	  free(error_message);
       return kEipStatusError;
       return kEipStatusError;
     }
     }
   }
   }
@@ -301,9 +337,11 @@ void CheckAndHandleUdpGlobalBroadcastSocket(void) {
                                  &from_address_length);
                                  &from_address_length);
 
 
     if (received_size <= 0) { /* got error */
     if (received_size <= 0) { /* got error */
+	  int error_code = GetSocketErrorNumber();
+	  char* error_message = GetErrorMessage(error_code);
       OPENER_TRACE_ERR(
       OPENER_TRACE_ERR(
-          "networkhandler: error on recvfrom UDP global broadcast port: %s\n",
-          strerror(errno));
+          "networkhandler: error on recvfrom UDP global broadcast port: %d - %s\n", error_code, error_message);
+	  free(error_message);
       return;
       return;
     }
     }
 
 
@@ -356,9 +394,11 @@ void CheckAndHandleUdpUnicastSocket(void) {
                                  &from_address_length);
                                  &from_address_length);
 
 
     if (received_size <= 0) { /* got error */
     if (received_size <= 0) { /* got error */
-      OPENER_TRACE_ERR(
-          "networkhandler: error on recvfrom UDP unicast port: %s\n",
-          strerror(errno));
+	  int error_code = GetSocketErrorNumber();
+	  char* error_message = GetErrorMessage(error_code);
+	  OPENER_TRACE_ERR(
+		  "networkhandler: error on recvfrom UDP unicast port: %d - %s\n", error_code, error_message);
+	  free(error_message);
       return;
       return;
     }
     }
 
 
@@ -397,8 +437,10 @@ EipStatus SendUdpData(struct sockaddr_in *address, int socket, EipUint8 *data,
                            (struct sockaddr *) address, sizeof(*address));
                            (struct sockaddr *) address, sizeof(*address));
 
 
   if (sent_length < 0) {
   if (sent_length < 0) {
-    OPENER_TRACE_ERR("networkhandler: error with sendto in sendUDPData: %s\n",
-                     strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+	OPENER_TRACE_ERR("networkhandler: error with sendto in sendUDPData: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
@@ -427,16 +469,21 @@ EipStatus HandleDataOnTcpSocket(int socket) {
                                    0); /*TODO we may have to set the socket to a non blocking socket */
                                    0); /*TODO we may have to set the socket to a non blocking socket */
 
 
   if (number_of_read_bytes == 0) {
   if (number_of_read_bytes == 0) {
-    OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
-                     strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+	OPENER_TRACE_ERR("networkhandler: connection closed by client: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
   if (number_of_read_bytes < 0) {
   if (number_of_read_bytes < 0) {
-    OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+    OPENER_TRACE_ERR("networkhandler: error on recv: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
-  EipUint8 *read_buffer = &g_ethernet_communication_buffer[2]; /* at this place EIP stores the data length */
+  const EipUint8 *read_buffer = &g_ethernet_communication_buffer[2]; /* at this place EIP stores the data length */
   size_t data_size = GetIntFromMessage(&read_buffer)
   size_t data_size = GetIntFromMessage(&read_buffer)
       + ENCAPSULATION_HEADER_LENGTH - 4; /* -4 is for the 4 bytes we have already read*/
       + ENCAPSULATION_HEADER_LENGTH - 4; /* -4 is for the 4 bytes we have already read*/
   /* (NOTE this advances the buffer pointer) */
   /* (NOTE this advances the buffer pointer) */
@@ -451,20 +498,25 @@ EipStatus HandleDataOnTcpSocket(int socket) {
 
 
       if (number_of_read_bytes == 0) /* got error or connection closed by client */
       if (number_of_read_bytes == 0) /* got error or connection closed by client */
       {
       {
-        OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
-                         strerror(errno));
+		int error_code = GetSocketErrorNumber();
+		char* error_message = GetErrorMessage(error_code);
+		OPENER_TRACE_ERR("networkhandler: connection closed by client: %d - %s\n", error_code, error_message);
+		free(error_message);
         return kEipStatusError;
         return kEipStatusError;
       }
       }
       if (number_of_read_bytes < 0) {
       if (number_of_read_bytes < 0) {
-        OPENER_TRACE_ERR("networkhandler: error on recv: %s\n",
-                         strerror(errno));
+		int error_code = GetSocketErrorNumber();
+		char* error_message = GetErrorMessage(error_code);
+		OPENER_TRACE_ERR("networkhandler: error on recv: %d - %s\n", error_code, error_message);
+		free(error_message);
         return kEipStatusError;
         return kEipStatusError;
       }
       }
       data_size -= number_of_read_bytes;
       data_size -= number_of_read_bytes;
       if ((data_size < PC_OPENER_ETHERNET_BUFFER_SIZE) && (data_size != 0)) {
       if ((data_size < PC_OPENER_ETHERNET_BUFFER_SIZE) && (data_size != 0)) {
         data_sent = data_size;
         data_sent = data_size;
       }
       }
-    } while (0 != data_size); /* TODO: fragile end statement */
+    } while (0 < data_size);
+    assert(0 <= data_size);
     return kEipStatusOk;
     return kEipStatusOk;
   }
   }
 
 
@@ -473,12 +525,17 @@ EipStatus HandleDataOnTcpSocket(int socket) {
 
 
   if (number_of_read_bytes == 0) /* got error or connection closed by client */
   if (number_of_read_bytes == 0) /* got error or connection closed by client */
   {
   {
-    OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
-                     strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+	OPENER_TRACE_ERR("networkhandler: connection closed by client: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
   if (number_of_read_bytes < 0) {
   if (number_of_read_bytes < 0) {
-    OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+	OPENER_TRACE_ERR("networkhandler: error on recv: %d - %s\n", error_code, error_message);
+	free(error_message);
     return kEipStatusError;
     return kEipStatusError;
   }
   }
 
 
@@ -539,8 +596,10 @@ int CreateUdpSocket(UdpCommuncationDirection communication_direction,
   peer_address_length = sizeof(struct sockaddr_in);
   peer_address_length = sizeof(struct sockaddr_in);
   /* create a new UDP socket */
   /* create a new UDP socket */
   if ((new_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
   if ((new_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
-    OPENER_TRACE_ERR("networkhandler: cannot create UDP socket: %s\n",
-                     strerror(errno));
+	int error_code = GetSocketErrorNumber();
+	char* error_message = GetErrorMessage(error_code);
+	OPENER_TRACE_ERR("networkhandler: cannot create UDP socket: %d- %s\n", error_code, error_message);
+	free(error_message);
     return kEipInvalidSocket;
     return kEipInvalidSocket;
   }
   }
 
 
@@ -559,7 +618,10 @@ int CreateUdpSocket(UdpCommuncationDirection communication_direction,
     /* bind is only for consuming necessary */
     /* bind is only for consuming necessary */
     if ((bind(new_socket, (struct sockaddr *) socket_data,
     if ((bind(new_socket, (struct sockaddr *) socket_data,
               sizeof(struct sockaddr))) == -1) {
               sizeof(struct sockaddr))) == -1) {
-      OPENER_TRACE_ERR("error on bind udp: %s\n", strerror(errno));
+		int error_code = GetSocketErrorNumber();
+		char* error_message = GetErrorMessage(error_code);
+		OPENER_TRACE_ERR("error on bind udp: %d - %s\n", error_code, error_message);
+		free(error_message);
       return kEipInvalidSocket;
       return kEipInvalidSocket;
     }
     }
 
 
@@ -571,10 +633,13 @@ int CreateUdpSocket(UdpCommuncationDirection communication_direction,
       if (1 != g_time_to_live_value) { /* we need to set a TTL value for the socket */
       if (1 != g_time_to_live_value) { /* we need to set a TTL value for the socket */
         if (setsockopt(new_socket, IPPROTO_IP, IP_MULTICAST_TTL,
         if (setsockopt(new_socket, IPPROTO_IP, IP_MULTICAST_TTL,
                        &g_time_to_live_value,
                        &g_time_to_live_value,
-                       sizeof(g_time_to_live_value)) < 0) {
-          OPENER_TRACE_ERR(
-              "networkhandler: could not set the TTL to: %d, error: %s\n",
-              g_time_to_live_value, strerror(errno));
+                       sizeof(g_time_to_live_value) < 0)) {
+			int error_code = GetSocketErrorNumber();
+			char* error_message = GetErrorMessage(error_code);
+			OPENER_TRACE_ERR(
+				"networkhandler: could not set the TTL to: %d, error: %d - %s\n",
+				g_time_to_live_value, error_code, error_message);
+			free(error_message);
           return kEipInvalidSocket;
           return kEipInvalidSocket;
         }
         }
       }
       }
@@ -587,8 +652,10 @@ int CreateUdpSocket(UdpCommuncationDirection communication_direction,
     if (getpeername(g_current_active_tcp_socket,
     if (getpeername(g_current_active_tcp_socket,
                     (struct sockaddr *) &peer_address, &peer_address_length)
                     (struct sockaddr *) &peer_address, &peer_address_length)
         < 0) {
         < 0) {
-      OPENER_TRACE_ERR("networkhandler: could not get peername: %s\n",
-                       strerror(errno));
+		int error_code = GetSocketErrorNumber();
+		char* error_message = GetErrorMessage(error_code);
+		OPENER_TRACE_ERR("networkhandler: could not get peername: %d - %s\n", error_code, error_message);
+		free(error_message);
       return kEipInvalidSocket;
       return kEipInvalidSocket;
     }
     }
     /* store the originators address */
     /* store the originators address */
@@ -634,8 +701,10 @@ void CheckAndHandleConsumingUdpSockets(void) {
       }
       }
 
 
       if (0 > received_size) {
       if (0 > received_size) {
-        OPENER_TRACE_ERR("networkhandler: error on recv: %s\n",
-                         strerror(errno));
+		int error_code = GetSocketErrorNumber();
+		char* error_message = GetErrorMessage(error_code);
+		OPENER_TRACE_ERR("networkhandler: error on recv: %d - %s\n", error_code, error_message);
+		free(error_message);
         current_connection_object->connection_close_function(
         current_connection_object->connection_close_function(
             current_connection_object);
             current_connection_object);
         continue;
         continue;

+ 32 - 0
source/src/ports/opener_error.h

@@ -0,0 +1,32 @@
+/*******************************************************************************
+ * Copyright (c) 2009, Rockwell Automation, Inc.
+ * All rights reserved.
+ *
+ ******************************************************************************/
+
+/** @file opener_error.h
+ *  @author Martin Melik Merkumians
+ *  @brief This file includes the prototypes for error resolution functions like strerror_r or WSAGetLastError
+ *
+ */
+
+/**
+ * @brief Gets the error number or equivalent
+ *
+ * A delegate which implements how to get the error number from the system
+ *
+ * @return Error number
+ */
+int GetSocketErrorNumber();
+
+
+/**
+ * @brief Returns a human readable message for the given error number
+ *
+ * Returns a human readable error message to be used in logs and traces.
+ * The error message shall not be a shared memory, like the classic strerror function, as such functions are non-reentrant
+ * The user of this function is responsible to free the space in which the error message is returned
+ *
+ * @return A human readable error message for the given error number
+ */
+char *GetErrorMessage(int error_number);

+ 25 - 12
source/tests/enet_encap/endianconvtest.cpp

@@ -22,31 +22,44 @@ TEST_GROUP(EndianConversion) {
 
 
 };
 };
 
 
+TEST(EndianConversion, GetSintFromMessage) {
+  const EipUint8 test_message[] = { 8 };
+  const EipUint8 *message_pointer = test_message;
+  const EipUint8 **const message = &message_pointer;
+  EipUint16 returned_value = GetSintFromMessage(message);
+
+  LONGS_EQUAL(8, returned_value);
+  POINTERS_EQUAL(test_message + 1, *message);
+}
+
 TEST(EndianConversion, GetIntFromMessage) {
 TEST(EndianConversion, GetIntFromMessage) {
-  CipOctet test_message[] = { 8, 60 };
-  CipOctet *message = test_message;
-  EipUint16 returned_value = GetIntFromMessage(&message);
+  const EipUint8 test_message[] = { 8, 60 };
+  const EipUint8 *message_pointer = test_message;
+  const EipUint8 **const message = &message_pointer;
+  EipUint16 returned_value = GetIntFromMessage(message);
 
 
   LONGS_EQUAL(15368, returned_value);
   LONGS_EQUAL(15368, returned_value);
-  POINTERS_EQUAL(test_message + 2, message);
+  POINTERS_EQUAL(test_message + 2, *message);
 }
 }
 
 
 TEST(EndianConversion, GetDintFromMessage) {
 TEST(EndianConversion, GetDintFromMessage) {
-  CipOctet test_message[] = { 28, 53, 41, 37 };
-  CipOctet *message = test_message;
-  EipUint32 returned_value = GetDintFromMessage(&message);
+  const EipUint8 test_message[] = { 28, 53, 41, 37 };
+  const EipUint8 *message_pointer = test_message;
+  const EipUint8 **const message = &message_pointer;
+  EipUint32 returned_value = GetDintFromMessage(message);
 
 
   LONGS_EQUAL(623457564, returned_value);
   LONGS_EQUAL(623457564, returned_value);
-  POINTERS_EQUAL(test_message + 4, message);
+  POINTERS_EQUAL(test_message + 4, *message);
 }
 }
 
 
 TEST(EndianConversion, GetLintFromMessage) {
 TEST(EndianConversion, GetLintFromMessage) {
-  CipOctet test_message[] = { 81, 126, 166, 15, 70, 97, 208, 236 };
-  CipOctet *message = test_message;
-  EipUint64 returned_value = GetLintFromMessage(&message);
+  const EipUint8 test_message[] = { 81, 126, 166, 15, 70, 97, 208, 236 };
+  const EipUint8 *message_pointer = test_message;
+  const EipUint8 **const message = &message_pointer;
+  EipUint64 returned_value = GetLintFromMessage(message);
 
 
   LONGS_EQUAL(5872313548673241324, returned_value);
   LONGS_EQUAL(5872313548673241324, returned_value);
-  POINTERS_EQUAL(test_message + 8, message);
+  POINTERS_EQUAL(test_message + 8, *message);
 }
 }
 
 
 TEST(EndianConversion, AddIntToMessage) {
 TEST(EndianConversion, AddIntToMessage) {