Kaynağa Gözat

Merge remote-tracking branch 'EIPStackGroup_OpENer/master'

micsat 5 yıl önce
ebeveyn
işleme
1eff329028

+ 160 - 159
source/src/cip/cipcommon.c

@@ -86,10 +86,11 @@ EipStatus NotifyClass(const CipClass *RESTRICT const cip_class,
   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 */
   {
-    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)" : "");
 
-    CipServiceStruct *service = instance->cip_class->services;             /* get pointer to array of services */
+    CipServiceStruct *service = instance->cip_class->services;         /* get pointer to array of services */
     if (NULL != service)             /* if services are defined */
     {
       for (size_t i = 0; i < instance->cip_class->number_of_services; i++)                   /* seach the services list */
@@ -97,8 +98,7 @@ EipStatus NotifyClass(const CipClass *RESTRICT const cip_class,
         if (message_router_request->service == service->service_number)                         /* if match is found */
         {
           /* call the service, and return what it returns */
-          OPENER_TRACE_INFO("notify: calling %s service\n",
-                            service->name);
+          OPENER_TRACE_INFO("notify: calling %s service\n", service->name);
           OPENER_ASSERT(NULL != service->service_function);
           return service->service_function(instance,
                                            message_router_request,
@@ -110,13 +110,12 @@ EipStatus NotifyClass(const CipClass *RESTRICT const cip_class,
         }
       }
     }
-    OPENER_TRACE_WARN("notify: service 0x%x not supported\n",
-                      message_router_request->service);
-    message_router_response->general_status = kCipErrorServiceNotSupported;             /* if no services or service not found, return an error reply*/
+    OPENER_TRACE_WARN(
+      "notify: service 0x%x not supported\n", message_router_request->service);
+    message_router_response->general_status = kCipErrorServiceNotSupported;                                                                                    /* if no services or service not found, return an error reply*/
   } else {
-    OPENER_TRACE_WARN("notify: instance number %d unknown\n",
-                      instance_number);
-    /* if instance not found, return an error reply */
+    OPENER_TRACE_WARN("notify: instance number %d unknown\n", instance_number);
+/* if instance not found, return an error reply */
     message_router_response->general_status =
       kCipErrorPathDestinationUnknown;
     /* according to the test tool this is the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST */
@@ -138,10 +137,11 @@ CipInstance *AddCipInstances(CipClass *RESTRICT const cip_class,
   EipUint32 instance_number = 1;      /* the first instance is number 1 */
   int new_instances   = 0;
 
-  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);
 
-  next_instance = &cip_class->instances;       /* get address of pointer to head of chain */
+  next_instance = &cip_class->instances;     /* get address of pointer to head of chain */
   while (*next_instance)       /* as long as what pp points to is not zero */
   {
     next_instance = &(*next_instance)->next;              /* follow the chain until pp points to pointer that contains a zero */
@@ -153,7 +153,7 @@ CipInstance *AddCipInstances(CipClass *RESTRICT const cip_class,
   {
     CipInstance *current_instance =
       (CipInstance *) CipCalloc(1, sizeof(CipInstance) );
-    OPENER_ASSERT(NULL != current_instance);              /* fail if run out of memory */
+    OPENER_ASSERT(NULL != current_instance); /* fail if run out of memory */
     if (NULL == current_instance) {break;}
     if (NULL == first_instance)
     {
@@ -185,7 +185,7 @@ CipInstance *AddCipInstances(CipClass *RESTRICT const cip_class,
       new_instances,
       number_of_instances,
       cip_class->class_name);
-    first_instance = NULL;  /* failed to allocate all instances / attributes */
+    first_instance = NULL; /* failed to allocate all instances / attributes */
   }
   return first_instance;
 }
@@ -194,7 +194,7 @@ CipInstance *AddCipInstance(CipClass *RESTRICT const cip_class,
                             const EipUint32 instance_id) {
   CipInstance *instance = GetCipInstance(cip_class, instance_id);
 
-  if (NULL == instance) {       /*we have no instance with given id*/
+  if (NULL == instance) { /*we have no instance with given id*/
     instance = AddCipInstances(cip_class, 1);
     instance->instance_number = instance_id;
   }
@@ -217,96 +217,98 @@ CipClass *CreateCipClass(const CipUdint class_code,
                     class_code);
 
   OPENER_ASSERT(NULL == GetCipClass(class_code) ); /* 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
-     CIP can talk to an instance, therefore an instance has a pointer to its class
-     CIP can talk to a class, therefore a class struct is a subclass of the instance struct,
-     and contains a pointer to a metaclass
-     CIP never explicitly addresses a metaclass*/
+/* a metaClass is a class that holds the class attributes and services
+   CIP can talk to an instance, therefore an instance has a pointer to its class
+   CIP can talk to a class, therefore a class struct is a subclass of the instance struct,
+   and contains a pointer to a metaclass
+   CIP never explicitly addresses a metaclass*/
 
-  CipClass *const cip_class = (CipClass *) CipCalloc(1, sizeof(CipClass) );        /* create the class object*/
-  CipClass *const meta_class = (CipClass *) CipCalloc(1, sizeof(CipClass) );       /* create the metaclass object*/
+  CipClass *const cip_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*/
-  cip_class->class_code = class_code;       /* the class remembers the class ID */
-  cip_class->revision = revision;       /* the class remembers the class ID */
-  cip_class->number_of_instances = 0;       /* the number of instances initially zero (more created below) */
+/* initialize the class-specific fields of the Class struct*/
+  cip_class->class_code = class_code; /* the class remembers the class ID */
+  cip_class->revision = revision; /* the class remembers the class ID */
+  cip_class->number_of_instances = 0; /* the number of instances initially zero (more created below) */
   cip_class->instances = 0;
-  cip_class->number_of_attributes = number_of_instance_attributes;       /* the class remembers the number of instances of that class */
-  cip_class->highest_attribute_number = highest_instance_attribute_number;       /* indicate which attributes are included in instance getAttributeAll */
-  cip_class->number_of_services = number_of_instance_services;       /* the class manages the behavior of the instances */
+  cip_class->number_of_attributes = number_of_instance_attributes; /* the class remembers the number of instances of that class */
+  cip_class->highest_attribute_number = highest_instance_attribute_number; /* indicate which attributes are included in instance getAttributeAll */
+  cip_class->number_of_services = number_of_instance_services; /* the class manages the behavior of the instances */
   cip_class->services = 0;
-  cip_class->class_name = name;       /* initialize the class-specific fields of the metaClass struct */
-  meta_class->class_code = 0xffffffff;       /* set metaclass ID (this should never be referenced) */
-  meta_class->number_of_instances = 1;       /* the class object is the only instance of the metaclass */
+  cip_class->class_name = name; /* initialize the class-specific fields of the metaClass struct */
+  meta_class->class_code = 0xffffffff; /* set metaclass ID (this should never be referenced) */
+  meta_class->number_of_instances = 1; /* the class object is the only instance of the metaclass */
   meta_class->instances = (CipInstance *) cip_class;
-  meta_class->number_of_attributes = number_of_class_attributes + 7;      /* the metaclass remembers how many class attributes exist*/
-  meta_class->highest_attribute_number = highest_class_attribute_number;  /* indicate which attributes are included in class getAttributeAll*/
-  meta_class->number_of_services = number_of_class_services;              /* the metaclass manages the behavior of the class itself */
-  meta_class->class_name = (char *) CipCalloc(1, strlen(name) + 6);       /* fabricate the name "meta<classname>"*/
+  meta_class->number_of_attributes = number_of_class_attributes + 7; /* the metaclass remembers how many class attributes exist*/
+  meta_class->highest_attribute_number = highest_class_attribute_number; /* indicate which attributes are included in class getAttributeAll*/
+  meta_class->number_of_services = number_of_class_services; /* the metaclass manages the behavior of the class itself */
+  meta_class->class_name = (char *) CipCalloc(1, strlen(name) + 6); /* fabricate the name "meta<classname>"*/
   snprintf(meta_class->class_name, strlen(name) + 6, "meta-%s", name);
 
-  /* initialize the instance-specific fields of the Class struct*/
-  cip_class->class_instance.instance_number = 0;    /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
-  cip_class->class_instance.attributes = 0;         /* this will later point to the class attibutes*/
+/* initialize the instance-specific fields of the Class struct*/
+  cip_class->class_instance.instance_number = 0; /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
+  cip_class->class_instance.attributes = 0; /* this will later point to the class attibutes*/
   cip_class->class_instance.cip_class = meta_class; /* the class's class is the metaclass (like SmallTalk)*/
-  cip_class->class_instance.next = 0;       /* the next link will always be zero, since there is only one instance of any particular class object */
+  cip_class->class_instance.next = 0; /* the next link will always be zero, since there is only one instance of any particular class object */
 
-  meta_class->class_instance.instance_number = 0xffffffff;  /*the metaclass object does not really have a valid instance number*/
+  meta_class->class_instance.instance_number = 0xffffffff; /*the metaclass object does not really have a valid instance number*/
   meta_class->class_instance.attributes = NULL;/* the metaclass has no attributes*/
   meta_class->class_instance.cip_class = NULL; /* the metaclass has no class*/
-  meta_class->class_instance.next = NULL;      /* the next link will always be zero, since there is only one instance of any particular metaclass object*/
+  meta_class->class_instance.next = NULL; /* 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*/
 
   cip_class->class_instance.attributes = (CipAttributeStruct *) CipCalloc(
-    meta_class->number_of_attributes, sizeof(CipAttributeStruct) );
-  /* TODO -- check that we didn't run out of memory?*/
+    meta_class->number_of_attributes,
+    sizeof(CipAttributeStruct) );
+/* TODO -- check that we didn't run out of memory?*/
 
   meta_class->services = (CipServiceStruct *) CipCalloc(
-    meta_class->number_of_services, sizeof(CipServiceStruct) );
+    meta_class->number_of_services,
+    sizeof(CipServiceStruct) );
 
   cip_class->services = (CipServiceStruct *) CipCalloc(
     cip_class->number_of_services,
     sizeof(CipServiceStruct) );
 
-  if (number_of_instances > 0) {
-    AddCipInstances(cip_class, number_of_instances);  /*TODO handle return value and clean up if necessary*/
+  if(number_of_instances > 0) {
+    AddCipInstances(cip_class, number_of_instances); /*TODO handle return value and clean up if necessary*/
   }
 
-  if (RegisterCipClass(cip_class) == kEipStatusError) {/* no memory to register class in Message Router */
-    return 0;             /*TODO handle return value and clean up if necessary*/
+  if(RegisterCipClass(cip_class) == kEipStatusError) {/* no memory to register class in Message Router */
+    return 0; /*TODO handle return value and clean up if necessary*/
   }
 
   AllocateAttributeMasks(meta_class); /* Allocation of bitmasks for Class Attributes */
-  AllocateAttributeMasks(cip_class);  /* Allocation of bitmasks for Instance Attributes */
+  AllocateAttributeMasks(cip_class); /* Allocation of bitmasks for Instance Attributes */
 
-  if (NULL == initializer) {
+  if(NULL == initializer) {
     InsertAttribute( (CipInstance *) cip_class, 1, kCipUint, EncodeCipUint,
-                     (void *) &cip_class->revision, kGetableSingleAndAll ); /* revision */
+                     (void *) &cip_class->revision, kGetableSingleAndAll );                                                /* revision */
     InsertAttribute( (CipInstance *) cip_class, 2, kCipUint, EncodeCipUint,
                      (void *) &cip_class->number_of_instances,
-                     kGetableSingleAndAll );                        /* #2 Max instance no. */
+                     kGetableSingleAndAll );                                                                                          /* #2 Max instance no. */
     InsertAttribute( (CipInstance *) cip_class, 3, kCipUint, EncodeCipUint,
                      (void *) &cip_class->number_of_instances,
-                     kGetableSingleAndAll );                        /* number of instances currently existing*/
+                     kGetableSingleAndAll );                                                                                          /* number of instances currently existing*/
     InsertAttribute( (CipInstance *) cip_class, 4, kCipUint, EncodeCipUint,
-                     (void *) &kCipUintZero, kGetableAllDummy );         /* optional attribute list - default = 0 */
+                     (void *) &kCipUintZero, kGetableAllDummy );                                                /* optional attribute list - default = 0 */
     InsertAttribute( (CipInstance *) cip_class, 5, kCipUint, EncodeCipUint,
-                     (void *) &kCipUintZero, kNotSetOrGetable );    /* optional service list - default = 0 */
+                     (void *) &kCipUintZero, kNotSetOrGetable );                                                /* optional service list - default = 0 */
     InsertAttribute( (CipInstance *) cip_class, 6, kCipUint, EncodeCipUint,
                      (void *) &meta_class->highest_attribute_number,
-                     kGetableSingle );                              /* max class attribute number*/
+                     kGetableSingle );                                                                                                /* max class attribute number*/
     InsertAttribute( (CipInstance *) cip_class, 7, kCipUint, EncodeCipUint,
                      (void *) &cip_class->highest_attribute_number,
-                     kGetableSingle );                              /* max instance attribute number*/
-    if (number_of_class_services > 0) {
-      if (number_of_class_services > 1) {                 /*only if the mask has values add the get_attribute_all service */
+                     kGetableSingle );                                                                                               /* max instance attribute number*/
+    if(number_of_class_services > 0) {
+      if(number_of_class_services > 1) { /*only if the mask has values add the get_attribute_all service */
         InsertService(meta_class,
                       kGetAttributeAll,
                       &GetAttributeAll,
-                      "GetAttributeAll");                                                                         /* bind instance services to the metaclass*/
+                      "GetAttributeAll");                                             /* bind instance services to the metaclass*/
       }
       InsertService(meta_class,
                     kGetAttributeSingle,
@@ -317,7 +319,7 @@ CipClass *CreateCipClass(const CipUdint class_code,
     initializer(cip_class);
   }
 
-  /* create the standard class services*/
+/* create the standard class services*/
   return cip_class;
 }
 
@@ -335,9 +337,9 @@ void InsertAttribute(CipInstance *const instance,
   CipClass *cip_class = instance->cip_class;
 
   OPENER_ASSERT(NULL != attribute);
-  /* adding a attribute to a class that was not declared to have any attributes is not allowed */
-  for (int i = 0; i < instance->cip_class->number_of_attributes; i++) {
-    if (attribute->data == NULL) {             /* found non set attribute */
+/* adding a attribute to a class that was not declared to have any attributes is not allowed */
+  for(int i = 0; i < instance->cip_class->number_of_attributes; i++) {
+    if(attribute->data == NULL) { /* found non set attribute */
       attribute->attribute_number = attribute_number;
       attribute->type = cip_type;
       attribute->encode = encode_function;
@@ -349,25 +351,23 @@ void InsertAttribute(CipInstance *const instance,
       size_t index = CalculateIndex(attribute_number);
 
       cip_class->get_single_bit_mask[index] |=
-        (cip_flags & kGetableSingle) ?
-        1 << (attribute_number) % 8 : 0;
+        (cip_flags & kGetableSingle) ? 1 << (attribute_number) % 8 : 0;
       cip_class->get_all_bit_mask[index] |=
         (cip_flags & (kGetableAll | kGetableAllDummy) ) ? 1 <<
         (attribute_number) % 8 : 0;
-      cip_class->set_bit_mask[index] |=
-        ( (cip_flags & kSetable) ? 1 : 0 ) << ( (attribute_number) % 8 );
+      cip_class->set_bit_mask[index] |= ( (cip_flags & kSetable) ? 1 : 0 ) <<
+                                        ( (attribute_number) % 8 );
 
       return;
     }
     attribute++;
-  }
-  OPENER_TRACE_ERR(
+  } OPENER_TRACE_ERR(
     "Tried to insert too many attributes into class: %" PRIu32 " '%s', instance %" PRIu32 "\n",
     cip_class->class_code,
     cip_class->class_name,
     instance->instance_number);
   OPENER_ASSERT(false);
-  /* trying to insert too many attributes*/
+/* trying to insert too many attributes*/
 }
 
 void InsertService(const CipClass *const cip_class,
@@ -375,46 +375,43 @@ void InsertService(const CipClass *const cip_class,
                    const CipServiceFunction service_function,
                    char *const service_name) {
 
-  CipServiceStruct *service = cip_class->services;  /* get a pointer to the service array*/
+  CipServiceStruct *service = cip_class->services; /* get a pointer to the service array*/
   OPENER_TRACE_INFO("%s, number of services:%d, service number:%d\n",
                     cip_class->class_name, cip_class->number_of_services,
                     service_number);
   OPENER_ASSERT(service != NULL);
-  /* adding a service to a class that was not declared to have services is not allowed*/
-  for (int i = 0; i < cip_class->number_of_services; i++) /* Iterate over all service slots attached to the class */
+/* adding a service to a class that was not declared to have services is not allowed*/
+  for(int i = 0; i < cip_class->number_of_services; i++) /* Iterate over all service slots attached to the class */
   {
-    if (service->service_number == service_number||
-        service->service_function == NULL)         /* found undefined service slot*/
+    if(service->service_number == service_number ||
+       service->service_function == NULL)                                          /* found undefined service slot*/
     {
-      service->service_number = service_number;                   /* fill in service number*/
-      service->service_function = service_function;                   /* fill in function address*/
+      service->service_number = service_number; /* fill in service number*/
+      service->service_function = service_function; /* fill in function address*/
       service->name = service_name;
       return;
     }
     ++service;
   }
   OPENER_ASSERT(false);
-  /* adding more services than were declared is a no-no*/
+/* adding more services than were declared is a no-no*/
 }
 
-void InsertGetSetCallback
-(
-  CipClass *const cip_class,
-  CipGetSetCallback callback_function,
-  CIPAttributeFlag callbacks_to_install
-) {
-  if (0 != (kPreGetFunc & callbacks_to_install) ) {
+void InsertGetSetCallback(CipClass *const cip_class,
+                          CipGetSetCallback callback_function,
+                          CIPAttributeFlag callbacks_to_install) {
+  if(0 != (kPreGetFunc & callbacks_to_install) ) {
     cip_class->PreGetCallback = callback_function;
   }
-  if (0 != (kPostGetFunc & callbacks_to_install) ) {
+  if(0 != (kPostGetFunc & callbacks_to_install) ) {
     cip_class->PostGetCallback = callback_function;
   }
-  if (0 != (kPreSetFunc & callbacks_to_install) ) {
+  if(0 != (kPreSetFunc & callbacks_to_install) ) {
     cip_class->PreSetCallback = callback_function;
   }
-  /* The PostSetCallback is used for both, the after set action and the storage
-   * of non volatile data. Therefore check for both flags set. */
-  if (0 != ( (kPostSetFunc | kNvDataFunc) & callbacks_to_install ) ) {
+/* The PostSetCallback is used for both, the after set action and the storage
+ * of non volatile data. Therefore check for both flags set. */
+  if(0 != ( (kPostSetFunc | kNvDataFunc) & callbacks_to_install ) ) {
     cip_class->PostSetCallback = callback_function;
   }
 }
@@ -422,9 +419,9 @@ void InsertGetSetCallback
 CipAttributeStruct *GetCipAttribute(const CipInstance *const instance,
                                     const EipUint16 attribute_number) {
 
-  CipAttributeStruct *attribute = instance->attributes;       /* init pointer to array of attributes*/
-  for (int i = 0; i < instance->cip_class->number_of_attributes; i++) {
-    if (attribute_number == attribute->attribute_number) {
+  CipAttributeStruct *attribute = instance->attributes; /* init pointer to array of attributes*/
+  for(int i = 0; i < instance->cip_class->number_of_attributes; i++) {
+    if(attribute_number == attribute->attribute_number) {
       return attribute;
     } else {
       ++attribute;
@@ -470,9 +467,9 @@ EipStatus GetAttributeSingle(CipInstance *RESTRICT const instance,
        ]);
     if (0 != (get_bit_mask & (1 << (attribute_number % 8) ) ) ) {
       OPENER_TRACE_INFO("getAttribute %d\n",
-                        message_router_request->request_path.attribute_number);                 /* create a reply message containing the data*/
+                        message_router_request->request_path.attribute_number);                      /* create a reply message containing the data*/
 
-      /* Call the PreGetCallback if enabled for this attribute and the class provides one. */
+/* Call the PreGetCallback if enabled for this attribute and the class provides one. */
       if ( (attribute->attribute_flags & kPreGetFunc) &&
            NULL != instance->cip_class->PreGetCallback ) {
         instance->cip_class->PreGetCallback(instance,
@@ -480,11 +477,11 @@ EipStatus GetAttributeSingle(CipInstance *RESTRICT const instance,
                                             message_router_request->service);
       }
 
-      OPENER_ASSERT(NULL != attribute);
-      attribute->encode(attribute->data, &message_router_response->message);
+      OPENER_ASSERT(NULL != attribute); attribute->encode(attribute->data,
+                                                          &message_router_response->message);
       message_router_response->general_status = kCipErrorSuccess;
 
-      /* Call the PostGetCallback if enabled for this attribute and the class provides one. */
+/* Call the PostGetCallback if enabled for this attribute and the class provides one. */
       if ( (attribute->attribute_flags & kPostGetFunc) &&
            NULL != instance->cip_class->PostGetCallback ) {
         instance->cip_class->PostGetCallback(instance,
@@ -597,8 +594,8 @@ void EncodeCipString(const CipString *const data,
     outgoing_message->current_message_position += string->length;
     outgoing_message->used_message_length += string->length;
 
-    if (outgoing_message->used_message_length & 0x01) {
-      /* we have an odd byte count */
+    if(outgoing_message->used_message_length & 0x01) {
+/* we have an odd byte count */
       AddSintToMessage(0, outgoing_message);
     }
   }
@@ -627,23 +624,29 @@ void EncodeCipStringI(const CipStringI *const data,
                       ENIPMessage *const outgoing_message) {
   const CipStringI *const string_i = data;
   EncodeCipUsint(&(string_i->number_of_strings), outgoing_message);
-  for (size_t i = 0; i < string_i->number_of_strings; ++i) {
+  for(size_t i = 0; i < string_i->number_of_strings; ++i) {
     CipStringIHeaderEncoding( (string_i->array_of_string_i_structs) + i,
                               outgoing_message );
     switch(string_i->array_of_string_i_structs[i].char_string_struct) {
-      case kCipString: EncodeCipString(
-          string_i->array_of_string_i_structs[i].string,
-          outgoing_message); break;
-      case kCipString2: EncodeCipString2(
-          string_i->array_of_string_i_structs[i].string,
-          outgoing_message); break;
-      case kCipStringN: EncodeCipStringN(
-          string_i->array_of_string_i_structs[i].string,
-          outgoing_message); break;
-      case kCipShortString: EncodeCipShortString(
-          string_i->array_of_string_i_structs[i].string,
-          outgoing_message); break;
-      default: OPENER_ASSERT(false); break;
+      case kCipString:
+        EncodeCipString(string_i->array_of_string_i_structs[i].string,
+                        outgoing_message);
+        break;
+      case kCipString2:
+        EncodeCipString2(string_i->array_of_string_i_structs[i].string,
+                         outgoing_message);
+        break;
+      case kCipStringN:
+        EncodeCipStringN(string_i->array_of_string_i_structs[i].string,
+                         outgoing_message);
+        break;
+      case kCipShortString:
+        EncodeCipShortString(string_i->array_of_string_i_structs[i].string,
+                             outgoing_message);
+        break;
+      default:
+        OPENER_ASSERT(false);
+        break;
     }
   }
 }
@@ -910,8 +913,8 @@ int DecodeData(const EipUint8 cip_data_type,  //TODO: replace with Decode functi
                const EipUint8 **const cip_message) {
   int number_of_decoded_bytes = -1;
 
-  switch (cip_data_type)
-  /* check the data type of attribute */
+  switch(cip_data_type)
+/* check the data type of attribute */
   {
     case (kCipBool):
     case (kCipSint):
@@ -925,7 +928,7 @@ int DecodeData(const EipUint8 cip_data_type,  //TODO: replace with Decode functi
     case (kCipInt):
     case (kCipUint):
     case (kCipWord):
-      (*(EipUint16 *) (cip_data) ) = GetIntFromMessage(cip_message);
+      (*(EipUint16 *) (cip_data) ) = GetUintFromMessage(cip_message);
       number_of_decoded_bytes = 2;
       break;
 
@@ -933,7 +936,7 @@ int DecodeData(const EipUint8 cip_data_type,  //TODO: replace with Decode functi
     case (kCipUdint):
     case (kCipDword):
     case (kCipReal):
-      (*(EipUint32 *) (cip_data) ) = GetDintFromMessage(cip_message);
+      (*(EipUint32 *) (cip_data) ) = GetUdintFromMessage(cip_message);
       number_of_decoded_bytes = 4;
       break;
 
@@ -947,13 +950,13 @@ int DecodeData(const EipUint8 cip_data_type,  //TODO: replace with Decode functi
 
     case (kCipString): {
       CipString *string = (CipString *) cip_data;
-      string->length = GetIntFromMessage(cip_message);
+      string->length = GetUintFromMessage(cip_message);
       memcpy(string->string, *cip_message, string->length);
       *cip_message += string->length;
 
-      number_of_decoded_bytes = string->length + 2;           /* we have a two byte length field */
-      if (number_of_decoded_bytes & 0x01) {
-        /* we have an odd byte count */
+      number_of_decoded_bytes = string->length + 2; /* we have a two byte length field */
+      if(number_of_decoded_bytes & 0x01) {
+/* we have an odd byte count */
         ++(*cip_message);
         number_of_decoded_bytes++;
       }
@@ -982,10 +985,10 @@ int DecodeData(const EipUint8 cip_data_type,  //TODO: replace with Decode functi
 CipServiceStruct *GetCipService(const CipInstance *const instance,
                                 CipUsint service_number) {
   CipServiceStruct *service = instance->cip_class->services;
-  for (size_t i = 0; i < instance->cip_class->number_of_services; i++)       /* hunt for the GET_ATTRIBUTE_SINGLE service*/
+  for(size_t i = 0; i < instance->cip_class->number_of_services; i++) /* hunt for the GET_ATTRIBUTE_SINGLE service*/
   {
-    if (service->service_number == service_number) {
-      return service;   /* found the service */
+    if(service->service_number == service_number) {
+      return service; /* found the service */
     }
     service++;
   }
@@ -999,12 +1002,12 @@ EipStatus GetAttributeAll(CipInstance *instance,
                           const int encapsulation_session) {
 
   InitializeENIPMessage(&message_router_response->message);
-  CipAttributeStruct *attribute = instance->attributes;       /* pointer to list of attributes*/
+  CipAttributeStruct *attribute = instance->attributes; /* pointer to list of attributes*/
 
   //Missing header
 
-  if (0 == instance->cip_class->number_of_attributes) {
-    /*there are no attributes to be sent back*/
+  if(0 == instance->cip_class->number_of_attributes) {
+/*there are no attributes to be sent back*/
     message_router_response->reply_service =
       (0x80 | message_router_request->service);
     message_router_response->general_status = kCipErrorServiceNotSupported;
@@ -1013,13 +1016,12 @@ EipStatus GetAttributeAll(CipInstance *instance,
     GenerateGetAttributeSingleHeader(message_router_request,
                                      message_router_response);
     message_router_response->general_status = kCipErrorSuccess;
-    for (size_t j = 0; j < instance->cip_class->number_of_attributes; j++) {
-      /* for each instance attribute of this class */
+    for(size_t j = 0; j < instance->cip_class->number_of_attributes; j++) {
+/* for each instance attribute of this class */
       EipUint16 attribute_number = attribute->attribute_number;
-      if ( (instance->cip_class->get_all_bit_mask[CalculateIndex(
-                                                    attribute_number)]) &
-           (1 << (attribute_number % 8) ) ) {
-        /* only return attributes that are flagged as being part of GetAttributeAll */
+      if( (instance->cip_class->get_all_bit_mask[CalculateIndex(attribute_number)
+           ]) & (1 << (attribute_number % 8) ) ) {
+/* only return attributes that are flagged as being part of GetAttributeAll */
         message_router_request->request_path.attribute_number =
           attribute_number;
 
@@ -1037,19 +1039,19 @@ void EncodeEPath(CipEpath *epath,
   size_t start_length = message->used_message_length;
   AddIntToMessage(epath->path_size, message);
 
-  if (epath->class_id < 256) {
-    AddSintToMessage(0x20, message);     /* 8 Bit Class Id */
+  if(epath->class_id < 256) {
+    AddSintToMessage(0x20, message); /* 8 Bit Class Id */
     AddSintToMessage( (EipUint8) epath->class_id, message );
     length -= 1;
   } else {
-    AddSintToMessage(0x21, message);     /*16Bit Class Id */
-    AddSintToMessage(0, message);     /*pad byte */
+    AddSintToMessage(0x21, message); /*16Bit Class Id */
+    AddSintToMessage(0, message); /*pad byte */
     AddIntToMessage(epath->class_id, message);
     length -= 2;
   }
 
-  if (0 < length) {
-    if (epath->instance_number < 256) {
+  if(0 < length) {
+    if(epath->instance_number < 256) {
       AddSintToMessage(0x24, message); /*8Bit Instance Id */
       AddSintToMessage(epath->instance_number, message);
       length -= 1;
@@ -1060,8 +1062,8 @@ void EncodeEPath(CipEpath *epath,
       length -= 2;
     }
 
-    if (0 < length) {
-      if (epath->attribute_number < 256) {
+    if(0 < length) {
+      if(epath->attribute_number < 256) {
         AddSintToMessage(0x30, message); /*8Bit Attribute Id */
         AddSintToMessage(epath->attribute_number, message);
         length -= 1;
@@ -1075,7 +1077,7 @@ void EncodeEPath(CipEpath *epath,
   }
 
   OPENER_ASSERT(
-    2 + epath->path_size * 2 == message->used_message_length - start_length);              /* path size is in 16 bit chunks according to the specification */
+    2 + epath->path_size * 2 == message->used_message_length - start_length);           /* path size is in 16 bit chunks according to the specification */
 }
 
 int DecodePaddedEPath(CipEpath *epath,
@@ -1085,20 +1087,19 @@ int DecodePaddedEPath(CipEpath *epath,
 
   epath->path_size = *message_runner;
   message_runner++;
-  /* copy path to structure, in version 0.1 only 8 bit for Class,Instance and Attribute, need to be replaced with function */
+/* copy path to structure, in version 0.1 only 8 bit for Class,Instance and Attribute, need to be replaced with function */
   epath->class_id = 0;
   epath->instance_number = 0;
   epath->attribute_number = 0;
 
-  while (number_of_decoded_elements < epath->path_size) {
-    if (kSegmentTypeReserved
-        == ( (*message_runner) & kSegmentTypeReserved ) ) {
-      /* If invalid/reserved segment type, segment type greater than 0xE0 */
+  while(number_of_decoded_elements < epath->path_size) {
+    if(kSegmentTypeReserved == ( (*message_runner) & kSegmentTypeReserved ) ) {
+/* If invalid/reserved segment type, segment type greater than 0xE0 */
       return kEipStatusError;
     }
 
     number_of_decoded_elements++; /*At least one element is decoded */
-    switch (*message_runner) {
+    switch(*message_runner) {
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_CLASS_ID +
         LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
         epath->class_id = *(EipUint8 *) (message_runner + 1);
@@ -1108,7 +1109,7 @@ int DecodePaddedEPath(CipEpath *epath,
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_CLASS_ID +
         LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
         message_runner += 2;
-        epath->class_id = GetIntFromMessage(&(message_runner) );
+        epath->class_id = GetUintFromMessage(&(message_runner) );
         number_of_decoded_elements++;
         break;
 
@@ -1121,7 +1122,7 @@ int DecodePaddedEPath(CipEpath *epath,
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_INSTANCE_ID +
         LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
         message_runner += 2;
-        epath->instance_number = GetIntFromMessage(&(message_runner) );
+        epath->instance_number = GetUintFromMessage(&(message_runner) );
         number_of_decoded_elements++;
         break;
 
@@ -1134,12 +1135,12 @@ int DecodePaddedEPath(CipEpath *epath,
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_ATTRIBUTE_ID +
         LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT:
         message_runner += 2;
-        epath->attribute_number = GetIntFromMessage(&(message_runner) );
+        epath->attribute_number = GetUintFromMessage(&(message_runner) );
         number_of_decoded_elements++;
         break;
 
-      case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_MEMBER_ID
-        + LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
+      case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_MEMBER_ID +
+        LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
         message_runner += 2;
         break;
       case SEGMENT_TYPE_LOGICAL_SEGMENT + LOGICAL_SEGMENT_TYPE_MEMBER_ID +
@@ -1155,7 +1156,7 @@ int DecodePaddedEPath(CipEpath *epath,
   }
 
   *message = message_runner;
-  return number_of_decoded_elements * 2 + 1;       /* number_of_decoded_elements times 2 as every encoding uses 2 bytes */
+  return number_of_decoded_elements * 2 + 1; /* number_of_decoded_elements times 2 as every encoding uses 2 bytes */
 }
 
 void AllocateAttributeMasks(CipClass *target_class) {

Dosya farkı çok büyük olduğundan ihmal edildi
+ 269 - 304
source/src/cip/cipconnectionmanager.c


+ 114 - 123
source/src/cip/cipconnectionobject.c

@@ -60,14 +60,16 @@ CipConnectionObject explicit_connection_object_pool[
   OPENER_CIP_NUM_EXPLICIT_CONNS];
 
 DoublyLinkedListNode *CipConnectionObjectListArrayAllocator() {
-  enum {kNodesAmount = OPENER_CIP_NUM_EXPLICIT_CONNS +
-                       OPENER_CIP_NUM_INPUT_ONLY_CONNS +
-                       OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS +
-                       OPENER_CIP_NUM_LISTEN_ONLY_CONNS};
-  static DoublyLinkedListNode nodes[kNodesAmount] = {0};
+  enum {
+    kNodesAmount = OPENER_CIP_NUM_EXPLICIT_CONNS +
+                   OPENER_CIP_NUM_INPUT_ONLY_CONNS +
+                   OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS +
+                   OPENER_CIP_NUM_LISTEN_ONLY_CONNS
+  };
+  static DoublyLinkedListNode nodes[kNodesAmount] = { 0 };
   for(size_t i = 0; i < kNodesAmount; ++i) {
-    if(nodes[i].previous == NULL && nodes[i].next == NULL && nodes[i].data ==
-       NULL) {
+    if(nodes[i].previous == NULL && nodes[i].next == NULL &&
+       nodes[i].data == NULL) {
       return &nodes[i];
     }
   }
@@ -78,7 +80,7 @@ void CipConnectionObjectListArrayFree(DoublyLinkedListNode **node) {
 
   if(NULL != node) {
     if(NULL != *node) {
-      memset( *node, 0, sizeof(DoublyLinkedListNode) );
+      memset(*node, 0, sizeof(DoublyLinkedListNode) );
       *node = NULL;
     } else {
       OPENER_TRACE_ERR("Attempt to delete NULL pointer to node\n");
@@ -89,7 +91,6 @@ void CipConnectionObjectListArrayFree(DoublyLinkedListNode **node) {
 
 }
 
-
 /* Private methods declaration */
 uint64_t ConnectionObjectCalculateRegularInactivityWatchdogTimerValue(
   const CipConnectionObject *const connection_object);
@@ -100,7 +101,7 @@ void ConnectionObjectSetInitialInactivityWatchdogTimerValue(
 
 void ConnectionObjectInitializeEmpty(
   CipConnectionObject *const connection_object) {
-  memset( connection_object, 0, sizeof(*connection_object) );
+  memset(connection_object, 0, sizeof(*connection_object) );
   ConnectionObjectSetState(connection_object,
                            kConnectionObjectStateNonExistent);
   connection_object->socket[0] = kEipInvalidSocket;
@@ -112,28 +113,28 @@ CipConnectionObject *CipConnectionObjectCreate(const CipOctet *message) {
   return NULL;
 }
 
-void ConnectionObjectInitializeFromMessage(
-  const CipOctet **message,
-  CipConnectionObject *const connection_object) {
+void ConnectionObjectInitializeFromMessage(const CipOctet **message,
+                                           CipConnectionObject *const connection_object)
+{
   /* For unconnected send - can be ignored by targets, and is ignored here */
-  CipByte priority_timetick = GetSintFromMessage(message);
-  CipUsint timeout_ticks = GetSintFromMessage(message);
-  (void)priority_timetick;  /* Silence unused variable compiler warning */
-  (void)timeout_ticks;
+  CipByte priority_timetick = GetByteFromMessage(message);
+  CipUsint timeout_ticks = GetUsintFromMessage(message);
+  (void) priority_timetick; /* Silence unused variable compiler warning */
+  (void) timeout_ticks;
 
   /* O_to_T Conn ID */
   ConnectionObjectSetCipConsumedConnectionID(connection_object,
-                                             GetDintFromMessage(message) );
+                                             GetUdintFromMessage(message) );
   /* T_to_O Conn ID */
   ConnectionObjectSetCipProducedConnectionID(connection_object,
-                                             GetDintFromMessage(message) );
+                                             GetUdintFromMessage(message) );
 
   ConnectionObjectSetConnectionSerialNumber(connection_object,
-                                            GetIntFromMessage(message) );
+                                            GetUintFromMessage(message) );
   ConnectionObjectSetOriginatorVendorId(connection_object,
-                                        GetIntFromMessage(message) );
+                                        GetUintFromMessage(message) );
   ConnectionObjectSetOriginatorSerialNumber(connection_object,
-                                            GetDintFromMessage(message) );
+                                            GetUdintFromMessage(message) );
 
   /* keep it to none existent till the setup is done this eases error handling and
    * the state changes within the forward open request can not be detected from
@@ -144,8 +145,7 @@ void ConnectionObjectInitializeFromMessage(
   connection_object->sequence_count_producing = 0; /* set the sequence count to zero */
 
   ConnectionObjectSetConnectionTimeoutMultiplier(connection_object,
-                                                 GetSintFromMessage(
-                                                   message) );
+                                                 GetUsintFromMessage(message) );
 
   (*message) += 3; /* 3 bytes reserved */
 
@@ -158,43 +158,42 @@ void ConnectionObjectInitializeFromMessage(
     connection_object->connection_serial_number);
 
   ConnectionObjectSetOToTRequestedPacketInterval(connection_object,
-                                                 GetDintFromMessage(
-                                                   message) );
+                                                 GetUdintFromMessage(message) );
 
   ConnectionObjectSetInitialInactivityWatchdogTimerValue(connection_object);
 
-  if (connection_object->is_large_forward_open == true) {
+  if(connection_object->is_large_forward_open == true) {
     ConnectionObjectSetOToTNetworkConnectionParameters(connection_object,
-                                                       GetDintFromMessage(
+                                                       GetDwordFromMessage(
                                                          message) );
   } else {
     ConnectionObjectSetOToTNetworkConnectionParameters(connection_object,
-                                                       GetIntFromMessage(
+                                                       GetWordFromMessage(
                                                          message) );
   }
 
   ConnectionObjectSetTToORequestedPacketInterval(connection_object,
-                                                 GetDintFromMessage(message) );
+                                                 GetUdintFromMessage(message) );
 
   ConnectionObjectSetExpectedPacketRate(connection_object);
 
-  if (connection_object->is_large_forward_open == true) {
+  if(connection_object->is_large_forward_open == true) {
     ConnectionObjectSetTToONetworkConnectionParameters(connection_object,
-                                                       GetDintFromMessage(
+                                                       GetDwordFromMessage(
                                                          message) );
   } else {
     ConnectionObjectSetTToONetworkConnectionParameters(connection_object,
-                                                       GetIntFromMessage(
+                                                       GetWordFromMessage(
                                                          message) );
   }
 
-  connection_object->transport_class_trigger = GetSintFromMessage(message);
+  connection_object->transport_class_trigger = GetByteFromMessage(message);
 }
 
 ConnectionObjectState ConnectionObjectGetState(
   const CipConnectionObject *const connection_object) {
   ConnectionObjectState new_state = kConnectionObjectStateInvalid;
-  switch (connection_object->state) {
+  switch(connection_object->state) {
     case CIP_CONNECTION_OBJECT_STATE_NON_EXISTENT:
       new_state = kConnectionObjectStateNonExistent;
       break;
@@ -225,7 +224,7 @@ ConnectionObjectState ConnectionObjectGetState(
 
 void ConnectionObjectSetState(CipConnectionObject *const connection_object,
                               const ConnectionObjectState state) {
-  switch (state) {
+  switch(state) {
     case kConnectionObjectStateNonExistent:
       connection_object->state =
         CIP_CONNECTION_OBJECT_STATE_NON_EXISTENT;
@@ -287,7 +286,7 @@ void ConnectionObjectSetInstanceType(
 CipUsint ConnectionObjectGetInstanceTypeForAttribute(
   const CipConnectionObject *const connection_object) {
   CipUsint instance_type = kConnectionObjectInstanceTypeInvalid;
-  switch (connection_object->instance_type) {
+  switch(connection_object->instance_type) {
     case kConnectionObjectInstanceTypeExplicitMessaging:
       instance_type = CIP_CONNECTION_OBJECT_INSTANCE_TYPE_EXPLICIT_MESSAGING;
       break;
@@ -315,7 +314,8 @@ bool ConnectionObjectIsTypeNonLOIOConnection(
     case kConnectionObjectInstanceTypeIOExclusiveOwner:
     case kConnectionObjectInstanceTypeIOInputOnly:
       return true;
-    default: return false;
+    default:
+      return false;
   }
   return false;
 }
@@ -328,7 +328,8 @@ bool ConnectionObjectIsTypeIOConnection(
     case kConnectionObjectInstanceTypeIOInputOnly:
     case kConnectionObjectInstanceTypeIOListenOnly:
       return true;
-    default: return false;
+    default:
+      return false;
   }
   return false;
 }
@@ -337,11 +338,11 @@ ConnectionObjectTransportClassTriggerDirection
 ConnectionObjectGetTransportClassTriggerDirection(
   const CipConnectionObject *const connection_object) {
   const CipByte TransportClassTriggerDirectionMask = 0x80;
-  return (connection_object->transport_class_trigger &
-          TransportClassTriggerDirectionMask) ==
-         TransportClassTriggerDirectionMask ?
-         kConnectionObjectTransportClassTriggerDirectionServer
-         : kConnectionObjectTransportClassTriggerDirectionClient;
+  return
+    (connection_object->transport_class_trigger &
+     TransportClassTriggerDirectionMask) == TransportClassTriggerDirectionMask ?
+    kConnectionObjectTransportClassTriggerDirectionServer :
+    kConnectionObjectTransportClassTriggerDirectionClient;
 }
 
 ConnectionObjectTransportClassTriggerProductionTrigger
@@ -351,8 +352,8 @@ ConnectionObjectGetTransportClassTriggerProductionTrigger(
 
   ConnectionObjectTransportClassTriggerProductionTrigger production_trigger =
     kConnectionObjectTransportClassTriggerProductionTriggerInvalid;
-  switch ( (connection_object->transport_class_trigger) &
-           kTransportClassTriggerProductionTriggerMask ) {
+  switch( (connection_object->transport_class_trigger) &
+          kTransportClassTriggerProductionTriggerMask ) {
     case
       CIP_CONNECTION_OBJECT_TRANSPORT_CLASS_TRIGGER_PRODUCTION_TRIGGER_CYCLIC:
       production_trigger =
@@ -385,8 +386,8 @@ ConnectionObjectGetTransportClassTriggerTransportClass(
 
   ConnectionObjectTransportClassTriggerTransportClass transport_class_trigger =
     kConnectionObjectTransportClassTriggerTransportClassInvalid;
-  switch ( (connection_object->transport_class_trigger) &
-           kTransportClassTriggerTransportClassMask ) {
+  switch( (connection_object->transport_class_trigger) &
+          kTransportClassTriggerTransportClassMask ) {
     case CIP_CONNECTION_OBJECT_TRANSPORT_CLASS_TRIGGER_TRANSPORT_CLASS_0:
       transport_class_trigger =
         kConnectionObjectTransportClassTriggerTransportClass0;
@@ -417,8 +418,7 @@ CipUint ConnectionObjectGetProducedConnectionSize(
 
 void ConnectionObjectSetProducedConnectionSize(
   CipConnectionObject *const connection_object,
-  const CipUint
-  produced_connection_size) {
+  const CipUint produced_connection_size) {
   connection_object->produced_connection_size = produced_connection_size;
 }
 
@@ -443,13 +443,12 @@ CipUint ConnectionObjectGetRequestedPacketInterval(
   CipUdint remainder_to_resolution =
     (connection_object->t_to_o_requested_packet_interval) %
     (kOpenerTimerTickInMilliSeconds * 1000);
-  if( 0 == remainder_to_resolution ) {         /* Value can be represented in multiples of the timer resolution */
-    return (CipUint)(connection_object->t_to_o_requested_packet_interval /
-                     1000);
-  }
-  else{
-    return (CipUint)(connection_object->t_to_o_requested_packet_interval /
-                     1000 - remainder_to_resolution / 1000);
+  if(0 == remainder_to_resolution) { /* Value can be represented in multiples of the timer resolution */
+    return (CipUint) (connection_object->t_to_o_requested_packet_interval /
+                      1000);
+  } else {
+    return (CipUint) (connection_object->t_to_o_requested_packet_interval /
+                      1000 - remainder_to_resolution / 1000);
   }
 }
 
@@ -458,15 +457,14 @@ void ConnectionObjectSetExpectedPacketRate(
   CipUdint remainder_to_resolution =
     (connection_object->t_to_o_requested_packet_interval) %
     (kOpenerTimerTickInMilliSeconds * 1000);
-  if( 0 == remainder_to_resolution ) { /* Value can be represented in multiples of the timer resolution */
+  if(0 == remainder_to_resolution) { /* Value can be represented in multiples of the timer resolution */
     connection_object->expected_packet_rate =
       connection_object->t_to_o_requested_packet_interval / 1000;
-  }
-  else{
+  } else {
     connection_object->expected_packet_rate =
-      connection_object->t_to_o_requested_packet_interval / 1000 +
-      ( (CipUdint)
-        kOpenerTimerTickInMilliSeconds - remainder_to_resolution / 1000 );
+      connection_object->t_to_o_requested_packet_interval / 1000
+      + ( (CipUdint)
+          kOpenerTimerTickInMilliSeconds - remainder_to_resolution / 1000 );
   }
 }
 
@@ -477,8 +475,7 @@ CipUdint ConnectionObjectGetCipProducedConnectionID(
 
 void ConnectionObjectSetCipProducedConnectionID(
   CipConnectionObject *const connection_object,
-  const CipUdint
-  cip_produced_connection_id) {
+  const CipUdint cip_produced_connection_id) {
   connection_object->cip_produced_connection_id = cip_produced_connection_id;
 }
 
@@ -489,8 +486,7 @@ CipUdint ConnectionObjectGetCipConsumedConnectionID(
 
 void ConnectionObjectSetCipConsumedConnectionID(
   CipConnectionObject *const connection_object,
-  const CipUdint
-  cip_consumed_connection_id) {
+  const CipUdint cip_consumed_connection_id) {
   connection_object->cip_consumed_connection_id = cip_consumed_connection_id;
 }
 
@@ -498,7 +494,7 @@ ConnectionObjectWatchdogTimeoutAction ConnectionObjectGetWatchdogTimeoutAction(
   const CipConnectionObject *const connection_object) {
   ConnectionObjectWatchdogTimeoutAction timeout_action =
     kConnectionObjectWatchdogTimeoutActionInvalid;
-  switch (connection_object->watchdog_timeout_action) {
+  switch(connection_object->watchdog_timeout_action) {
     case CIP_CONNECTION_OBJECT_WATCHDOG_TIMEOUT_ACTION_TRANSITION_TO_TIMED_OUT:
       timeout_action =
         kConnectionObjectWatchdogTimeoutActionTransitionToTimedOut;
@@ -521,9 +517,8 @@ ConnectionObjectWatchdogTimeoutAction ConnectionObjectGetWatchdogTimeoutAction(
 
 void ConnectionObjectSetWatchdogTimeoutAction(
   CipConnectionObject *const connection_object,
-  const CipUsint
-  watchdog_timeout_action) {
-  switch (watchdog_timeout_action) {
+  const CipUsint watchdog_timeout_action) {
+  switch(watchdog_timeout_action) {
     case CIP_CONNECTION_OBJECT_WATCHDOG_TIMEOUT_ACTION_TRANSITION_TO_TIMED_OUT:
       connection_object->watchdog_timeout_action =
         kConnectionObjectWatchdogTimeoutActionTransitionToTimedOut;
@@ -554,8 +549,7 @@ CipUint ConnectionObjectGetProducedConnectionPathLength(
 
 void ConnectionObjectSetProducedConnectionPathLength(
   CipConnectionObject *const connection_object,
-  const CipUint
-  produced_connection_path_length) {
+  const CipUint produced_connection_path_length) {
   connection_object->produced_connection_path_length =
     produced_connection_path_length;
 }
@@ -567,8 +561,7 @@ CipUint ConnectionObjectGetConsumedConnectionPathLength(
 
 void ConnectionObjectSetConsumedConnectionPathLength(
   CipConnectionObject *const connection_object,
-  const CipUint
-  consumed_connection_path_length) {
+  const CipUint consumed_connection_path_length) {
   connection_object->consumed_connection_path_length =
     consumed_connection_path_length;
 }
@@ -580,8 +573,7 @@ CipUint ConnectionObjectGetProductionInhibitTime(
 
 void ConnectionObjectSetProductionInhibitTime(
   CipConnectionObject *const connection_object,
-  const CipUint
-  production_inhibit_time) {
+  const CipUint production_inhibit_time) {
   connection_object->production_inhibit_time = production_inhibit_time;
 }
 
@@ -615,12 +607,10 @@ void ConnectionObjectResetLastPackageInactivityTimerValue(
 uint64_t ConnectionObjectCalculateRegularInactivityWatchdogTimerValue(
   const CipConnectionObject *const connection_object) {
   return ( ( (uint64_t)(connection_object->o_to_t_requested_packet_interval) /
-             (uint64_t)1000 ) <<
+             (uint64_t) 1000 ) <<
            (2 + connection_object->connection_timeout_multiplier) );
 }
 
-
-
 CipUint ConnectionObjectGetConnectionSerialNumber(
   const CipConnectionObject *const connection_object) {
   return connection_object->connection_serial_number;
@@ -704,10 +694,9 @@ void ConnectionObjectSetOToTNetworkConnectionParameters(
     connection_parameters;
 }
 
-bool ConnectionObjectIsRedundantOwner(
-  const CipDword connection_parameters,
-  const CipBool is_lfo) {
-  if (is_lfo) {
+bool ConnectionObjectIsRedundantOwner(const CipDword connection_parameters,
+                                      const CipBool is_lfo) {
+  if(is_lfo) {
     return (connection_parameters & (1 << 31) );
   } else {
     return (connection_parameters & (1 << 15) );
@@ -733,20 +722,21 @@ ConnectionObjectConnectionType ConnectionObjectGetConnectionType(
   const CipBool is_lfo) {
 
   CipUsint connection_type;
-  if (is_lfo) {
+  if(is_lfo) {
     connection_type = (connection_parameters & (3 << 29) ) >> 29;
   } else {
     connection_type = (connection_parameters & (3 << 13) ) >> 13;
   }
 
   switch(connection_type) {
-    case CIP_CONNECTION_OBJECT_CONNECTION_TYPE_NULL: return
-        kConnectionObjectConnectionTypeNull;
-    case CIP_CONNECTION_OBJECT_CONNECTION_TYPE_MULTICAST: return
-        kConnectionObjectConnectionTypeMulticast;
-    case CIP_CONNECTION_OBJECT_CONNECTION_TYPE_POINT_TO_POINT: return
-        kConnectionObjectConnectionTypePointToPoint;
-    default: return kConnectionObjectConnectionTypeInvalid;
+    case CIP_CONNECTION_OBJECT_CONNECTION_TYPE_NULL:
+      return kConnectionObjectConnectionTypeNull;
+    case CIP_CONNECTION_OBJECT_CONNECTION_TYPE_MULTICAST:
+      return kConnectionObjectConnectionTypeMulticast;
+    case CIP_CONNECTION_OBJECT_CONNECTION_TYPE_POINT_TO_POINT:
+      return kConnectionObjectConnectionTypePointToPoint;
+    default:
+      return kConnectionObjectConnectionTypeInvalid;
   }
 }
 
@@ -769,7 +759,7 @@ ConnectionObjectPriority ConnectionObjectGetPriority(
   const CipBool is_lfo) {
 
   CipUsint priority;
-  if (is_lfo) {
+  if(is_lfo) {
     priority = (connection_parameters & (3 << 26) ) >> 26;
   } else {
     priority = (connection_parameters & (3 << 10) ) >> 10;
@@ -777,15 +767,20 @@ ConnectionObjectPriority ConnectionObjectGetPriority(
 
   ConnectionObjectPriority result;
   switch(priority) {
-    case CIP_CONNECTION_OBJECT_PRIORITY_LOW: result =
-      kConnectionObjectPriorityLow; break;
-    case CIP_CONNECTION_OBJECT_PRIORITY_HIGH: result =
-      kConnectionObjectPriorityHigh; break;
-    case CIP_CONNECTION_OBJECT_PRIORITY_SCHEDULED: result =
-      kConnectionObjectPriorityScheduled; break;
-    case CIP_CONNECTION_OBJECT_PRIORITY_URGENT: result =
-      kConnectionObjectPriorityUrgent; break;
-    default: OPENER_ASSERT(false);/* Not possible to get here! */
+    case CIP_CONNECTION_OBJECT_PRIORITY_LOW:
+      result = kConnectionObjectPriorityLow;
+      break;
+    case CIP_CONNECTION_OBJECT_PRIORITY_HIGH:
+      result = kConnectionObjectPriorityHigh;
+      break;
+    case CIP_CONNECTION_OBJECT_PRIORITY_SCHEDULED:
+      result = kConnectionObjectPriorityScheduled;
+      break;
+    case CIP_CONNECTION_OBJECT_PRIORITY_URGENT:
+      result = kConnectionObjectPriorityUrgent;
+      break;
+    default:
+      OPENER_ASSERT(false);/* Not possible to get here! */
       result = kConnectionObjectPriorityLow;
       break;
   }
@@ -806,19 +801,18 @@ ConnectionObjectPriority ConnectionObjectGetTToOPriority(
     connection_object->is_large_forward_open);
 }
 
-
 ConnectionObjectConnectionSizeType ConnectionObjectGetConnectionSizeType(
   const CipDword connection_parameters,
   const CipBool is_lfo) {
 
   bool connection_size_type;
-  if (is_lfo) {
+  if(is_lfo) {
     connection_size_type = (connection_parameters & (1 << 25) );
   } else {
     connection_size_type = (connection_parameters & (1 << 9) );
   }
 
-  if (connection_size_type) {
+  if(connection_size_type) {
     return kConnectionObjectConnectionSizeTypeVariable;
   } else {
     return kConnectionObjectConnectionSizeTypeFixed;
@@ -839,14 +833,13 @@ ConnectionObjectConnectionSizeType ConnectionObjectGetTToOConnectionSizeType(
     connection_object->is_large_forward_open);
 }
 
-size_t ConnectionObjectGetConnectionSize(
-  const CipDword connection_parameters,
-  const CipBool is_lfo) {
+size_t ConnectionObjectGetConnectionSize(const CipDword connection_parameters,
+                                         const CipBool is_lfo) {
   const CipDword kConnectionSizeMask = 0x000001FF;
   const CipDword kConnectionSizeMaskLFO = 0x0000FFFF;
 
   CipDword mask = kConnectionSizeMask;
-  if (is_lfo) {
+  if(is_lfo) {
     mask = kConnectionSizeMaskLFO;
   }
 
@@ -894,8 +887,8 @@ void ConnectionObjectGeneralConfiguration(
   connection_object->socket[0] = kEipInvalidSocket;
   connection_object->socket[1] = kEipInvalidSocket;
 
-  if ( kConnectionObjectConnectionTypePointToPoint
-       == ConnectionObjectGetOToTConnectionType(connection_object) ) {
+  if(kConnectionObjectConnectionTypePointToPoint ==
+     ConnectionObjectGetOToTConnectionType(connection_object) ) {
     /* if we have a point to point connection for the O to T direction
      * the target shall choose the connection ID.
      */
@@ -903,8 +896,8 @@ void ConnectionObjectGeneralConfiguration(
                                                GetConnectionId() );
   }
 
-  if ( kConnectionObjectConnectionTypeMulticast
-       == ConnectionObjectGetTToOConnectionType(connection_object) ) {
+  if(kConnectionObjectConnectionTypeMulticast ==
+     ConnectionObjectGetTToOConnectionType(connection_object) ) {
     /* if we have a multi-cast connection for the T to O direction the
      * target shall choose the connection ID.
      */
@@ -924,10 +917,9 @@ void ConnectionObjectGeneralConfiguration(
 
 bool ConnectionObjectEqualOriginator(const CipConnectionObject *const object1,
                                      const CipConnectionObject *const object2) {
-  if ( (object1->originator_vendor_id
-        == object2->originator_vendor_id)
-       && (object1->originator_serial_number
-           == object2->originator_serial_number) ) {
+  if( (object1->originator_vendor_id == object2->originator_vendor_id) &&
+      (object1->originator_serial_number ==
+       object2->originator_serial_number) ) {
     return true;
   }
   return false;
@@ -935,12 +927,11 @@ bool ConnectionObjectEqualOriginator(const CipConnectionObject *const object1,
 
 bool EqualConnectionTriad(const CipConnectionObject *const object1,
                           const CipConnectionObject *const object2) {
-  if ( (object1->connection_serial_number
-        == object2->connection_serial_number)
-       && (object1->originator_vendor_id
-           == object2->originator_vendor_id)
-       && (object1->originator_serial_number
-           == object2->originator_serial_number) ) {
+  if( (object1->connection_serial_number ==
+       object2->connection_serial_number) &&
+      (object1->originator_vendor_id == object2->originator_vendor_id)
+      && (object1->originator_serial_number ==
+          object2->originator_serial_number) ) {
     return true;
   }
   return false;

+ 173 - 199
source/src/cip/cipepath.c

@@ -16,68 +16,12 @@
 
 const unsigned int kPortSegmentExtendedPort = 15; /**< Reserved port segment port value, indicating the use of the extended port field */
 
-/* Segments */
-#define SEGMENT_TYPE_PORT_SEGMENT 0x00 /**< Message value of the Port segment */
-#define SEGMENT_TYPE_LOGICAL_SEGMENT 0x20 /**< Message value of the Logical segment */
-#define SEGMENT_TYPE_NETWORK_SEGMENT 0x40 /**< Message value of the Network segment */
-#define SEGMENT_TYPE_SYMBOLIC_SEGMENT 0x60 /**< Message value of the Symbolic segment */
-#define SEGMENT_TYPE_DATA_SEGMENT 0x80 /**< Message value of the Data segment */
-#define SEGMENT_TYPE_DATA_TYPE_CONSTRUCTED 0xA0 /**< Message value of the Data type constructed */
-#define SEGMENT_TYPE_DATA_TYPE_ELEMENTARTY 0xC0 /**< Message value of the Data type elementary */
-#define SEGMENT_TYPE_SEGMENT_RESERVED 0xE0 /**< Reserved value */
-
-#define LOGICAL_SEGMENT_TYPE_CLASS_ID 0x00 /**< Message value of the logical segment/logical type Class ID */
-#define LOGICAL_SEGMENT_TYPE_INSTANCE_ID 0x04 /**< Message value of the logical segment/logical type Instance ID */
-#define LOGICAL_SEGMENT_TYPE_MEMBER_ID 0x08 /**< Message value of the logical segment/logical type Member ID */
-#define LOGICAL_SEGMENT_TYPE_CONNECTION_POINT 0x0C /**< Message value of the logical segment/logical type Connection Point */
-#define LOGICAL_SEGMENT_TYPE_ATTRIBUTE_ID 0x10 /**< Message value of the logical segment/logical type Attribute ID */
-#define LOGICAL_SEGMENT_TYPE_SPECIAL 0x14 /**< Message value of the logical segment/logical type Special */
-#define LOGICAL_SEGMENT_TYPE_SERVICE_ID 0x18 /**< Message value of the logical segment/logical type Service ID */
-#define LOGICAL_SEGMENT_TYPE_EXTENDED_LOGICAL 0x1C /**< Message value of the logical segment/logical type Extended Logical */
-
-#define LOGICAL_SEGMENT_FORMAT_EIGHT_BIT 0x00
-#define LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT 0x01
-#define LOGICAL_SEGMENT_FORMAT_THIRTY_TWO_BIT 0x02
-
-#define LOGICAL_SEGMENT_EXTENDED_TYPE_RESERVED 0x00
-#define LOGICAL_SEGMENT_EXTENDED_TYPE_ARRAY_INDEX 0x01
-#define LOGICAL_SEGMENT_EXTENDED_TYPE_INDIRECT_ARRAY_INDEX 0x02
-#define LOGICAL_SEGMENT_EXTENDED_TYPE_BIT_INDEX 0x03
-#define LOGICAL_SEGMENT_EXTENDED_TYPE_INDIRECT_BIT_INDEX 0x04
-#define LOGICAL_SEGMENT_EXTENDED_TYPE_STRUCTURE_MEMBER_NUMBER 0x05
-#define LOGICAL_SEGMENT_EXTENDED_TYPE_STRUCTURE_MEMBER_HANDLE 0x06
-
-#define LOGICAL_SEGMENT_SPECIAL_TYPE_FORMAT_ELECTRONIC_KEY 0x00
-#define ELECTRONIC_KEY_SEGMENT_KEY_FORMAT_4 0x04
-
-#define NETWORK_SEGMENT_SCHEDULE 0x01
-#define NETWORK_SEGMENT_FIXED_TAG 0x02
-#define NETWORK_SEGMENT_PRODUCTION_INHIBIT_TIME_IN_MILLISECONDS 0x03
-#define NETWORK_SEGMENT_SAFETY 0x04
-#define NETWORK_SEGMENT_PRODUCTION_INHIBIT_TIME_IN_MICROSECONDS 0x10
-#define NETWORK_SEGMENT_EXTENDED_NETWORK 0x1F
-
-#define SYMBOLIC_SEGMENT_FORMAT_EXTENDED_STRING 0x00
-
-#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_DOUBLE_CHAR 0x20
-#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_TRIPLE_CHAR 0x40
-#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC 0xC0
-
-#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_USINT_TYPE 0x06
-#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UINT_TYPE 0x07
-#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UDINT_TYPE 0x08
-
-#define DATA_SEGMENT_SUBTYPE_SIMPLE_DATA 0x00
-#define DATA_SEGMENT_SUBTYPE_ANSI_EXTENDED_SYMBOL 0x11
-
-
-
 /*** Path Segment ***/
 SegmentType GetPathSegmentType(const CipOctet *const cip_path) {
   const unsigned int kSegmentTypeMask = 0xE0;
   const unsigned int segment_type = *cip_path & kSegmentTypeMask;
   SegmentType result = kSegmentTypeReserved;
-  switch (segment_type) {
+  switch(segment_type) {
     case SEGMENT_TYPE_PORT_SEGMENT:
       result = kSegmentTypePortSegment;
       break;
@@ -113,7 +57,7 @@ SegmentType GetPathSegmentType(const CipOctet *const cip_path) {
 
 void SetPathSegmentType(SegmentType segment_type,
                         unsigned char *const cip_path) {
-  switch (segment_type) {
+  switch(segment_type) {
     case kSegmentTypePortSegment:
       *cip_path = SEGMENT_TYPE_PORT_SEGMENT;
       break;
@@ -150,8 +94,8 @@ void SetPathSegmentType(SegmentType segment_type,
 bool GetPathPortSegmentExtendedLinkAddressSizeBit(
   const unsigned char *const cip_path) {
   const unsigned int kExtendedLinkAddressSizeMask = 0x10;
-  if ( kExtendedLinkAddressSizeMask ==
-       (*cip_path & kExtendedLinkAddressSizeMask) ) {
+  if(kExtendedLinkAddressSizeMask ==
+     (*cip_path & kExtendedLinkAddressSizeMask) ) {
     return true;
   }
   return false;
@@ -162,7 +106,7 @@ unsigned int GetPathPortSegmentPortIdentifier(
   const unsigned int kPortIdentifierMask = 0x0F;
   unsigned int port_identifier = *cip_path & kPortIdentifierMask;
 
-  OPENER_ASSERT( kSegmentTypePortSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kSegmentTypePortSegment == GetPathSegmentType(cip_path) );
   /* Use of reserved port identifier 0 */
   OPENER_ASSERT(0 != port_identifier);
   return port_identifier;
@@ -170,32 +114,32 @@ unsigned int GetPathPortSegmentPortIdentifier(
 
 void SetPathPortSegmentPortIdentifier(const unsigned int port_identifier,
                                       unsigned char *const cip_path) {
-/* OPENER_ASSERT(
-      port_identifier < 16,
-      "Port identifier too large for standard port identifier field\n"); */
+  /* OPENER_ASSERT(
+     port_identifier < 16,
+     "Port identifier too large for standard port identifier field\n"); */
   OPENER_ASSERT(port_identifier < 16);
   (*cip_path) |= port_identifier;
 }
 
 unsigned int GetPathPortSegmentLinkAddressSize(
   const unsigned char *const cip_path) {
-/*  OPENER_ASSERT(false == GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path),
-                "Call to non existent extended link address size\n"); */
-  OPENER_ASSERT( true ==
-                 GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path) );
+  /*  OPENER_ASSERT(false == GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path),
+     "Call to non existent extended link address size\n"); */
+  OPENER_ASSERT(true ==
+                GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path) );
   return *(cip_path + 1);
 }
 
 unsigned int GetPathPortSegmentExtendedPortNumber(
   const unsigned char *const cip_path) {
-/*  OPENER_ASSERT(kPortSegmentExtendedPort == GetPathPortSegmentPortIdentifier(cip_path),
-                "There is no extended port available!\n");*/
-  OPENER_ASSERT( kPortSegmentExtendedPort ==
-                 GetPathPortSegmentPortIdentifier(cip_path) );
+  /*  OPENER_ASSERT(kPortSegmentExtendedPort == GetPathPortSegmentPortIdentifier(cip_path),
+     "There is no extended port available!\n");*/
+  OPENER_ASSERT(kPortSegmentExtendedPort ==
+                GetPathPortSegmentPortIdentifier(cip_path) );
   const unsigned int kExtendedPortSegmentPosition =
     GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path) == true ? 2 : 1;
-  return cip_path[kExtendedPortSegmentPosition]
-         + (cip_path[kExtendedPortSegmentPosition + 1] << 8);
+  return cip_path[kExtendedPortSegmentPosition] +
+         (cip_path[kExtendedPortSegmentPosition + 1] << 8);
 }
 
 void SetPathPortSegmentExtendedPortIdentifier(
@@ -204,10 +148,10 @@ void SetPathPortSegmentExtendedPortIdentifier(
   SetPathPortSegmentPortIdentifier(kPortSegmentExtendedPort, cip_path);
   const unsigned int kExtendedPortSegmentPosition =
     GetPathPortSegmentExtendedLinkAddressSizeBit(cip_path) == true ? 2 : 1;
-  cip_path[kExtendedPortSegmentPosition] = (char) (extended_port_identifier
-                                                   & 0x00FF);
-  cip_path[kExtendedPortSegmentPosition + 1] =
-    (char) ( (extended_port_identifier & 0xFF00) >> 8 );
+  cip_path[kExtendedPortSegmentPosition] =
+    (char) (extended_port_identifier & 0x00FF);
+  cip_path[kExtendedPortSegmentPosition +
+           1] = (char) ( (extended_port_identifier & 0xFF00) >> 8 );
 }
 /*** Port Segment ***/
 
@@ -215,11 +159,11 @@ void SetPathPortSegmentExtendedPortIdentifier(
 
 LogicalSegmentLogicalType GetPathLogicalSegmentLogicalType(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
   const unsigned int kLogicalTypeMask = 0x1C;
   const unsigned int logical_type = (*cip_path) & kLogicalTypeMask;
   LogicalSegmentLogicalType result = kLogicalSegmentLogicalTypeExtendedLogical;
-  switch (logical_type) {
+  switch(logical_type) {
     case LOGICAL_SEGMENT_TYPE_CLASS_ID:
       result = kLogicalSegmentLogicalTypeClassId;
       break;
@@ -255,8 +199,8 @@ LogicalSegmentLogicalType GetPathLogicalSegmentLogicalType(
 
 void SetPathLogicalSegmentLogicalType(LogicalSegmentLogicalType logical_type,
                                       CipOctet *const cip_path) {
-  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
-  switch (logical_type) {
+  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  switch(logical_type) {
     case kLogicalSegmentLogicalTypeClassId:
       (*cip_path) |= LOGICAL_SEGMENT_TYPE_CLASS_ID;
       break;
@@ -291,11 +235,11 @@ void SetPathLogicalSegmentLogicalType(LogicalSegmentLogicalType logical_type,
 
 LogicalSegmentLogicalFormat GetPathLogicalSegmentLogicalFormat(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
   const unsigned int kLogicalFormatMask = 0x03;
   const unsigned int logical_format = (*cip_path) & kLogicalFormatMask;
   LogicalSegmentLogicalFormat result = kLogicalSegmentLogicalFormatEightBit;
-  switch (logical_format) {
+  switch(logical_format) {
     case LOGICAL_SEGMENT_FORMAT_EIGHT_BIT:
       result = kLogicalSegmentLogicalFormatEightBit;
       break;
@@ -316,9 +260,9 @@ LogicalSegmentLogicalFormat GetPathLogicalSegmentLogicalFormat(
 
 void SetPathLogicalSegmentLogicalFormat(LogicalSegmentLogicalFormat format,
                                         CipOctet *const cip_path) {
-  OPENER_ASSERT( kSegmentTypeLogicalSegment ==
-                 GetPathSegmentType( (const CipOctet *)cip_path ) );
-  switch (format) {
+  OPENER_ASSERT(kSegmentTypeLogicalSegment ==
+                GetPathSegmentType( (const CipOctet * )cip_path ) );
+  switch(format) {
     case kLogicalSegmentLogicalFormatEightBit:
       (*cip_path) |= LOGICAL_SEGMENT_FORMAT_EIGHT_BIT;
       break;
@@ -341,17 +285,17 @@ CipDword CipEpathGetLogicalValue(const EipUint8 **message) {
     GetPathLogicalSegmentLogicalFormat(*message);
   CipDword data = 0;
   (*message) += 1; /* Move to logical value */
-  switch (logical_format) {
+  switch(logical_format) {
     case kLogicalSegmentLogicalFormatEightBit:
-      data = GetSintFromMessage(message);
+      data = GetByteFromMessage(message);
       break;
     case kLogicalSegmentLogicalFormatSixteenBit:
       (*message) += 1; /* Pad byte needs to be skipped */
-      data = GetIntFromMessage(message);
+      data = GetWordFromMessage(message);
       break;
     case kLogicalSegmentLogicalFormatThirtyTwoBit:
       (*message) += 1; /* Pad byte needs to be skipped */
-      data = GetDintFromMessage(message);
+      data = GetDwordFromMessage(message);
       break;
     default:
       OPENER_ASSERT(false);/* shall not happen! */
@@ -363,17 +307,17 @@ CipDword CipEpathGetLogicalValue(const EipUint8 **message) {
 void CipEpathSetLogicalValue(const CipDword logical_value,
                              const LogicalSegmentLogicalFormat logical_format,
                              CipMessageRouterResponse *const message) {
-  switch(logical_value) {
+  switch(logical_format) {
     case kLogicalSegmentLogicalFormatEightBit:
       AddSintToMessage(logical_value, &message->message);
       break;
     case kLogicalSegmentLogicalFormatSixteenBit:
       MoveMessageNOctets(1, &message->message); /* Needed for padding */
-      AddIntToMessage(logical_value, message);
+      AddIntToMessage(logical_value, &message->message);
       break;
     case kLogicalSegmentLogicalFormatThirtyTwoBit:
       MoveMessageNOctets(1, &message->message); /* Needed for padding */
-      AddDintToMessage(logical_value, message);
+      AddDintToMessage(logical_value, &message->message);
       break;
     default:
       OPENER_ASSERT(false); /* This should never happen! */
@@ -383,27 +327,34 @@ void CipEpathSetLogicalValue(const CipDword logical_value,
 
 LogicalSegmentExtendedLogicalType GetPathLogicalSegmentExtendedLogicalType(
   const unsigned char *const cip_path) {
-/*  OPENER_ASSERT(LOGICAL_SEGMENT_TYPE_EXTENDED_kLogicalSegmentLogicalTypeExtendedLogicalMessageValue == GetPathLogicalSegmentLogicalType(cip_path),
-                "Trying to extract non-existent extended logical type") */
-  OPENER_ASSERT( kLogicalSegmentLogicalTypeExtendedLogical == GetPathLogicalSegmentLogicalType(
-                   cip_path) );
+  /*  OPENER_ASSERT(LOGICAL_SEGMENT_TYPE_EXTENDED_kLogicalSegmentLogicalTypeExtendedLogicalMessageValue == GetPathLogicalSegmentLogicalType(cip_path),
+     "Trying to extract non-existent extended logical type") */
+  OPENER_ASSERT(kLogicalSegmentLogicalTypeExtendedLogical == GetPathLogicalSegmentLogicalType(
+                  cip_path) );
   const unsigned int extended_logical_type = *(cip_path + 1);
   LogicalSegmentExtendedLogicalType result =
     kLogicalSegmentExtendedLogicalTypeReserved;
   switch(extended_logical_type) {
-    case LOGICAL_SEGMENT_EXTENDED_TYPE_ARRAY_INDEX: result =
-      kLogicalSegmentExtendedLogicalTypeArrayIndex; break;
-    case LOGICAL_SEGMENT_EXTENDED_TYPE_INDIRECT_ARRAY_INDEX: result =
-      kLogicalSegmentExtendedLogicalTypeIndirectArrayIndex; break;
-    case LOGICAL_SEGMENT_EXTENDED_TYPE_BIT_INDEX: result =
-      kLogicalSegmentExtendedLogicalTypeBitIndex; break;
-    case LOGICAL_SEGMENT_EXTENDED_TYPE_INDIRECT_BIT_INDEX: result =
-      kLogicalSegmentExtendedLogicalTypeIndirectBitIndex; break;
-    case LOGICAL_SEGMENT_EXTENDED_TYPE_STRUCTURE_MEMBER_NUMBER: result =
-      kLogicalSegmentExtendedLogicalTypeStructureMemberNumber; break;
-    case LOGICAL_SEGMENT_EXTENDED_TYPE_STRUCTURE_MEMBER_HANDLE: result =
-      kLogicalSegmentExtendedLogicalTypeStructureMemberHandle; break;
-    default: result = kLogicalSegmentExtendedLogicalTypeReserved;
+    case LOGICAL_SEGMENT_EXTENDED_TYPE_ARRAY_INDEX:
+      result = kLogicalSegmentExtendedLogicalTypeArrayIndex;
+      break;
+    case LOGICAL_SEGMENT_EXTENDED_TYPE_INDIRECT_ARRAY_INDEX:
+      result = kLogicalSegmentExtendedLogicalTypeIndirectArrayIndex;
+      break;
+    case LOGICAL_SEGMENT_EXTENDED_TYPE_BIT_INDEX:
+      result = kLogicalSegmentExtendedLogicalTypeBitIndex;
+      break;
+    case LOGICAL_SEGMENT_EXTENDED_TYPE_INDIRECT_BIT_INDEX:
+      result = kLogicalSegmentExtendedLogicalTypeIndirectBitIndex;
+      break;
+    case LOGICAL_SEGMENT_EXTENDED_TYPE_STRUCTURE_MEMBER_NUMBER:
+      result = kLogicalSegmentExtendedLogicalTypeStructureMemberNumber;
+      break;
+    case LOGICAL_SEGMENT_EXTENDED_TYPE_STRUCTURE_MEMBER_HANDLE:
+      result = kLogicalSegmentExtendedLogicalTypeStructureMemberHandle;
+      break;
+    default:
+      result = kLogicalSegmentExtendedLogicalTypeReserved;
   }
   return result;
 }
@@ -411,10 +362,10 @@ LogicalSegmentExtendedLogicalType GetPathLogicalSegmentExtendedLogicalType(
 LogicalSegmentSpecialTypeLogicalFormat
 GetPathLogicalSegmentSpecialTypeLogicalType(const unsigned char *const cip_path)
 {
-/*  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path), "Not a logical segment!\n") */
-  OPENER_ASSERT( kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT( kLogicalSegmentLogicalTypeSpecial == GetPathLogicalSegmentLogicalType(
-                   cip_path) );
+  /*  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path), "Not a logical segment!\n") */
+  OPENER_ASSERT(kSegmentTypeLogicalSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kLogicalSegmentLogicalTypeSpecial == GetPathLogicalSegmentLogicalType(
+                  cip_path) );
   const unsigned int kLogicalFormatMask = 0x03;
   const unsigned int logical_format = (*cip_path) & kLogicalFormatMask;
 
@@ -422,45 +373,49 @@ GetPathLogicalSegmentSpecialTypeLogicalType(const unsigned char *const cip_path)
     kLogicalSegmentSpecialTypeLogicalFormatReserved;
   switch(logical_format) {
     case LOGICAL_SEGMENT_SPECIAL_TYPE_FORMAT_ELECTRONIC_KEY:
-      result = kLogicalSegmentSpecialTypeLogicalFormatElectronicKey; break;
-    default: result = kLogicalSegmentSpecialTypeLogicalFormatReserved; break;
+      result = kLogicalSegmentSpecialTypeLogicalFormatElectronicKey;
+      break;
+    default:
+      result = kLogicalSegmentSpecialTypeLogicalFormatReserved;
+      break;
   }
   return result;
 }
 
 ElectronicKeySegmentFormat GetPathLogicalSegmentElectronicKeyFormat(
   const unsigned char *const cip_path) {
-/*  OPENER_ASSERT(kLogicalSegmentSpecialTypeLogicalFormatElectronicKey ==
-      GetPathLogicalSegmentSpecialTypeLogicalType(cip_path), "Not an electronic key!\n") */
-  OPENER_ASSERT( kLogicalSegmentSpecialTypeLogicalFormatElectronicKey ==
-                 GetPathLogicalSegmentSpecialTypeLogicalType(cip_path) );
+  /*  OPENER_ASSERT(kLogicalSegmentSpecialTypeLogicalFormatElectronicKey ==
+     GetPathLogicalSegmentSpecialTypeLogicalType(cip_path), "Not an electronic key!\n") */
+  OPENER_ASSERT(kLogicalSegmentSpecialTypeLogicalFormatElectronicKey == GetPathLogicalSegmentSpecialTypeLogicalType(
+                  cip_path) );
   ElectronicKeySegmentFormat result = kElectronicKeySegmentFormatReserved;
-  switch( *(cip_path + 1) ) {
-    case ELECTRONIC_KEY_SEGMENT_KEY_FORMAT_4: result =
-      kElectronicKeySegmentFormatKeyFormat4; break;
-    default: result = kElectronicKeySegmentFormatReserved; break;
+  switch(*(cip_path + 1) ) {
+    case ELECTRONIC_KEY_SEGMENT_KEY_FORMAT_4:
+      result = kElectronicKeySegmentFormatKeyFormat4;
+      break;
+    default:
+      result = kElectronicKeySegmentFormatReserved;
+      break;
   }
   return result;
 }
 
-void GetElectronicKeyFormat4FromMessage(
-  const CipOctet **const message,
-  ElectronicKeyFormat4 *key) {
-  OPENER_ASSERT( kElectronicKeySegmentFormatKeyFormat4 ==
-                 GetPathLogicalSegmentElectronicKeyFormat(*message) );
+void GetElectronicKeyFormat4FromMessage(const CipOctet **const message,
+                                        ElectronicKeyFormat4 *key) {
+  OPENER_ASSERT(kElectronicKeySegmentFormatKeyFormat4 == GetPathLogicalSegmentElectronicKeyFormat(
+                  *message) );
 
   (*message) += 2;
-  ElectronicKeyFormat4SetVendorId(key, GetIntFromMessage(message) );
-  ElectronicKeyFormat4SetDeviceType(key, GetIntFromMessage(message) );
-  ElectronicKeyFormat4SetProductCode(key, GetIntFromMessage(message) );
+  ElectronicKeyFormat4SetVendorId(key, GetUintFromMessage(message) );
+  ElectronicKeyFormat4SetDeviceType(key, GetUintFromMessage(message) );
+  ElectronicKeyFormat4SetProductCode(key, GetUintFromMessage(message) );
   ElectronicKeyFormat4SetMajorRevisionCompatibility(key,
-                                                    GetSintFromMessage(message) );
-  ElectronicKeyFormat4SetMinorRevision(key, GetSintFromMessage(message) );
+                                                    GetByteFromMessage(message) );
+  ElectronicKeyFormat4SetMinorRevision(key, GetUsintFromMessage(message) );
 }
 
 /*** Logical Segment ***/
 
-
 /*** Network Segment ***/
 
 /** @brief Return the Network Segment subtype
@@ -470,24 +425,32 @@ void GetElectronicKeyFormat4FromMessage(
  */
 NetworkSegmentSubtype GetPathNetworkSegmentSubtype(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT( kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
   const unsigned int kSubtypeMask = 0x1F;
   const unsigned int subtype = (*cip_path) & kSubtypeMask;
   NetworkSegmentSubtype result = kNetworkSegmentSubtypeReserved;
   switch(subtype) {
     case NETWORK_SEGMENT_SCHEDULE:
-      result = kNetworkSegmentSubtypeScheduleSegment; break;
+      result = kNetworkSegmentSubtypeScheduleSegment;
+      break;
     case NETWORK_SEGMENT_FIXED_TAG:
-      result = kNetworkSegmentSubtypeFixedTagSegment; break;
+      result = kNetworkSegmentSubtypeFixedTagSegment;
+      break;
     case NETWORK_SEGMENT_PRODUCTION_INHIBIT_TIME_IN_MILLISECONDS:
-      result = kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds; break;
+      result = kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds;
+      break;
     case NETWORK_SEGMENT_SAFETY:
-      result = kNetworkSegmentSubtypeSafetySegment; break;
+      result = kNetworkSegmentSubtypeSafetySegment;
+      break;
     case NETWORK_SEGMENT_PRODUCTION_INHIBIT_TIME_IN_MICROSECONDS:
-      result = kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds; break;
+      result = kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds;
+      break;
     case NETWORK_SEGMENT_EXTENDED_NETWORK:
-      result = kNetworkSegmentSubtypeExtendedNetworkSegment; break;
-    default: result = kNetworkSegmentSubtypeReserved; break;
+      result = kNetworkSegmentSubtypeExtendedNetworkSegment;
+      break;
+    default:
+      result = kNetworkSegmentSubtypeReserved;
+      break;
   }
 
   return result;
@@ -501,12 +464,12 @@ NetworkSegmentSubtype GetPathNetworkSegmentSubtype(
  */
 CipUsint GetPathNetworkSegmentProductionInhibitTimeInMilliseconds(
   const unsigned char *const cip_path) {
-/*  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path),"Not a network segment!\n")
-   OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds == GetPathNetworkSegmentSubtype(cip_path),
-                "Not a Production Inhibit Time milliseconds segment!\n") */
-  OPENER_ASSERT( kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT( kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds == GetPathNetworkSegmentSubtype(
-                   cip_path) );
+  /*  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path),"Not a network segment!\n")
+     OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds == GetPathNetworkSegmentSubtype(cip_path),
+     "Not a Production Inhibit Time milliseconds segment!\n") */
+  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMilliseconds == GetPathNetworkSegmentSubtype(
+                  cip_path) );
   return *(cip_path + 1);
 }
 
@@ -518,18 +481,18 @@ CipUsint GetPathNetworkSegmentProductionInhibitTimeInMilliseconds(
  */
 CipUdint GetPathNetworkSegmentProductionInhibitTimeInMicroseconds(
   const unsigned char *const cip_path) {
-/*  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path),"Not a network segment!\n")
-   OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds == GetPathNetworkSegmentSubtype(cip_path),
-                  "Not a Production Inhibit Time microseconds segment!\n")
-   OPENER_ASSERT(2 == *(cip_path + 1), "Data Words length is incorrect! See CIP Spec Vol.1 C-1.4.3.3.2\n") */
+  /*  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path),"Not a network segment!\n")
+     OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds == GetPathNetworkSegmentSubtype(cip_path),
+     "Not a Production Inhibit Time microseconds segment!\n")
+     OPENER_ASSERT(2 == *(cip_path + 1), "Data Words length is incorrect! See CIP Spec Vol.1 C-1.4.3.3.2\n") */
 
-  OPENER_ASSERT( kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT( kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds == GetPathNetworkSegmentSubtype(
-                   cip_path) );
-  OPENER_ASSERT( 2 == *(cip_path + 1) );
+  OPENER_ASSERT(kSegmentTypeNetworkSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kNetworkSegmentSubtypeProductionInhibitTimeInMicroseconds == GetPathNetworkSegmentSubtype(
+                  cip_path) );
+  OPENER_ASSERT(2 == *(cip_path + 1) );
 
   const unsigned char *message_runner = cip_path + 2;
-  return GetDintFromMessage(&message_runner);
+  return GetUdintFromMessage(&message_runner);
 }
 
 /*** Network Segment ***/
@@ -539,8 +502,8 @@ CipUdint GetPathNetworkSegmentProductionInhibitTimeInMicroseconds(
 SymbolicSegmentFormat GetPathSymbolicSegmentFormat(
   const unsigned char *const cip_path) {
   const unsigned int kSymbolicSegmentFormatMask = 0x1F;
-  if( SYMBOLIC_SEGMENT_FORMAT_EXTENDED_STRING ==
-      (*cip_path & kSymbolicSegmentFormatMask) ) {
+  if(SYMBOLIC_SEGMENT_FORMAT_EXTENDED_STRING ==
+     (*cip_path & kSymbolicSegmentFormatMask) ) {
     return kSymbolicSegmentFormatExtendedString;
   }
   return kSymbolicSegmentFormatASCII;
@@ -561,34 +524,44 @@ SymbolicSegmentExtendedFormat GetPathSymbolicSegmentNumericType(
                                        kSymbolicSegmentExtendedFormatNumericTypeMask;
   SymbolicSegmentExtendedFormat result = kSymbolicSegmentExtendedFormatReserved;
   switch(numeric_subtype) {
-    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_USINT_TYPE: result =
-      kSymbolicSegmentExtendedFormatNumericSymbolUSINT; break;
-    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UINT_TYPE: result =
-      kSymbolicSegmentExtendedFormatNumericSymbolUINT; break;
-    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UDINT_TYPE: result =
-      kSymbolicSegmentExtendedFormatNumericSymbolUDINT; break;
-    default: result = kSymbolicSegmentExtendedFormatReserved; break;
+    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_USINT_TYPE:
+      result = kSymbolicSegmentExtendedFormatNumericSymbolUSINT;
+      break;
+    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UINT_TYPE:
+      result = kSymbolicSegmentExtendedFormatNumericSymbolUINT;
+      break;
+    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UDINT_TYPE:
+      result = kSymbolicSegmentExtendedFormatNumericSymbolUDINT;
+      break;
+    default:
+      result = kSymbolicSegmentExtendedFormatReserved;
+      break;
   }
   return result;
 }
 
 SymbolicSegmentExtendedFormat GetPathSymbolicSegmentExtendedFormat(
   const unsigned char *const cip_path) {
-  OPENER_ASSERT( kSegmentTypeSymbolicSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT( kSymbolicSegmentFormatExtendedString == GetPathSymbolicSegmentFormat(
-                   cip_path) );
+  OPENER_ASSERT(kSegmentTypeSymbolicSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kSymbolicSegmentFormatExtendedString == GetPathSymbolicSegmentFormat(
+                  cip_path) );
   const unsigned int kSymbolicSegmentExtendedFormatMask = 0xE0;
   const unsigned int extended_type = *(cip_path + 1) &
                                      kSymbolicSegmentExtendedFormatMask;
   SymbolicSegmentExtendedFormat result = kSymbolicSegmentExtendedFormatReserved;
   switch(extended_type) {
-    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_DOUBLE_CHAR: result =
-      kSymbolicSegmentExtendedFormatDoubleByteChars; break;
-    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_TRIPLE_CHAR: result =
-      kSymbolicSegmentExtendedFormatTripleByteChars; break;
-    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC: result =
-      GetPathSymbolicSegmentNumericType(cip_path); break;
-    default: result = kSymbolicSegmentExtendedFormatReserved; break;
+    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_DOUBLE_CHAR:
+      result = kSymbolicSegmentExtendedFormatDoubleByteChars;
+      break;
+    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_TRIPLE_CHAR:
+      result = kSymbolicSegmentExtendedFormatTripleByteChars;
+      break;
+    case SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC:
+      result = GetPathSymbolicSegmentNumericType(cip_path);
+      break;
+    default:
+      result = kSymbolicSegmentExtendedFormatReserved;
+      break;
   }
   return result;
 }
@@ -605,10 +578,14 @@ DataSegmentSubtype GetPathDataSegmentSubtype(const unsigned char *const cip_path
   DataSegmentSubtype result = kDataSegmentSubtypeReserved;
   switch(data_subtype) {
     case DATA_SEGMENT_SUBTYPE_SIMPLE_DATA:
-      result = kDataSegmentSubtypeSimpleData; break;
+      result = kDataSegmentSubtypeSimpleData;
+      break;
     case DATA_SEGMENT_SUBTYPE_ANSI_EXTENDED_SYMBOL:
-      result = kDataSegmentSubtypeANSIExtendedSymbol; break;
-    default: result = kDataSegmentSubtypeReserved; break;
+      result = kDataSegmentSubtypeANSIExtendedSymbol;
+      break;
+    default:
+      result = kDataSegmentSubtypeReserved;
+      break;
   }
   return result;
 }
@@ -620,14 +597,14 @@ DataSegmentSubtype GetPathDataSegmentSubtype(const unsigned char *const cip_path
  */
 CipUsint GetPathDataSegmentSimpleDataWordLength(
   const unsigned char *const cip_path) {
-/*  OPENER_ASSERT(kSegmentTypeDataSegment == GetPathSegmentType(cip_path),"Not a data segment!\n");
-    OPENER_ASSERT(kDataSegmentSubtypeSimpleData == GetPathDataSegmentSubtype(cip_path), "Not a simple data segment!\n") */
-  OPENER_ASSERT( kSegmentTypeDataSegment == GetPathSegmentType(cip_path) );
-  OPENER_ASSERT( kDataSegmentSubtypeSimpleData ==
-                 GetPathDataSegmentSubtype(cip_path) );
+  /*  OPENER_ASSERT(kSegmentTypeDataSegment == GetPathSegmentType(cip_path),"Not a data segment!\n");
+     OPENER_ASSERT(kDataSegmentSubtypeSimpleData == GetPathDataSegmentSubtype(cip_path), "Not a simple data segment!\n") */
+  OPENER_ASSERT(kSegmentTypeDataSegment == GetPathSegmentType(cip_path) );
+  OPENER_ASSERT(kDataSegmentSubtypeSimpleData ==
+                GetPathDataSegmentSubtype(cip_path) );
 
   const unsigned char *message_runner = cip_path + 1;
-  return GetSintFromMessage(&message_runner);
+  return GetUsintFromMessage(&message_runner);
 }
 
 /*** End Data Segment ***/
@@ -647,7 +624,6 @@ LogicalSegmentLogicalFormat CipEpathGetNeededLogicalFormatForValue(
   return logical_format;
 }
 
-
 //TODO: Does not match the actual interface anymore, check how to fix
 size_t CipEpathEncodeConnectionEpath(
   const CipConnectionPathEpath *const connection_epath,
@@ -662,7 +638,7 @@ size_t CipEpathEncodeConnectionEpath(
       CipEpathGetNeededLogicalFormatForValue(connection_epath->class_id);
     SetPathLogicalSegmentLogicalFormat(logical_value, *encoded_path);
     encoded_path_length += 1;
-    MoveMessageNOctets(1, (const CipOctet **)encoded_path);
+    MoveMessageNOctets(1, (const CipOctet **) encoded_path);
     CipEpathSetLogicalValue(connection_epath->class_id,
                             logical_value,
                             encoded_path);
@@ -676,11 +652,10 @@ size_t CipEpathEncodeConnectionEpath(
       CipEpathGetNeededLogicalFormatForValue(connection_epath->instance_id);
     SetPathLogicalSegmentLogicalFormat(logical_value, *encoded_path);
     encoded_path_length += 1;
-    MoveMessageNOctets(1, (const CipOctet **)encoded_path);
-    CipEpathSetLogicalValue(
-      connection_epath->instance_id,
-      logical_value,
-      encoded_path);
+    MoveMessageNOctets(1, (const CipOctet **) encoded_path);
+    CipEpathSetLogicalValue(connection_epath->instance_id,
+                            logical_value,
+                            encoded_path);
   }
 
   if(0 != connection_epath->attribute_id_or_connection_point) {
@@ -692,11 +667,10 @@ size_t CipEpathEncodeConnectionEpath(
         connection_epath->attribute_id_or_connection_point);
     SetPathLogicalSegmentLogicalFormat(logical_value, *encoded_path);
     encoded_path_length += 1;
-    MoveMessageNOctets(1, (const CipOctet **)encoded_path);
-    CipEpathSetLogicalValue(
-      connection_epath->attribute_id_or_connection_point,
-      logical_value,
-      encoded_path);
+    MoveMessageNOctets(1, (const CipOctet **) encoded_path);
+    CipEpathSetLogicalValue(connection_epath->attribute_id_or_connection_point,
+                            logical_value,
+                            encoded_path);
   }
   return encoded_path_length += 1;
 }

+ 23 - 10
source/src/cip/cipepath.h

@@ -43,13 +43,27 @@
 #define LOGICAL_SEGMENT_EXTENDED_TYPE_STRUCTURE_MEMBER_HANDLE 0x06 /**< Message value indicating the Structured Member Handler Extended Logical Segment type */
 
 #define LOGICAL_SEGMENT_SPECIAL_TYPE_FORMAT_ELECTRONIC_KEY 0x00 /**< Message value indicating an electronic key */
+#define ELECTRONIC_KEY_SEGMENT_KEY_FORMAT_4 0x04
 
-#define NETWORK_SEGMENT_SUBTYPE_SCHEDULE 0x01 /**< Message value indicating a network segment schedule message */
-#define NETWORK_SEGMENT_SUBTYPE_FIXED_TAG 0x02 /**< Message value indicating a network segment fixed tag message */
-#define NETWORK_SEGMENT_SUBTYPE_PRODUCTION_INHIBIT_TIME_IN_MILLISECONDS 0x03 /**< Message value indicating a network segment PIT in milliseconds message */
-#define NETWORK_SEGMENT_SUBTYPE_SAFETY 0x04 /**< Message value indicating a network segment safety message */
-#define NETWORK_SEGMENT_SUBTYPE_PRODUCTION_INHIBIT_TIME_IN_MICROSECONDS 0x10 /**< Message value indicating a network segment PIT in microseconds message */
-#define NETWORK_SEGMENT_SUBTYPE_EXTENDED_NETWORK 0x1F /**< Message indicating a network message extended network message */
+#define NETWORK_SEGMENT_SCHEDULE 0x01 /**< Message value indicating a network segment schedule message */
+#define NETWORK_SEGMENT_FIXED_TAG 0x02 /**< Message value indicating a network segment fixed tag message */
+#define NETWORK_SEGMENT_PRODUCTION_INHIBIT_TIME_IN_MILLISECONDS 0x03 /**< Message value indicating a network segment PIT in milliseconds message */
+#define NETWORK_SEGMENT_SAFETY 0x04 /**< Message value indicating a network segment safety message */
+#define NETWORK_SEGMENT_PRODUCTION_INHIBIT_TIME_IN_MICROSECONDS 0x10 /**< Message value indicating a network segment PIT in microseconds message */
+#define NETWORK_SEGMENT_EXTENDED_NETWORK 0x1F /**< Message indicating a network message extended network message */
+
+#define SYMBOLIC_SEGMENT_FORMAT_EXTENDED_STRING 0x00
+
+#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_DOUBLE_CHAR 0x20
+#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_TRIPLE_CHAR 0x40
+#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC 0xC0
+
+#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_USINT_TYPE 0x06
+#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UINT_TYPE 0x07
+#define SYMBOLIC_SEGMENT_EXTENDED_FORMAT_NUMERIC_UDINT_TYPE 0x08
+
+#define DATA_SEGMENT_SUBTYPE_SIMPLE_DATA 0x00
+#define DATA_SEGMENT_SUBTYPE_ANSI_EXTENDED_SYMBOL 0x11
 
 /** @brief Segment type Enum
  *
@@ -161,7 +175,7 @@ typedef enum symbolic_segment_extended_format {
 
 /* Start - Often used types of EPaths */
 typedef struct connection_path_epath {
-  CipDword class_id; /**< here in accordance with Vol. 1 C-1.4.2 */
+  CipDword class_id;   /**< here in accordance with Vol. 1 C-1.4.2 */
   CipDword instance_id;
   CipDword attribute_id_or_connection_point;
 } CipConnectionPathEpath;
@@ -293,9 +307,8 @@ ElectronicKeySegmentFormat GetPathLogicalSegmentElectronicKeyFormat(
  * @param cip_path The start of the EPath message
  * @param key Writes the data on the user provided data electronic key struct
  */
-void GetElectronicKeyFormat4FromMessage(
-  const CipOctet **const cip_path,
-  ElectronicKeyFormat4 *key);
+void GetElectronicKeyFormat4FromMessage(const CipOctet **const cip_path,
+                                        ElectronicKeyFormat4 *key);
 
 /** @brief Gets the Network Segment Subtype of a EPatch Network Segement EPath message
  *

+ 175 - 200
source/src/cip/cipioconnection.c

@@ -20,7 +20,6 @@
 #include "trace.h"
 #include "endianconv.h"
 
-
 /*The port to be used per default for I/O messages on UDP.*/
 const int kOpenerEipIoUdpPort = 0x08AE;
 
@@ -31,10 +30,9 @@ EipStatus OpenProducingMulticastConnection(
   CipConnectionObject *connection_object,
   CipCommonPacketFormatData *common_packet_format_data);
 
-EipStatus OpenMulticastConnection(
-  UdpCommuncationDirection direction,
-  CipConnectionObject *connection_object,
-  CipCommonPacketFormatData *common_packet_format_data);
+EipStatus OpenMulticastConnection(UdpCommuncationDirection direction,
+                                  CipConnectionObject *connection_object,
+                                  CipCommonPacketFormatData *common_packet_format_data);
 
 EipStatus OpenConsumingPointToPointConnection(
   CipConnectionObject *const connection_object,
@@ -61,10 +59,9 @@ void HandleIoConnectionTimeOut(CipConnectionObject *connection_object);
  */
 EipStatus SendConnectedData(CipConnectionObject *connection_object);
 
-EipStatus HandleReceivedIoConnectionData(
-  CipConnectionObject *connection_object,
-  const EipUint8 *data,
-  EipUint16 data_length);
+EipStatus HandleReceivedIoConnectionData(CipConnectionObject *connection_object,
+                                         const EipUint8 *data,
+                                         EipUint16 data_length);
 
 /**** Global variables ****/
 EipUint8 *g_config_data_buffer = NULL; /**< buffers for the config data coming with a forward open request. */
@@ -74,23 +71,21 @@ EipUint32 g_run_idle_state = 0; /**< buffer for holding the run idle information
 
 EipUint16 ProcessProductionInhibitTime(CipConnectionObject *io_connection_object)
 {
-  if ( kConnectionObjectTransportClassTriggerProductionTriggerCyclic
-       == ConnectionObjectGetTransportClassTriggerProductionTrigger(
-         io_connection_object) ) {
-    if ( 256 ==
-         ConnectionObjectGetProductionInhibitTime(io_connection_object) ) {
+  if(kConnectionObjectTransportClassTriggerProductionTriggerCyclic ==
+     ConnectionObjectGetTransportClassTriggerProductionTrigger(
+       io_connection_object) )
+  {
+    if(256 == ConnectionObjectGetProductionInhibitTime(io_connection_object) ) {
       OPENER_TRACE_INFO("No PIT segment available\n");
       /* there was no PIT segment in the connection path; set PIT to one fourth of RPI */
       ConnectionObjectSetProductionInhibitTime(io_connection_object,
                                                ConnectionObjectGetTToORequestedPacketInterval(
-                                                 io_connection_object)
-                                               / 4000);
+                                                 io_connection_object) / 4000);
     } else {
       /* If a production inhibit time is provided, it needs to be smaller than the Requested Packet Interval */
-      if ( ConnectionObjectGetProductionInhibitTime(io_connection_object)
-           > (ConnectionObjectGetTToORequestedPacketInterval(
-                io_connection_object)
-              / 1000) ) {
+      if(ConnectionObjectGetProductionInhibitTime(io_connection_object) >
+         (ConnectionObjectGetTToORequestedPacketInterval(io_connection_object) /
+          1000) ) {
         /* see section C-1.4.3.3 */
         return
           kConnectionManagerExtendedStatusCodeProductionInhibitTimerGreaterThanRpi;
@@ -306,21 +301,21 @@ CipError EstablishIoConnection(
     ConnectionObjectGetTToOConnectionType(io_connection_object);
 
   /** Already handled by forward open */
-  OPENER_ASSERT( !(originator_to_target_connection_type ==
-                   kConnectionObjectConnectionTypeNull &&
-                   target_to_originator_connection_type ==
-                   kConnectionObjectConnectionTypeNull) );
+  OPENER_ASSERT(
+    !(originator_to_target_connection_type ==
+      kConnectionObjectConnectionTypeNull &&
+      target_to_originator_connection_type ==
+      kConnectionObjectConnectionTypeNull) );
 
   io_connection_object->consuming_instance = NULL;
   io_connection_object->consumed_connection_path_length = 0;
   io_connection_object->producing_instance = NULL;
   io_connection_object->produced_connection_path_length = 0;
 
-
-  /* we don't need to check for zero as this is handled in the connection path parsing */
+/* we don't need to check for zero as this is handled in the connection path parsing */
 
   if (originator_to_target_connection_type !=
-      kConnectionObjectConnectionTypeNull) {                                         /*setup consumer side*/
+      kConnectionObjectConnectionTypeNull) { /*setup consumer side*/
     *extended_error = SetupIoConnectionOriginatorToTargetConnectionPoint(
       io_connection_object,
       connection_object);
@@ -329,9 +324,8 @@ CipError EstablishIoConnection(
     }
   }
 
-
   if (target_to_originator_connection_type !=
-      kConnectionObjectConnectionTypeNull) {                                         /*setup producer side*/
+      kConnectionObjectConnectionTypeNull) { /*setup producer side*/
     *extended_error = SetupIoConnectionTargetToOriginatorConnectionPoint(
       io_connection_object,
       connection_object);
@@ -340,7 +334,6 @@ CipError EstablishIoConnection(
     }
   }
 
-
   if (NULL != g_config_data_buffer) { /* config data has been sent with this forward open request */
     *extended_error = HandleConfigData(io_connection_object);
     if (kConnectionManagerExtendedStatusCodeSuccess != *extended_error) {
@@ -370,14 +363,13 @@ CipError EstablishIoConnection(
  */
 EipStatus OpenConsumingPointToPointConnection(
   CipConnectionObject *const connection_object,
-  CipCommonPacketFormatData *const common_packet_format_data
-  ) {
+  CipCommonPacketFormatData *const common_packet_format_data) {
 
   int j = 0;
 
-  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;
-  } else if (common_packet_format_data->address_info_item[1].type_id == 0) {
+  } else if(common_packet_format_data->address_info_item[1].type_id == 0) {
     j = 1;
   }
 
@@ -388,8 +380,8 @@ EipStatus OpenConsumingPointToPointConnection(
   CipUsint qos_for_socket = ConnectionObjectGetTToOPriority(connection_object);
   int socket = CreateUdpSocket(kUdpCommuncationDirectionConsuming,
                                &addr,
-                               qos_for_socket);                                            /* the address is only needed for bind used if consuming */
-  if (socket == kEipInvalidSocket) {
+                               qos_for_socket);                                          /* the address is only needed for bind used if consuming */
+  if(socket == kEipInvalidSocket) {
     OPENER_TRACE_ERR(
       "cannot create UDP socket in OpenPointToPointConnection\n");
     return kEipStatusError;
@@ -404,9 +396,9 @@ EipStatus OpenConsumingPointToPointConnection(
     kCipItemIdSocketAddressInfoOriginatorToTarget;
 
   common_packet_format_data->address_info_item[j].sin_port = addr.sin_port;
-  /*TODO should we add our own address here? */
-  common_packet_format_data->address_info_item[j].sin_addr = addr.sin_addr
-                                                             .s_addr;
+/*TODO should we add our own address here? */
+  common_packet_format_data->address_info_item[j].sin_addr =
+    addr.sin_addr.s_addr;
   memset(common_packet_format_data->address_info_item[j].nasin_zero, 0, 8);
   common_packet_format_data->address_info_item[j].sin_family = htons(AF_INET);
 
@@ -415,16 +407,16 @@ EipStatus OpenConsumingPointToPointConnection(
 
 CipError OpenProducingPointToPointConnection(
   CipConnectionObject *connection_object,
-  CipCommonPacketFormatData *common_packet_format_data
-  ) {
+  CipCommonPacketFormatData *common_packet_format_data)
+{
   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
-      == common_packet_format_data->address_info_item[0].type_id) {
+  if(kCipItemIdSocketAddressInfoTargetToOriginator ==
+     common_packet_format_data->address_info_item[0].type_id) {
     port = common_packet_format_data->address_info_item[0].sin_port;
   } else {
-    if (kCipItemIdSocketAddressInfoTargetToOriginator
-        == common_packet_format_data->address_info_item[1].type_id) {
+    if(kCipItemIdSocketAddressInfoTargetToOriginator ==
+       common_packet_format_data->address_info_item[1].type_id) {
       port = common_packet_format_data->address_info_item[1].sin_port;
     }
   }
@@ -436,8 +428,8 @@ CipError OpenProducingPointToPointConnection(
   CipUsint qos_for_socket = ConnectionObjectGetTToOPriority(connection_object);
   int socket = CreateUdpSocket(kUdpCommuncationDirectionProducing,
                                &connection_object->remote_address,
-                               qos_for_socket);                                     /* the address is only needed for bind used if consuming */
-  if (socket == kEipInvalidSocket) {
+                               qos_for_socket);                                                                       /* the address is only needed for bind used if consuming */
+  if(socket == kEipInvalidSocket) {
     OPENER_TRACE_ERR(
       "cannot create UDP socket in OpenPointToPointConnection\n");
     /* *pa_pnExtendedError = 0x0315; miscellaneous*/
@@ -450,18 +442,18 @@ CipError OpenProducingPointToPointConnection(
 
 EipStatus OpenProducingMulticastConnection(
   CipConnectionObject *connection_object,
-  CipCommonPacketFormatData *common_packet_format_data
-  ) {
-  /* Here we look for existing multi-cast IO connections only. */
+  CipCommonPacketFormatData *common_packet_format_data)
+{
+/* Here we look for existing multi-cast IO connections only. */
   CipConnectionObject *existing_connection_object =
     GetExistingProducerIoConnection(true,
                                     connection_object->produced_path.instance_id);
 
   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;
-  } else if (g_common_packet_format_data_item.address_info_item[1].type_id
-             == 0) {
+  } else if(g_common_packet_format_data_item.address_info_item[1].type_id ==
+            0) {
     j = 1;
   }
 
@@ -474,21 +466,20 @@ EipStatus OpenProducingMulticastConnection(
   common_packet_format_data->address_info_item[j].type_id =
     kCipItemIdSocketAddressInfoTargetToOriginator;
 
-  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,
                                    connection_object,
                                    common_packet_format_data);
   } else {
     /* we need to inform our originator on the correct connection id */
-    connection_object->cip_produced_connection_id = existing_connection_object
-                                                    ->
-                                                    cip_produced_connection_id;
+    connection_object->cip_produced_connection_id =
+      existing_connection_object->cip_produced_connection_id;
   }
 
-  /* we have a connection reuse the data and the socket */
+/* we have a connection reuse the data and the socket */
 
-  if (kConnectionObjectInstanceTypeIOExclusiveOwner ==
-      connection_object->instance_type) {
+  if(kConnectionObjectInstanceTypeIOExclusiveOwner ==
+     connection_object->instance_type) {
     /* exclusive owners take the socket and further manage the connection
      * especially in the case of time outs.
      */
@@ -504,14 +495,11 @@ EipStatus OpenProducingMulticastConnection(
   common_packet_format_data->address_info_item[j].length = 16;
 
   connection_object->remote_address.sin_family = AF_INET;
-  connection_object->remote_address.sin_port = common_packet_format_data
-                                               ->address_info_item[j].sin_port
-                                                 = port;
-  connection_object->remote_address.sin_addr.s_addr = common_packet_format_data
-                                                      ->address_info_item[j].
-                                                      sin_addr =
-                                                        g_tcpip.mcast_config.
-                                                        starting_multicast_address;
+  connection_object->remote_address.sin_port =
+    common_packet_format_data->address_info_item[j].sin_port = port;
+  connection_object->remote_address.sin_addr.s_addr =
+    common_packet_format_data->address_info_item[j].sin_addr =
+      g_tcpip.mcast_config.starting_multicast_address;
   memset(common_packet_format_data->address_info_item[j].nasin_zero, 0, 8);
   common_packet_format_data->address_info_item[j].sin_family = htons(AF_INET);
 
@@ -525,31 +513,30 @@ EipStatus OpenProducingMulticastConnection(
  * @param common_packet_format_data Received CPF Data Item.
  * @return kEipStatusOk on success, otherwise kEipStatusError
  */
-EipStatus OpenMulticastConnection(
-  UdpCommuncationDirection direction,
-  CipConnectionObject *connection_object,
-  CipCommonPacketFormatData *common_packet_format_data
-  ) {
+EipStatus OpenMulticastConnection(UdpCommuncationDirection direction,
+                                  CipConnectionObject *connection_object,
+                                  CipCommonPacketFormatData *common_packet_format_data)
+{
   int j = -1;
 
   int address_info_item_which_contains_o_to_t = -1;
   int address_info_item_which_contains_t_to_o = -1;
 
-  if(kCipItemIdSocketAddressInfoOriginatorToTarget
-     == common_packet_format_data->address_info_item[0].type_id) {
+  if(kCipItemIdSocketAddressInfoOriginatorToTarget ==
+     common_packet_format_data->address_info_item[0].type_id) {
     address_info_item_which_contains_o_to_t = 0;
-  } else if(kCipItemIdSocketAddressInfoOriginatorToTarget
-            == common_packet_format_data->address_info_item[1].type_id) {
+  } else if(kCipItemIdSocketAddressInfoOriginatorToTarget ==
+            common_packet_format_data->address_info_item[1].type_id) {
     address_info_item_which_contains_o_to_t = 1;
   } else {
     OPENER_TRACE_INFO("No O->T Sockaddr info available\n");
   }
 
-  if(kCipItemIdSocketAddressInfoTargetToOriginator
-     == common_packet_format_data->address_info_item[0].type_id) {
+  if(kCipItemIdSocketAddressInfoTargetToOriginator ==
+     common_packet_format_data->address_info_item[0].type_id) {
     address_info_item_which_contains_t_to_o = 0;
-  } else if(kCipItemIdSocketAddressInfoTargetToOriginator
-            == common_packet_format_data->address_info_item[1].type_id) {
+  } else if(kCipItemIdSocketAddressInfoTargetToOriginator ==
+            common_packet_format_data->address_info_item[1].type_id) {
     address_info_item_which_contains_t_to_o = 1;
   } else {
     OPENER_TRACE_INFO("No T->O Sockaddr info available\n");
@@ -563,9 +550,9 @@ EipStatus OpenMulticastConnection(
     j = address_info_item_which_contains_t_to_o;
   }
 
-  /*****************/
+/*****************/
 
-  if (-1 == j) {
+  if(-1 == j) {
     OPENER_TRACE_ERR(
       "no suitable addr info item available / O->T: %d, T->O: %d, Selector: %d, direction: %d\n",
       address_info_item_which_contains_o_to_t,
@@ -575,10 +562,9 @@ EipStatus OpenMulticastConnection(
     return kEipStatusError;
   }
 
-  if (kCipItemIdSocketAddressInfoTargetToOriginator ==
-      common_packet_format_data->address_info_item[j].type_id) {                                                  /* we are using an unused item initialize it with the default multicast address */
-    common_packet_format_data->address_info_item[j].sin_family = htons(
-      AF_INET);
+  if(kCipItemIdSocketAddressInfoTargetToOriginator ==
+     common_packet_format_data->address_info_item[j].type_id) {                                                /* we are using an unused item initialize it with the default multicast address */
+    common_packet_format_data->address_info_item[j].sin_family = htons(AF_INET);
     common_packet_format_data->address_info_item[j].sin_port = htons(
       kOpenerEipIoUdpPort);
     common_packet_format_data->address_info_item[j].sin_addr =
@@ -587,31 +573,31 @@ EipStatus OpenMulticastConnection(
     common_packet_format_data->address_info_item[j].length = 16;
   }
 
-  if (htons(AF_INET)
-      != common_packet_format_data->address_info_item[j].sin_family) {
+  if(htons(AF_INET) !=
+     common_packet_format_data->address_info_item[j].sin_family) {
     OPENER_TRACE_ERR(
       "Sockaddr Info Item with wrong sin family value received\n");
     return kEipStatusError;
   }
 
-  /* allocate an unused sockaddr struct to use */
-  struct sockaddr_in socket_address = {0};
+/* allocate an unused sockaddr struct to use */
+  struct sockaddr_in socket_address = { 0 };
   socket_address.sin_family = ntohs(
     common_packet_format_data->address_info_item[j].sin_family);
   socket_address.sin_addr.s_addr =
     common_packet_format_data->address_info_item[j].sin_addr;
-  socket_address.sin_port = common_packet_format_data->address_info_item[j]
-                            .sin_port;
+  socket_address.sin_port =
+    common_packet_format_data->address_info_item[j].sin_port;
 
   CipUsint qos_for_socket = ConnectionObjectGetTToOPriority(connection_object);
   int socket = CreateUdpSocket(direction, &socket_address, qos_for_socket); /* 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");
     return kEipStatusError;
   }
   connection_object->socket[direction] = socket;
 
-  if (direction == kUdpCommuncationDirectionConsuming) {
+  if(direction == kUdpCommuncationDirectionConsuming) {
     common_packet_format_data->address_info_item[j].type_id =
       kCipItemIdSocketAddressInfoOriginatorToTarget;
     connection_object->originator_address = socket_address;
@@ -628,31 +614,29 @@ EipUint16 HandleConfigData(CipConnectionObject *connection_object) {
 
   CipClass *const assembly_class = GetCipClass(kCipAssemblyClassCode);
   EipUint16 connection_manager_status = 0;
-  CipInstance *config_instance = GetCipInstance(
-    assembly_class, connection_object->configuration_path.instance_id);
+  CipInstance *config_instance = GetCipInstance(assembly_class,
+                                                connection_object->configuration_path.instance_id);
 
-  if (0 != g_config_data_length) {
+  if(0 != g_config_data_length) {
     OPENER_ASSERT(NULL != config_instance);
-    if ( ConnectionWithSameConfigPointExists(
-           connection_object->configuration_path.instance_id) ) {
+    if(ConnectionWithSameConfigPointExists(connection_object->configuration_path
+                                           .instance_id) ) {
       /* there is a connected connection with the same config point
        * we have to have the same data as already present in the config point*/
-      CipAttributeStruct *attribute_three = GetCipAttribute(
-        config_instance,
-        3);
+      CipAttributeStruct *attribute_three = GetCipAttribute(config_instance, 3);
       OPENER_ASSERT(NULL != attribute_three);
       CipByteArray *attribute_three_data =
         (CipByteArray *) attribute_three->data;
       OPENER_ASSERT(NULL != attribute_three_data);
-      if (attribute_three_data->length != g_config_data_length) {
+      if(attribute_three_data->length != g_config_data_length) {
         connection_manager_status =
           kConnectionManagerExtendedStatusCodeErrorOwnershipConflict;
         OPENER_TRACE_INFO(
           "Hit an Ownership conflict in cipioconnection.c occurrence 1");
       } else {
         /*FIXME check if this is correct */
-        if ( memcmp(attribute_three_data->data, g_config_data_buffer,
-                    g_config_data_length) ) {
+        if(memcmp(attribute_three_data->data, g_config_data_buffer,
+                  g_config_data_length) ) {
           connection_manager_status =
             kConnectionManagerExtendedStatusCodeErrorOwnershipConflict;
           OPENER_TRACE_INFO(
@@ -662,10 +646,10 @@ EipUint16 HandleConfigData(CipConnectionObject *connection_object) {
     } else {
       /* put the data on the configuration assembly object with the current
          design this can be done rather efficiently */
-      if ( kEipStatusOk
-           != NotifyAssemblyConnectedDataReceived(config_instance,
-                                                  g_config_data_buffer,
-                                                  g_config_data_length) ) {
+      if(kEipStatusOk !=
+         NotifyAssemblyConnectedDataReceived(config_instance,
+                                             g_config_data_buffer,
+                                             g_config_data_length) ) {
         OPENER_TRACE_WARN("Configuration data was invalid\n");
         connection_manager_status =
           kConnectionManagerExtendedStatusCodeInvalidConfigurationApplicationPath;
@@ -683,22 +667,21 @@ void CloseIoConnection(CipConnectionObject *connection_object) {
   ConnectionObjectSetState(connection_object,
                            kConnectionObjectStateNonExistent);
 
-  if ( kConnectionObjectInstanceTypeIOExclusiveOwner ==
-       ConnectionObjectGetInstanceType(connection_object)
-       || kConnectionObjectInstanceTypeIOInputOnly ==
-       ConnectionObjectGetInstanceType(connection_object) ) {
-    if ( ( kConnectionObjectConnectionTypeMulticast
-           == ConnectionObjectGetTToOConnectionType(connection_object) )
-         && (kEipInvalidSocket
-             != connection_object->socket[kUdpCommuncationDirectionProducing]) )
-    {
+  if(kConnectionObjectInstanceTypeIOExclusiveOwner ==
+     ConnectionObjectGetInstanceType(connection_object)
+     || kConnectionObjectInstanceTypeIOInputOnly ==
+     ConnectionObjectGetInstanceType(connection_object) ) {
+    if( (kConnectionObjectConnectionTypeMulticast ==
+         ConnectionObjectGetTToOConnectionType(connection_object) )
+        && (kEipInvalidSocket !=
+            connection_object->socket[kUdpCommuncationDirectionProducing]) ) {
       OPENER_TRACE_INFO(
         "Exclusive Owner or Input Only connection closed - Instance type :%d\n",
         ConnectionObjectGetInstanceType(connection_object) );
       CipConnectionObject *next_non_control_master_connection =
         GetNextNonControlMasterConnection(
           connection_object->produced_path.instance_id);
-      if (NULL != next_non_control_master_connection) {
+      if(NULL != next_non_control_master_connection) {
 
         OPENER_TRACE_INFO("Transfer socket ownership\n");
         next_non_control_master_connection->socket[
@@ -709,12 +692,11 @@ void CloseIoConnection(CipConnectionObject *connection_object) {
           kEipInvalidSocket;
         /* End */
 
-        memcpy( &(next_non_control_master_connection->remote_address),
-                &(connection_object->remote_address),
-                sizeof(next_non_control_master_connection->remote_address) );
-        next_non_control_master_connection->eip_level_sequence_count_producing
-          =
-            connection_object->eip_level_sequence_count_producing;
+        memcpy(&(next_non_control_master_connection->remote_address),
+               &(connection_object->remote_address),
+               sizeof(next_non_control_master_connection->remote_address) );
+        next_non_control_master_connection->eip_level_sequence_count_producing =
+          connection_object->eip_level_sequence_count_producing;
         next_non_control_master_connection->sequence_count_producing =
           connection_object->sequence_count_producing;
         next_non_control_master_connection->transmission_trigger_timer =
@@ -727,8 +709,7 @@ void CloseIoConnection(CipConnectionObject *connection_object) {
     }
   }
 
-  CloseCommunicationChannelsAndRemoveFromActiveConnectionsList(
-    connection_object);
+  CloseCommunicationChannelsAndRemoveFromActiveConnectionsList(connection_object);
 }
 
 void HandleIoConnectionTimeOut(CipConnectionObject *connection_object) {
@@ -743,9 +724,9 @@ void HandleIoConnectionTimeOut(CipConnectionObject *connection_object) {
                                                       CloseEncapsulationSessionBySockAddr);
   }
 
-  if ( kConnectionObjectConnectionTypeMulticast
-       == ConnectionObjectGetTToOConnectionType(connection_object) ) {
-    switch (ConnectionObjectGetInstanceType(connection_object) ) {
+  if(kConnectionObjectConnectionTypeMulticast ==
+     ConnectionObjectGetTToOConnectionType(connection_object) ) {
+    switch(ConnectionObjectGetInstanceType(connection_object) ) {
       case kConnectionObjectInstanceTypeIOExclusiveOwner:
         CloseAllConnectionsForInputWithSameType(
           connection_object->produced_path.instance_id,
@@ -755,12 +736,12 @@ void HandleIoConnectionTimeOut(CipConnectionObject *connection_object) {
           kConnectionObjectInstanceTypeIOListenOnly);
         break;
       case kConnectionObjectInstanceTypeIOInputOnly:
-        if (kEipInvalidSocket
-            != connection_object->socket[kUdpCommuncationDirectionProducing]) { /* we are the controlling input only connection find a new controller*/
+        if(kEipInvalidSocket !=
+           connection_object->socket[kUdpCommuncationDirectionProducing]) {                    /* we are the controlling input only connection find a new controller*/
           CipConnectionObject *next_non_control_master_connection =
             GetNextNonControlMasterConnection(
               connection_object->produced_path.instance_id);
-          if (NULL != next_non_control_master_connection) {
+          if(NULL != next_non_control_master_connection) {
             next_non_control_master_connection->socket[
               kUdpCommuncationDirectionProducing] =
               connection_object->socket[kUdpCommuncationDirectionProducing];
@@ -785,19 +766,19 @@ void HandleIoConnectionTimeOut(CipConnectionObject *connection_object) {
 
 EipStatus SendConnectedData(CipConnectionObject *connection_object) {
 
-  /* 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 */
 
   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*/
+/* 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++;
 
-  /* assembleCPFData */
+/* assembleCPFData */
   common_packet_format_data->item_count = 2;
-  if ( kConnectionObjectTransportClassTriggerTransportClass0 !=
-       ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
-  {                                                                                /* use Sequenced Address Items if not Connection Class 0 */
+  if(kConnectionObjectTransportClassTriggerTransportClass0 !=
+     ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
+  {                                                                                                                                      /* use Sequenced Address Items if not Connection Class 0 */
     common_packet_format_data->address_item.type_id =
       kCipItemIdSequencedAddressItem;
     common_packet_format_data->address_item.length = 8;
@@ -818,35 +799,34 @@ EipStatus SendConnectedData(CipConnectionObject *connection_object) {
     (CipByteArray *) connection_object->producing_instance->attributes->data;
   common_packet_format_data->data_item.length = 0;
 
-  /* notify the application that data will be sent immediately after the call */
-  if ( BeforeAssemblyDataSend(connection_object->producing_instance) ) {
+/* notify the application that data will be sent immediately after the call */
+  if(BeforeAssemblyDataSend(connection_object->producing_instance) ) {
     /* the data has changed increase sequence counter */
     connection_object->sequence_count_producing++;
   }
 
-  /* set AddressInfo Items to invalid Type */
+/* set AddressInfo Items to invalid Type */
   common_packet_format_data->address_info_item[0].type_id = 0;
   common_packet_format_data->address_info_item[1].type_id = 0;
 
   ENIPMessage outgoing_message;
   InitializeENIPMessage(&outgoing_message);
-  AssembleIOMessage(common_packet_format_data,
-                    &outgoing_message);
+  AssembleIOMessage(common_packet_format_data, &outgoing_message);
 
   MoveMessageNOctets(-2, &outgoing_message);
-  common_packet_format_data->data_item.length = producing_instance_attributes
-                                                ->length;
+  common_packet_format_data->data_item.length =
+    producing_instance_attributes->length;
 #ifdef OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER
   bool is_heartbeat = (common_packet_format_data->data_item.length == 0);
 
 
   if(!is_heartbeat) {
-      common_packet_format_data->data_item.length += 4;
+    common_packet_format_data->data_item.length += 4;
   }
 #endif /* OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER */
 
-  if (kConnectionObjectTransportClassTriggerTransportClass1 ==
-      ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
+  if(kConnectionObjectTransportClassTriggerTransportClass1 ==
+     ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
   {
     common_packet_format_data->data_item.length += 2;
     AddIntToMessage(common_packet_format_data->data_item.length,
@@ -860,8 +840,8 @@ EipStatus SendConnectedData(CipConnectionObject *connection_object) {
 
 #ifdef OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER
   if(!is_heartbeat) {
-      AddDintToMessage( g_run_idle_state,
-                        &outgoing_message );
+    AddDintToMessage( g_run_idle_state,
+                      &outgoing_message );
   }
 #endif /* OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER */
 
@@ -871,30 +851,27 @@ EipStatus SendConnectedData(CipConnectionObject *connection_object) {
 
   outgoing_message.current_message_position +=
     producing_instance_attributes->length;
-  outgoing_message.used_message_length +=
-    producing_instance_attributes->length;
+  outgoing_message.used_message_length += producing_instance_attributes->length;
 
-  return SendUdpData(
-    &connection_object->remote_address,
-    connection_object->socket[kUdpCommuncationDirectionProducing],
-    &outgoing_message);
+  return SendUdpData(&connection_object->remote_address,
+                     connection_object->socket[
+                       kUdpCommuncationDirectionProducing],
+                     &outgoing_message);
 }
 
-EipStatus HandleReceivedIoConnectionData(
-  CipConnectionObject *connection_object,
-  const EipUint8 *data,
-  EipUint16 data_length
-  ) {
+EipStatus HandleReceivedIoConnectionData(CipConnectionObject *connection_object,
+                                         const EipUint8 *data,
+                                         EipUint16 data_length) {
 
   OPENER_TRACE_INFO("Starting data length: %d\n", data_length);
   bool no_new_data = false;
-  /* check class 1 sequence number*/
-  if (kConnectionObjectTransportClassTriggerTransportClass1 ==
-      ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
+/* check class 1 sequence number*/
+  if(kConnectionObjectTransportClassTriggerTransportClass1 ==
+     ConnectionObjectGetTransportClassTriggerTransportClass(connection_object) )
   {
-    EipUint16 sequence_buffer = GetIntFromMessage( &(data) );
-    if ( SEQ_LEQ16(sequence_buffer,
-                   connection_object->sequence_count_consuming) ) {
+    EipUint16 sequence_buffer = GetUintFromMessage(&(data) );
+    if(SEQ_LEQ16(sequence_buffer,
+                 connection_object->sequence_count_consuming) ) {
       no_new_data = true;
     }
     connection_object->sequence_count_consuming = sequence_buffer;
@@ -902,10 +879,10 @@ EipStatus HandleReceivedIoConnectionData(
   }
 
   OPENER_TRACE_INFO("data length after sequence count: %d\n", data_length);
-  if (data_length > 0) {
+  if(data_length > 0) {
     /* we have no heartbeat connection */
 #ifdef OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER
-    EipUint32 nRunIdleBuf = GetDintFromMessage( &(data) );
+    EipUint32 nRunIdleBuf = GetUdintFromMessage( &(data) );
     OPENER_TRACE_INFO("Run/Idle handler: 0x%x\n", nRunIdleBuf);
     const uint32_t kRunBitMask = 0x0001;
     if( (kRunBitMask & nRunIdleBuf) == 1 ) {
@@ -924,9 +901,9 @@ EipStatus HandleReceivedIoConnectionData(
       return kEipStatusOk;
     }
 
-    if (NotifyAssemblyConnectedDataReceived(
-          connection_object->consuming_instance, (EipUint8 *const)data,
-          data_length) != 0) {
+    if(NotifyAssemblyConnectedDataReceived(connection_object->consuming_instance,
+                                           (EipUint8 *const ) data,
+                                           data_length) != 0) {
       return kEipStatusError;
     }
   }
@@ -936,7 +913,7 @@ EipStatus HandleReceivedIoConnectionData(
 CipError OpenCommunicationChannels(CipConnectionObject *connection_object) {
 
   CipError cip_error = kCipErrorSuccess;
-  /*get pointer to the CPF data, currently we have just one global instance of the struct. This may change in the future*/
+/*get pointer to the CPF data, currently we have just one global instance of the struct. This may change in the future*/
   CipCommonPacketFormatData *common_packet_format_data =
     &g_common_packet_format_data_item;
 
@@ -946,43 +923,43 @@ CipError OpenCommunicationChannels(CipConnectionObject *connection_object) {
   ConnectionObjectConnectionType target_to_originator_connection_type =
     ConnectionObjectGetTToOConnectionType(connection_object);
 
-  /* open a connection "point to point" or "multicast" based on the ConnectionParameter */
-  if (originator_to_target_connection_type ==
-      kConnectionObjectConnectionTypeMulticast)                                         /* Multicast consuming */
+/* open a connection "point to point" or "multicast" based on the ConnectionParameter */
+  if(originator_to_target_connection_type ==
+     kConnectionObjectConnectionTypeMulticast)                                       /* Multicast consuming */
   {
-    if (OpenMulticastConnection(kUdpCommuncationDirectionConsuming,
-                                connection_object, common_packet_format_data)
-        != kEipStatusError) {
+    if(OpenMulticastConnection(kUdpCommuncationDirectionConsuming,
+                               connection_object,
+                               common_packet_format_data) != kEipStatusError) {
       OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
       return kCipErrorConnectionFailure;
     }
-  } else if (originator_to_target_connection_type ==
-             kConnectionObjectConnectionTypePointToPoint)                                  /* Point to Point consuming */
+  } else if(originator_to_target_connection_type ==
+            kConnectionObjectConnectionTypePointToPoint)                                       /* Point to Point consuming */
   {
-    if (OpenConsumingPointToPointConnection(connection_object,
-                                            common_packet_format_data)
-        == kEipStatusError) {
+    if(OpenConsumingPointToPointConnection(connection_object,
+                                           common_packet_format_data) ==
+       kEipStatusError) {
       OPENER_TRACE_ERR("error in PointToPoint consuming connection\n");
       return kCipErrorConnectionFailure;
     }
   }
 
-  if (target_to_originator_connection_type ==
-      kConnectionObjectConnectionTypeMulticast)                                         /* Multicast producing */
+  if(target_to_originator_connection_type ==
+     kConnectionObjectConnectionTypeMulticast)                                       /* Multicast producing */
   {
-    if (OpenProducingMulticastConnection(connection_object,
-                                         common_packet_format_data)
-        == kEipStatusError) {
+    if(OpenProducingMulticastConnection(connection_object,
+                                        common_packet_format_data) ==
+       kEipStatusError) {
       OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
       return kCipErrorConnectionFailure;
     }
-  } else if (target_to_originator_connection_type ==
-             kConnectionObjectConnectionTypePointToPoint)                                  /* Point to Point producing */
+  } else if(target_to_originator_connection_type ==
+            kConnectionObjectConnectionTypePointToPoint)                                       /* Point to Point producing */
   {
 
-    if (OpenProducingPointToPointConnection(connection_object,
-                                            common_packet_format_data)
-        != kEipStatusOk) {
+    if(OpenProducingPointToPointConnection(connection_object,
+                                           common_packet_format_data) !=
+       kEipStatusOk) {
       OPENER_TRACE_ERR("error in PointToPoint producing connection\n");
       return kCipErrorConnectionFailure;
     }
@@ -992,14 +969,12 @@ CipError OpenCommunicationChannels(CipConnectionObject *connection_object) {
 
 void CloseCommunicationChannelsAndRemoveFromActiveConnectionsList(
   CipConnectionObject *connection_object) {
-  CloseUdpSocket(
-    connection_object->socket[kUdpCommuncationDirectionConsuming]);
+  CloseUdpSocket(connection_object->socket[kUdpCommuncationDirectionConsuming]);
 
   connection_object->socket[kUdpCommuncationDirectionConsuming] =
     kEipInvalidSocket;
 
-  CloseUdpSocket(
-    connection_object->socket[kUdpCommuncationDirectionProducing]);
+  CloseUdpSocket(connection_object->socket[kUdpCommuncationDirectionProducing]);
 
   connection_object->socket[kUdpCommuncationDirectionProducing] =
     kEipInvalidSocket;

+ 120 - 127
source/src/enet_encap/cpf.c

@@ -30,42 +30,42 @@ static void InitializeMessageRouterResponse(
   InitializeENIPMessage(&message_router_response->message);
 }
 
-EipStatus NotifyCommonPacketFormat
-(
-  const EncapsulationData *const received_data,
-  const struct sockaddr *const originator_address,
-  ENIPMessage *const outgoing_message) {
+EipStatus NotifyCommonPacketFormat(const EncapsulationData *const received_data,
+                                   const struct sockaddr *const originator_address,
+                                   ENIPMessage *const outgoing_message) {
   EipStatus return_value = kEipStatusError;
   CipMessageRouterResponse message_router_response;
   InitializeMessageRouterResponse(&message_router_response);
 
-  if (kEipStatusError == ( return_value = CreateCommonPacketFormatStructure(
-                             received_data->
-                             current_communication_buffer_position,
-                             received_data->data_length,
-                             &g_common_packet_format_data_item) ) ) {
+  if(kEipStatusError
+     == (return_value =
+           CreateCommonPacketFormatStructure(received_data->
+                                             current_communication_buffer_position,
+                                             received_data->data_length,
+                                             &
+                                             g_common_packet_format_data_item) ) )
+  {
     OPENER_TRACE_ERR("notifyCPF: error from createCPFstructure\n");
   } else {
-    return_value = kEipStatusOkSend;  /* In cases of errors we normally need to send an error response */
-    if (g_common_packet_format_data_item.address_item.type_id
-        == kCipItemIdNullAddress) /* check if NullAddressItem received, otherwise it is no unconnected message and should not be here*/
-    {     /* found null address item*/
-      if (g_common_packet_format_data_item.data_item.type_id
-          == kCipItemIdUnconnectedDataItem) { /* unconnected data item received*/
+    return_value = kEipStatusOkSend; /* In cases of errors we normally need to send an error response */
+    if(g_common_packet_format_data_item.address_item.type_id ==
+       kCipItemIdNullAddress)                                                          /* check if NullAddressItem received, otherwise it is no unconnected message and should not be here*/
+    { /* found null address item*/
+      if(g_common_packet_format_data_item.data_item.type_id ==
+         kCipItemIdUnconnectedDataItem) {                                                       /* unconnected data item received*/
         return_value = NotifyMessageRouter(
           g_common_packet_format_data_item.data_item.data,
           g_common_packet_format_data_item.data_item.length,
           &message_router_response,
           originator_address,
           received_data->session_handle);
-        if (return_value != kEipStatusError) {
+        if(return_value != kEipStatusError) {
           SkipEncapsulationHeader(outgoing_message);
           /* TODO: Here we get the status. What to do? kEipStatusError from AssembleLinearMessage().
            *  Its not clear how to transport this error information to the requester. */
-          EipStatus status = AssembleLinearMessage(
-            &message_router_response,
-            &g_common_packet_format_data_item,
-            outgoing_message);
+          EipStatus status = AssembleLinearMessage(&message_router_response,
+                                                   &g_common_packet_format_data_item,
+                                                   outgoing_message);
 
           /* Save pointer and move to start for Encapusulation Header */
           CipOctet *buffer = outgoing_message->current_message_position;
@@ -112,28 +112,28 @@ EipStatus NotifyConnectedCommonPacketFormat(
 
   EipStatus return_value = CreateCommonPacketFormatStructure(
     received_data->current_communication_buffer_position,
-    received_data->data_length, &g_common_packet_format_data_item);
+    received_data->data_length,
+    &g_common_packet_format_data_item);
 
-  if (kEipStatusError == return_value) {
+  if(kEipStatusError == return_value) {
     OPENER_TRACE_ERR("notifyConnectedCPF: error from createCPFstructure\n");
   } else {
     return_value = kEipStatusError; /* For connected explicit messages status always has to be 0*/
-    if (g_common_packet_format_data_item.address_item.type_id
-        == kCipItemIdConnectionAddress) /* check if ConnectedAddressItem received, otherwise it is no connected message and should not be here*/
-    {     /* ConnectedAddressItem item */
+    if(g_common_packet_format_data_item.address_item.type_id ==
+       kCipItemIdConnectionAddress)                                                          /* check if ConnectedAddressItem received, otherwise it is no connected message and should not be here*/
+    { /* ConnectedAddressItem item */
       CipConnectionObject *connection_object = GetConnectedObject(
-        g_common_packet_format_data_item.address_item.data
-        .connection_identifier);
-      if (NULL != connection_object) {
+        g_common_packet_format_data_item.address_item.data.connection_identifier);
+      if(NULL != connection_object) {
         /* reset the watchdog timer */
         ConnectionObjectResetInactivityWatchdogTimerValue(connection_object);
 
         /*TODO check connection id  and sequence count */
-        if (g_common_packet_format_data_item.data_item.type_id
-            == kCipItemIdConnectedDataItem) { /* connected data item received*/
+        if(g_common_packet_format_data_item.data_item.type_id ==
+           kCipItemIdConnectedDataItem) {                                                       /* connected data item received*/
           EipUint8 *buffer = g_common_packet_format_data_item.data_item.data;
           g_common_packet_format_data_item.address_item.data.sequence_number =
-            (EipUint32) GetIntFromMessage( (const EipUint8 **const)&buffer );
+            GetUintFromMessage( (const EipUint8 **const ) &buffer );
           OPENER_TRACE_INFO(
             "Class 3 sequence number: %d, last sequence number: %d\n",
             g_common_packet_format_data_item.address_item.data.sequence_number,
@@ -165,23 +165,22 @@ EipStatus NotifyConnectedCommonPacketFormat(
 
           CipMessageRouterResponse message_router_response;
           InitializeMessageRouterResponse(&message_router_response);
-          return_value = NotifyMessageRouter(
-            buffer,
-            g_common_packet_format_data_item.data_item.length - 2,
-            &message_router_response,
-            originator_address,
-            received_data->session_handle);
-
-          if (return_value != kEipStatusError) {
-            g_common_packet_format_data_item.address_item.data
-            .connection_identifier = connection_object
-                                     ->cip_produced_connection_id;
+          return_value = NotifyMessageRouter(buffer,
+                                             g_common_packet_format_data_item.data_item.length - 2,
+                                             &message_router_response,
+                                             originator_address,
+                                             received_data->session_handle);
+
+          if(return_value != kEipStatusError) {
+            g_common_packet_format_data_item.address_item.data.
+            connection_identifier =
+              connection_object->cip_produced_connection_id;
             SkipEncapsulationHeader(outgoing_message);
             /* TODO: Here we get the status. What to do? kEipStatusError from AssembleLinearMessage().
              *  Its not clear how to transport this error information to the requester. */
-            EipStatus status = AssembleLinearMessage(
-              &message_router_response, &g_common_packet_format_data_item,
-              outgoing_message);
+            EipStatus status = AssembleLinearMessage(&message_router_response,
+                                                     &g_common_packet_format_data_item,
+                                                     outgoing_message);
 
             CipOctet *buffer = outgoing_message->current_message_position;
             outgoing_message->current_message_position =
@@ -226,53 +225,52 @@ EipStatus NotifyConnectedCommonPacketFormat(
  *   @return kEipStatusOk .. success
  *             kEipStatusError .. error
  */
-EipStatus CreateCommonPacketFormatStructure(
-  const EipUint8 *data,
-  size_t data_length,
-  CipCommonPacketFormatData *common_packet_format_data) {
+EipStatus CreateCommonPacketFormatStructure(const EipUint8 *data,
+                                            size_t data_length,
+                                            CipCommonPacketFormatData *common_packet_format_data)
+{
 
   common_packet_format_data->address_info_item[0].type_id = 0;
   common_packet_format_data->address_info_item[1].type_id = 0;
 
   int length_count = 0;
-  CipUint item_count = GetIntFromMessage(&data);
+  CipUint item_count = GetUintFromMessage(&data);
   OPENER_ASSERT(4U >= item_count);/* Sanitizing data - probably needs to be changed for productive code */
   common_packet_format_data->item_count = item_count;
   length_count += 2;
-  if (common_packet_format_data->item_count >= 1U) {
-    common_packet_format_data->address_item.type_id = GetIntFromMessage(&data);
-    common_packet_format_data->address_item.length = GetIntFromMessage(&data);
+  if(common_packet_format_data->item_count >= 1U) {
+    common_packet_format_data->address_item.type_id = GetUintFromMessage(&data);
+    common_packet_format_data->address_item.length = GetUintFromMessage(&data);
     length_count += 4;
-    if (common_packet_format_data->address_item.length >= 4) {
+    if(common_packet_format_data->address_item.length >= 4) {
       common_packet_format_data->address_item.data.connection_identifier =
-        GetDintFromMessage(&data);
+        GetUdintFromMessage(&data);
       length_count += 4;
     }
-    if (common_packet_format_data->address_item.length == 8) {
+    if(common_packet_format_data->address_item.length == 8) {
       common_packet_format_data->address_item.data.sequence_number =
-        GetDintFromMessage(&data);
+        GetUdintFromMessage(&data);
       length_count += 4;
     }
   }
-  if (common_packet_format_data->item_count >= 2) {
-    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.data = (EipUint8 *)data;
+  if(common_packet_format_data->item_count >= 2) {
+    common_packet_format_data->data_item.type_id = GetUintFromMessage(&data);
+    common_packet_format_data->data_item.length = GetUintFromMessage(&data);
+    common_packet_format_data->data_item.data = (EipUint8 *) data;
     data += common_packet_format_data->data_item.length;
     length_count += (4 + common_packet_format_data->data_item.length);
 
-    for (size_t j = 0; j < (common_packet_format_data->item_count - 2); j++) /* TODO there needs to be a limit check here???*/
+    for(size_t j = 0; j < (common_packet_format_data->item_count - 2); j++) /* TODO there needs to be a limit check here???*/
     {
       common_packet_format_data->address_info_item[j].type_id =
-        GetIntFromMessage(
-          &data);
+        GetIntFromMessage(&data);
       OPENER_TRACE_INFO("Sockaddr type id: %x\n",
                         common_packet_format_data->address_info_item[j].type_id);
       length_count += 2;
-      if ( (common_packet_format_data->address_info_item[j].type_id
-            == kCipItemIdSocketAddressInfoOriginatorToTarget)
-           || (common_packet_format_data->address_info_item[j].type_id
-               == kCipItemIdSocketAddressInfoTargetToOriginator) ) {
+      if( (common_packet_format_data->address_info_item[j].type_id ==
+           kCipItemIdSocketAddressInfoOriginatorToTarget)
+          || (common_packet_format_data->address_info_item[j].type_id ==
+              kCipItemIdSocketAddressInfoTargetToOriginator) ) {
         common_packet_format_data->address_info_item[j].length =
           GetIntFromMessage(&data);
         common_packet_format_data->address_info_item[j].sin_family =
@@ -280,8 +278,8 @@ EipStatus CreateCommonPacketFormatStructure(
         common_packet_format_data->address_info_item[j].sin_port =
           GetIntFromMessage(&data);
         common_packet_format_data->address_info_item[j].sin_addr =
-          GetDintFromMessage(&data);
-        for (size_t i = 0; i < 8; i++) {
+          GetUdintFromMessage(&data);
+        for(size_t i = 0; i < 8; i++) {
           common_packet_format_data->address_info_item[j].nasin_zero[i] = *data;
           data++;
         }
@@ -293,18 +291,18 @@ EipStatus CreateCommonPacketFormatStructure(
     }
   }
   /* set the addressInfoItems to not set if they were not received */
-  if (common_packet_format_data->item_count < 4) {
+  if(common_packet_format_data->item_count < 4) {
     common_packet_format_data->address_info_item[1].type_id = 0;
-    if (common_packet_format_data->item_count < 3) {
+    if(common_packet_format_data->item_count < 3) {
       common_packet_format_data->address_info_item[0].type_id = 0;
     }
   }
-  if (length_count == data_length) { /* length of data is equal to length of Addr and length of Data */
+  if(length_count == data_length) { /* length of data is equal to length of Addr and length of Data */
     return kEipStatusOk;
   } else {
     OPENER_TRACE_WARN(
       "something is wrong with the length in Message Router @ CreateCommonPacketFormatStructure\n");
-    if (common_packet_format_data->item_count > 2) {
+    if(common_packet_format_data->item_count > 2) {
       /* there is an optional packet in data stream which is not sockaddr item */
       return kEipStatusOk;
     } else { /* something with the length was wrong */
@@ -425,11 +423,11 @@ void EncodeDataItemData(
 void EncodeConnectedDataItemLength(
   const CipMessageRouterResponse *const message_router_response,
   ENIPMessage *const outgoing_message) {
-  AddIntToMessage( (EipUint16) ( message_router_response->message.
-                                 used_message_length + 4 + 2                                  /* TODO: Magic numbers */
-                                 + (2 *
-                                    message_router_response->
-                                    size_of_additional_status) ),
+  AddIntToMessage( (EipUint16) (message_router_response->message.
+                                used_message_length + 4 + 2                                 /* TODO: Magic numbers */
+                                + (2 *
+                                   message_router_response->
+                                   size_of_additional_status) ),
                    outgoing_message );
 }
 
@@ -443,7 +441,7 @@ void EncodeSequenceNumber(
   const CipCommonPacketFormatData *const common_packet_format_data_item,
   ENIPMessage *const outgoing_message) {
   AddIntToMessage(
-    (EipUint16) common_packet_format_data_item->address_item.data.sequence_number,
+     (EipUint16) common_packet_format_data_item->address_item.data.sequence_number,
     outgoing_message );
 }
 
@@ -506,9 +504,9 @@ void EncodeExtendedStatusLength(
 void EncodeExtendedStatusDataItems(
   const CipMessageRouterResponse *const message_router_response,
   ENIPMessage *const outgoing_message) {
-  for (size_t i = 0;
-       i < message_router_response->size_of_additional_status &&
-       i < MAX_SIZE_OF_ADD_STATUS; i++) {
+  for(size_t i = 0;
+      i < message_router_response->size_of_additional_status &&
+      i < MAX_SIZE_OF_ADD_STATUS; i++) {
     AddIntToMessage(message_router_response->additional_status[i],
                     outgoing_message);
   }
@@ -541,11 +539,11 @@ void EncodeExtendedStatus(
 void EncodeUnconnectedDataItemLength(
   const CipMessageRouterResponse *const message_router_response,
   ENIPMessage *const outgoing_message) {
-  AddIntToMessage( (EipUint16) ( message_router_response->message.
-                                 used_message_length + 4                                  /* TODO: Magic number */
-                                 + (2 *
-                                    message_router_response->
-                                    size_of_additional_status) ),
+  AddIntToMessage( (EipUint16) (message_router_response->message.
+                                used_message_length + 4                                 /* TODO: Magic number */
+                                + (2 *
+                                   message_router_response->
+                                   size_of_additional_status) ),
                    outgoing_message );
 }
 
@@ -575,10 +573,9 @@ void EncodeMessageRouterResponseData(
  * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
  * @param outgoing_message The outgoing message object
  */
-void EncodeSockaddrInfoItemTypeId(
-  int item_type,
-  const CipCommonPacketFormatData *const common_packet_format_data_item,
-  ENIPMessage *const outgoing_message) {
+void EncodeSockaddrInfoItemTypeId(int item_type,
+                                  const CipCommonPacketFormatData *const common_packet_format_data_item,
+                                  ENIPMessage *const outgoing_message) {
   OPENER_ASSERT(item_type == 0 || item_type == 1);
   AddIntToMessage(
     common_packet_format_data_item->address_info_item[item_type].type_id,
@@ -592,10 +589,9 @@ void EncodeSockaddrInfoItemTypeId(
  * @param common_packet_format_data_item The Common Packet Format data structure from which the message is constructed
  * @param outgoing_message The outgoing message object
  */
-void EncodeSockaddrInfoLength(
-  int item_type,
-  const CipCommonPacketFormatData *const common_packet_format_data_item,
-  ENIPMessage *const outgoing_message) {
+void EncodeSockaddrInfoLength(int item_type,
+                              const CipCommonPacketFormatData *const common_packet_format_data_item,
+                              ENIPMessage *const outgoing_message) {
   AddIntToMessage(
     common_packet_format_data_item->address_info_item[item_type].length,
     outgoing_message);
@@ -606,7 +602,7 @@ EipStatus AssembleLinearMessage(
   const CipCommonPacketFormatData *const common_packet_format_data_item,
   ENIPMessage *const outgoing_message) {
 
-  if (message_router_response) {
+  if(message_router_response) {
     /* add Interface Handle and Timeout = 0 -> only for SendRRData and SendUnitData necessary */
     AddDintToMessage(0, outgoing_message);
     AddIntToMessage(0, outgoing_message);
@@ -615,7 +611,7 @@ EipStatus AssembleLinearMessage(
   EncodeItemCount(common_packet_format_data_item, outgoing_message);
 
   /* process Address Item */
-  switch (common_packet_format_data_item->address_item.type_id) {
+  switch(common_packet_format_data_item->address_item.type_id) {
     case kCipItemIdNullAddress: {
       EncodeNullAddressItem(outgoing_message);
       break;
@@ -636,17 +632,16 @@ EipStatus AssembleLinearMessage(
   }
 
   /* process Data Item */
-  if ( (common_packet_format_data_item->data_item.type_id
-        == kCipItemIdUnconnectedDataItem)
-       || (common_packet_format_data_item->data_item.type_id
-           == kCipItemIdConnectedDataItem) ) {
+  if( (common_packet_format_data_item->data_item.type_id ==
+       kCipItemIdUnconnectedDataItem)
+      || (common_packet_format_data_item->data_item.type_id ==
+          kCipItemIdConnectedDataItem) ) {
 
-    if (message_router_response) {
-      EncodeDataItemType(common_packet_format_data_item,
-                         outgoing_message);
+    if(message_router_response) {
+      EncodeDataItemType(common_packet_format_data_item, outgoing_message);
 
-      if (common_packet_format_data_item->data_item.type_id
-          == kCipItemIdConnectedDataItem) { /* Connected Item */
+      if(common_packet_format_data_item->data_item.type_id ==
+         kCipItemIdConnectedDataItem) {                                                      /* Connected Item */
         EncodeConnectedDataItemLength(message_router_response,
                                       outgoing_message);
         EncodeSequenceNumber(&g_common_packet_format_data_item,
@@ -666,14 +661,11 @@ EipStatus AssembleLinearMessage(
       EncodeMessageRouterResponseData(message_router_response,
                                       outgoing_message);
     } else { /* connected IO Message to send */
-      EncodeDataItemType(common_packet_format_data_item,
-                         outgoing_message);
+      EncodeDataItemType(common_packet_format_data_item, outgoing_message);
 
-      EncodeDataItemLength(common_packet_format_data_item,
-                           outgoing_message);
+      EncodeDataItemLength(common_packet_format_data_item, outgoing_message);
 
-      EncodeDataItemData(common_packet_format_data_item,
-                         outgoing_message);
+      EncodeDataItemData(common_packet_format_data_item, outgoing_message);
     }
   }
 
@@ -682,15 +674,16 @@ EipStatus AssembleLinearMessage(
    * EtherNet/IP specification doesn't demand it, but there are EIP
    * devices which depend on CPF items to appear in the order of their
    * ID number */
-  for (int type = kCipItemIdSocketAddressInfoOriginatorToTarget;
-       type <= kCipItemIdSocketAddressInfoTargetToOriginator; type++) {
-    for (int j = 0; j < 2; j++) {
-      if (common_packet_format_data_item->address_info_item[j].type_id
-          == type) {
-        EncodeSockaddrInfoItemTypeId(
-          j, common_packet_format_data_item, outgoing_message);
-
-        EncodeSockaddrInfoLength(j,common_packet_format_data_item,
+  for(int type = kCipItemIdSocketAddressInfoOriginatorToTarget;
+      type <= kCipItemIdSocketAddressInfoTargetToOriginator; type++) {
+    for(int j = 0; j < 2; j++) {
+      if(common_packet_format_data_item->address_info_item[j].type_id == type) {
+        EncodeSockaddrInfoItemTypeId(j,
+                                     common_packet_format_data_item,
+                                     outgoing_message);
+
+        EncodeSockaddrInfoLength(j,
+                                 common_packet_format_data_item,
                                  outgoing_message);
 
         EncapsulateIpAddress(
@@ -698,8 +691,9 @@ EipStatus AssembleLinearMessage(
           common_packet_format_data_item->address_info_item[j].sin_addr,
           outgoing_message);
 
-        FillNextNMessageOctetsWithValueAndMoveToNextPosition(
-          0, 8, outgoing_message);
+        FillNextNMessageOctetsWithValueAndMoveToNextPosition(0,
+                                                             8,
+                                                             outgoing_message);
         break;
       }
     }
@@ -710,6 +704,5 @@ EipStatus AssembleLinearMessage(
 void AssembleIOMessage(
   const CipCommonPacketFormatData *const common_packet_format_data_item,
   ENIPMessage *const outgoing_message) {
-  AssembleLinearMessage(0, common_packet_format_data_item,
-                        outgoing_message);
+  AssembleLinearMessage(0, common_packet_format_data_item, outgoing_message);
 }

+ 151 - 157
source/src/enet_encap/encap.c

@@ -34,26 +34,28 @@ const int kListIdentityDefaultDelayTime = 2000; /**< Default delay time for List
 const int kListIdentityMinimumDelayTime = 500; /**< Minimum delay time for List Identity response */
 
 typedef enum {
-  kSessionStatusInvalid = -1, kSessionStatusValid = 0
+  kSessionStatusInvalid = -1,
+  kSessionStatusValid = 0
 } SessionStatus;
 
 const int kSenderContextSize = 8; /**< size of sender context in encapsulation header*/
 
 /** @brief definition of known encapsulation commands */
 typedef enum {
-  kEncapsulationCommandNoOperation = 0x0000,       /**< only allowed for TCP */
-  kEncapsulationCommandListServices = 0x0004,       /**< allowed for both UDP and TCP */
-  kEncapsulationCommandListIdentity = 0x0063,       /**< allowed for both UDP and TCP */
-  kEncapsulationCommandListInterfaces = 0x0064,       /**< optional, allowed for both UDP and TCP */
-  kEncapsulationCommandRegisterSession = 0x0065,       /**< only allowed for TCP */
-  kEncapsulationCommandUnregisterSession = 0x0066,       /**< only allowed for TCP */
-  kEncapsulationCommandSendRequestReplyData = 0x006F,       /**< only allowed for TCP */
-  kEncapsulationCommandSendUnitData = 0x0070       /**< only allowed for TCP */
+  kEncapsulationCommandNoOperation = 0x0000, /**< only allowed for TCP */
+  kEncapsulationCommandListServices = 0x0004, /**< allowed for both UDP and TCP */
+  kEncapsulationCommandListIdentity = 0x0063, /**< allowed for both UDP and TCP */
+  kEncapsulationCommandListInterfaces = 0x0064, /**< optional, allowed for both UDP and TCP */
+  kEncapsulationCommandRegisterSession = 0x0065, /**< only allowed for TCP */
+  kEncapsulationCommandUnregisterSession = 0x0066, /**< only allowed for TCP */
+  kEncapsulationCommandSendRequestReplyData = 0x006F, /**< only allowed for TCP */
+  kEncapsulationCommandSendUnitData = 0x0070 /**< only allowed for TCP */
 } EncapsulationCommand;
 
 /** @brief definition of capability flags */
 typedef enum {
-  kCapabilityFlagsCipTcp = 0x0020, kCapabilityFlagsCipUdpClass0or1 = 0x0100
+  kCapabilityFlagsCipTcp = 0x0020,
+  kCapabilityFlagsCipUdpClass0or1 = 0x0100
 } CapabilityFlags;
 
 #define ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES 2 /**< According to EIP spec at least 2 delayed message requests should be supported */
@@ -65,8 +67,8 @@ typedef enum {
 
 /** @brief Delayed Encapsulation Message structure */
 typedef struct {
-  EipInt32 time_out;       /**< time out in milli seconds */
-  int socket;       /**< associated socket */
+  EipInt32 time_out; /**< time out in milli seconds */
+  int socket; /**< associated socket */
   struct sockaddr_in receiver;
   ENIPMessage outgoing_message;
 } DelayedEncapsulationMessage;
@@ -119,12 +121,11 @@ void EncapsulationInit(void) {
   srand(g_tcpip.interface_configuration.ip_address);
 
   /* initialize Sessions to invalid == free session */
-  for (size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++) {
+  for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++) {
     g_registered_sessions[i] = kEipInvalidSocket;
   }
 
-  for (size_t i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES;
-       i++) {
+  for(size_t i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
     g_delayed_encapsulation_messages[i].socket = kEipInvalidSocket;
   }
 
@@ -133,39 +134,37 @@ void EncapsulationInit(void) {
   g_service_information.type_code = kCipItemIdListServiceResponse;
   g_service_information.length = sizeof(g_service_information);
   g_service_information.encapsulation_protocol_version = 1;
-  g_service_information.capability_flags = kCapabilityFlagsCipTcp
-                                           | kCapabilityFlagsCipUdpClass0or1;
+  g_service_information.capability_flags = kCapabilityFlagsCipTcp |
+                                           kCapabilityFlagsCipUdpClass0or1;
   snprintf( (char *) g_service_information.name_of_service,
-            sizeof(g_service_information.name_of_service),
-            "Communications" );
+            sizeof(g_service_information.name_of_service), "Communications" );
 }
 
-EipStatus HandleReceivedExplictTcpData
-(
-  int socket,
-  EipUint8 *buffer,
-  size_t length,
-  int *remaining_bytes,
-  struct sockaddr *originator_address,
-  ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedExplictTcpData(int socket,
+                                       EipUint8 *buffer,
+                                       size_t length,
+                                       int *remaining_bytes,
+                                       struct sockaddr *originator_address,
+                                       ENIPMessage *const outgoing_message) {
   OPENER_TRACE_INFO("Handles data for TCP socket: %d\n", socket);
   EipStatus return_value = kEipStatusOk;
   EncapsulationData encapsulation_data = { 0 };
   /* eat the encapsulation header*/
   /* the structure contains a pointer to the encapsulated data*/
   /* returns how many bytes are left after the encapsulated data*/
-  *remaining_bytes = CreateEncapsulationStructure(buffer, length,
+  *remaining_bytes = CreateEncapsulationStructure(buffer,
+                                                  length,
                                                   &encapsulation_data);
 
-  if (kEncapsulationHeaderOptionsFlag == encapsulation_data.options)       /*TODO generate appropriate error response*/
+  if(kEncapsulationHeaderOptionsFlag == encapsulation_data.options) /*TODO generate appropriate error response*/
   {
-    if (*remaining_bytes >= 0)             /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
+    if(*remaining_bytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
     {
       /* full package or more received */
       encapsulation_data.status = kEncapsulationProtocolSuccess;
       return_value = kEipStatusOkSend;
       /* most of these functions need a reply to be send */
-      switch (encapsulation_data.command_code) {
+      switch(encapsulation_data.command_code) {
         case (kEncapsulationCommandNoOperation):
           OPENER_TRACE_INFO("NOP\n");
           /* NOP needs no reply and does nothing */
@@ -200,19 +199,23 @@ EipStatus HandleReceivedExplictTcpData
         case (kEncapsulationCommandUnregisterSession):
           OPENER_TRACE_INFO("unregister session\n");
           return_value = HandleReceivedUnregisterSessionCommand(
-            &encapsulation_data, outgoing_message);
+            &encapsulation_data,
+            outgoing_message);
           break;
 
         case (kEncapsulationCommandSendRequestReplyData):
           OPENER_TRACE_INFO("Send Request/Reply Data\n");
           return_value = HandleReceivedSendRequestResponseDataCommand(
-            &encapsulation_data, originator_address, outgoing_message);
+            &encapsulation_data,
+            originator_address,
+            outgoing_message);
           break;
 
         case (kEncapsulationCommandSendUnitData):
           OPENER_TRACE_INFO("Send Unit Data\n");
-          return_value = HandleReceivedSendUnitDataCommand(
-            &encapsulation_data, originator_address, outgoing_message);
+          return_value = HandleReceivedSendUnitDataCommand(&encapsulation_data,
+                                                           originator_address,
+                                                           outgoing_message);
           break;
 
         default:
@@ -226,15 +229,13 @@ EipStatus HandleReceivedExplictTcpData
   return return_value;
 }
 
-EipStatus HandleReceivedExplictUdpData
-(
-  const int socket,
-  const struct sockaddr_in *from_address,
-  const EipUint8 *buffer,
-  const size_t buffer_length,
-  int *number_of_remaining_bytes,
-  bool unicast,
-  ENIPMessage *const outgoing_message) {
+EipStatus HandleReceivedExplictUdpData(const int socket,
+                                       const struct sockaddr_in *from_address,
+                                       const EipUint8 *buffer,
+                                       const size_t buffer_length,
+                                       int *number_of_remaining_bytes,
+                                       bool unicast,
+                                       ENIPMessage *const outgoing_message) {
   EipStatus return_value = kEipStatusOk;
   EncapsulationData encapsulation_data = { 0 };
   /* eat the encapsulation header*/
@@ -244,15 +245,15 @@ EipStatus HandleReceivedExplictUdpData
                                                             buffer_length,
                                                             &encapsulation_data);
 
-  if (kEncapsulationHeaderOptionsFlag == encapsulation_data.options)       /*TODO generate appropriate error response*/
+  if(kEncapsulationHeaderOptionsFlag == encapsulation_data.options) /*TODO generate appropriate error response*/
   {
-    if (*number_of_remaining_bytes >= 0)             /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
+    if(*number_of_remaining_bytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
     {
       /* full package or more received */
       encapsulation_data.status = kEncapsulationProtocolSuccess;
       return_value = kEipStatusOkSend;
       /* most of these functions need a reply to be send */
-      switch (encapsulation_data.command_code) {
+      switch(encapsulation_data.command_code) {
         case (kEncapsulationCommandListServices):
           OPENER_TRACE_INFO("List Service\n");
           HandleReceivedListServicesCommand(&encapsulation_data,
@@ -261,7 +262,7 @@ EipStatus HandleReceivedExplictUdpData
 
         case (kEncapsulationCommandListIdentity):
           OPENER_TRACE_INFO("List Identity\n");
-          if (unicast == true) {
+          if(unicast == true) {
             HandleReceivedListIdentityCommandTcp(&encapsulation_data,
                                                  outgoing_message);
           } else {
@@ -289,8 +290,7 @@ EipStatus HandleReceivedExplictUdpData
         default:
           OPENER_TRACE_INFO("No command\n");
           //TODO: Check this
-          encapsulation_data.status =
-            kEncapsulationProtocolInvalidCommand;
+          encapsulation_data.status = kEncapsulationProtocolInvalidCommand;
           encapsulation_data.data_length = 0;
           break;
       }
@@ -314,7 +314,8 @@ void GenerateEncapsulationHeader(const EncapsulationData *const receive_data,
   AddDintToMessage(session_handle, outgoing_message); //Session handle
   AddDintToMessage(encapsulation_protocol_status, outgoing_message); //Status
   memcpy(outgoing_message->current_message_position,
-         receive_data->sender_context, kSenderContextSize);                // sender context
+         receive_data->sender_context,
+         kSenderContextSize);                                                                           // sender context
   outgoing_message->current_message_position += kSenderContextSize;
   outgoing_message->used_message_length += kSenderContextSize;
   AddDintToMessage(0, outgoing_message); // options
@@ -329,13 +330,15 @@ void HandleReceivedListServicesCommand(
   ENIPMessage *const outgoing_message) {
 
   /* Create encapsulation header */
-  const size_t kListServicesCommandSpecificDataLength = sizeof(CipUint)
-                                                        + sizeof(
+  const size_t kListServicesCommandSpecificDataLength = sizeof(CipUint) +
+                                                        sizeof(
     g_service_information);
   GenerateEncapsulationHeader(receive_data,
                               kListServicesCommandSpecificDataLength,
-                              0, /* Session handle will be ignored */
-                              kEncapsulationProtocolSuccess,                             /* Protocol status */
+                              0,
+                              /* Session handle will be ignored */
+                              kEncapsulationProtocolSuccess,
+                              /* Protocol status */
                               outgoing_message);
 
   /* Command specific data copy Interface data to msg for sending */
@@ -364,7 +367,8 @@ void HandleReceivedListInterfacesCommand(
 
   GenerateEncapsulationHeader(receive_data,
                               kListInterfacesCommandSpecificDataLength,
-                              0, /* Session handle will be ignored */
+                              0,
+                              /* Session handle will be ignored */
                               kEncapsulationProtocolSuccess,
                               outgoing_message);
   /* Command specific data */
@@ -384,9 +388,8 @@ void HandleReceivedListIdentityCommandUdp(const int socket,
   DelayedEncapsulationMessage *delayed_message_buffer = NULL;
   ENIPMessage *p_outgoing_message = NULL;
 
-  for (size_t i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES;
-       i++) {
-    if (kEipInvalidSocket == g_delayed_encapsulation_messages[i].socket) {
+  for(size_t i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
+    if(kEipInvalidSocket == g_delayed_encapsulation_messages[i].socket) {
       delayed_message_buffer = &(g_delayed_encapsulation_messages[i]);
 
       p_outgoing_message = &(delayed_message_buffer->outgoing_message);
@@ -395,7 +398,7 @@ void HandleReceivedListIdentityCommandUdp(const int socket,
     }
   }
 
-  if (NULL != delayed_message_buffer) {
+  if(NULL != delayed_message_buffer) {
     delayed_message_buffer->socket = socket;
     memcpy( (&delayed_message_buffer->receiver), from_address,
             sizeof(struct sockaddr_in) );
@@ -408,11 +411,11 @@ void HandleReceivedListIdentityCommandUdp(const int socket,
 }
 
 CipUint ListIdentityGetCipIdentityItemLength() {
-  return sizeof(CipUint) + sizeof(CipInt) + sizeof(CipUint) +
-         sizeof(CipUdint) + 8 * sizeof(CipUsint) + sizeof(CipUint) +
-         sizeof(CipUint) + sizeof(CipUint) + 2 * sizeof(CipUsint) +
-         sizeof(CipWord) + sizeof(CipUdint) + sizeof(CipUsint) +
-         g_identity.product_name.length + sizeof(CipUsint);
+  return sizeof(CipUint) + sizeof(CipInt) + sizeof(CipUint) + sizeof(CipUdint) +
+         8 * sizeof(CipUsint) + sizeof(CipUint) + sizeof(CipUint) +
+         sizeof(CipUint)
+         + 2 * sizeof(CipUsint) + sizeof(CipWord) + sizeof(CipUdint) +
+         sizeof(CipUsint) + g_identity.product_name.length + sizeof(CipUsint);
 }
 
 void EncodeListIdentityCipIdentityItem(ENIPMessage *const outgoing_message) {
@@ -455,13 +458,13 @@ void EncapsulateListIdentityResponseMessage(
   ENIPMessage *const outgoing_message) {
 
   const CipUint kEncapsulationCommandListIdentityLength =
-    ListIdentityGetCipIdentityItemLength() + sizeof(CipUint) +
-    sizeof(CipUint)
-    + sizeof(CipUint);               /* Last element is item count */
+    ListIdentityGetCipIdentityItemLength() + sizeof(CipUint) + sizeof(CipUint) +
+    sizeof(CipUint);                                                                                                                                    /* Last element is item count */
 
   GenerateEncapsulationHeader(receive_data,
                               kEncapsulationCommandListIdentityLength,
-                              0,   /* Session handle will be ignored by receiver */
+                              0,
+                              /* Session handle will be ignored by receiver */
                               kEncapsulationProtocolSuccess,
                               outgoing_message);
 
@@ -474,13 +477,13 @@ void DetermineDelayTime(const EipByte *buffer_start,
                         DelayedEncapsulationMessage *const delayed_message_buffer)
 {
 
-  buffer_start += 12;             /* start of the sender context */
-  EipUint16 maximum_delay_time = GetIntFromMessage(
-    (const EipUint8 **const ) &buffer_start);
+  buffer_start += 12; /* start of the sender context */
+  EipUint16 maximum_delay_time = GetUintFromMessage(
+     (const EipUint8 **const ) &buffer_start );
 
-  if (0 == maximum_delay_time) {
+  if(0 == maximum_delay_time) {
     maximum_delay_time = kListIdentityDefaultDelayTime;
-  } else if (kListIdentityMinimumDelayTime > maximum_delay_time) {       /* if maximum_delay_time is between 1 and 500ms set it to 500ms */
+  } else if(kListIdentityMinimumDelayTime > maximum_delay_time) { /* if maximum_delay_time is between 1 and 500ms set it to 500ms */
     maximum_delay_time = kListIdentityMinimumDelayTime;
   }
 
@@ -494,8 +497,8 @@ void EncapsulateRegisterSessionCommandResponseMessage(
   ENIPMessage *const outgoing_message) {
 
   /* Encapsulation header */
-  const size_t kListInterfacesCommandSpecificDataLength = sizeof(CipUint)
-                                                          + sizeof(CipUint);
+  const size_t kListInterfacesCommandSpecificDataLength = sizeof(CipUint) +
+                                                          sizeof(CipUint);
   assert(kListInterfacesCommandSpecificDataLength == 4);
   GenerateEncapsulationHeader(receive_data,
                               kListInterfacesCommandSpecificDataLength,
@@ -519,20 +522,17 @@ void HandleReceivedRegisterSessionCommand(int socket,
   EncapsulationProtocolErrorCode encapsulation_protocol_status =
     kEncapsulationProtocolSuccess;
 
-  EipUint16 protocol_version =
-    GetIntFromMessage(
-      (const EipUint8 **const ) &receive_data->current_communication_buffer_position);
-  EipUint16 option_flag =
-    GetIntFromMessage(
-      (const EipUint8 **const ) &receive_data->current_communication_buffer_position);
+  EipUint16 protocol_version = GetUintFromMessage(
+     (const EipUint8 **const ) &receive_data->current_communication_buffer_position );
+  EipUint16 option_flag = GetUintFromMessage(
+     (const EipUint8 **const ) &receive_data->current_communication_buffer_position );
 
   /* check if requested protocol version is supported and the register session option flag is zero*/
-  if ( (0 < protocol_version)
-       && (protocol_version <= kSupportedProtocolVersion)
-       && (0 == option_flag) ) {                 /*Option field should be zero*/
+  if( (0 < protocol_version) &&
+      (protocol_version <= kSupportedProtocolVersion) && (0 == option_flag) ) {                         /*Option field should be zero*/
     /* check if the socket has already a session open */
-    for (size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
-      if (g_registered_sessions[i] == socket) {
+    for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+      if(g_registered_sessions[i] == socket) {
         /* the socket has already registered a session this is not allowed*/
         OPENER_TRACE_INFO(
           "Error: A session is already registered at socket %d\n",
@@ -544,24 +544,24 @@ void HandleReceivedRegisterSessionCommand(int socket,
       }
     }
 
-    if (kSessionStatusInvalid != session_index) {
+    if(kSessionStatusInvalid != session_index) {
       session_index = GetFreeSessionIndex();
-      if (kSessionStatusInvalid == session_index)                   /* no more sessions available */
+      if(kSessionStatusInvalid == session_index) /* no more sessions available */
       {
         encapsulation_protocol_status =
           kEncapsulationProtocolInsufficientMemory;
-      } else {                   /* successful session registered */
+      } else { /* successful session registered */
         SocketTimer *socket_timer = SocketTimerArrayGetEmptySocketTimer(
           g_timestamps,
           OPENER_NUMBER_OF_SUPPORTED_SESSIONS);
         SocketTimerSetSocket(socket_timer, socket);
         SocketTimerSetLastUpdate(socket_timer, g_actual_time);
-        g_registered_sessions[session_index] = socket;                         /* store associated socket */
+        g_registered_sessions[session_index] = socket; /* store associated socket */
         session_handle = session_index + 1;
         encapsulation_protocol_status = kEncapsulationProtocolSuccess;
       }
     }
-  } else {       /* protocol not supported */
+  } else { /* protocol not supported */
     encapsulation_protocol_status = kEncapsulationProtocolUnsupportedProtocol;
   }
 
@@ -583,11 +583,11 @@ EipStatus HandleReceivedUnregisterSessionCommand(
   const EncapsulationData *const receive_data,
   ENIPMessage *const outgoing_message) {
   OPENER_TRACE_INFO("encap.c: Unregister Session Command\n");
-  if ( (0 < receive_data->session_handle) && (receive_data->session_handle <=
-                                              OPENER_NUMBER_OF_SUPPORTED_SESSIONS) )
+  if( (0 < receive_data->session_handle) && (receive_data->session_handle <=
+                                             OPENER_NUMBER_OF_SUPPORTED_SESSIONS) )
   {
     size_t i = receive_data->session_handle - 1;
-    if (kEipInvalidSocket != g_registered_sessions[i]) {
+    if(kEipInvalidSocket != g_registered_sessions[i]) {
       CloseTcpSocket(g_registered_sessions[i]);
       g_registered_sessions[i] = kEipInvalidSocket;
       CloseClass3ConnectionBasedOnSession(i + 1);
@@ -614,30 +614,30 @@ EipStatus HandleReceivedSendUnitDataCommand(
   const struct sockaddr *const originator_address,
   ENIPMessage *const outgoing_message) {
   EipStatus return_value = kEipStatusOkSend;
-  /*EipStatus*/ return_value = kEipStatusOk;    /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
+  /*EipStatus*/ return_value = kEipStatusOk; /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
 
-  if (receive_data->data_length >= 6) {
+  if(receive_data->data_length >= 6) {
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* don't use the data yet */
     GetDintFromMessage(
-      (const EipUint8 **const ) &receive_data->current_communication_buffer_position);                            /* skip over null interface handle*/
+       (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*/
-    ( (EncapsulationData *const)receive_data )->data_length -= 6;             /* the rest is in CPF format*/
+       (const EipUint8 **const ) &receive_data->current_communication_buffer_position );               /* skip over unused timeout value*/
+    ( (EncapsulationData *const ) 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*/
     {
       return_value = NotifyConnectedCommonPacketFormat(receive_data,
                                                        originator_address,
                                                        outgoing_message);
-    } else {             /* received a package with non registered session handle */
+    } else { /* received a package with non registered session handle */
       InitializeENIPMessage(outgoing_message);
       GenerateEncapsulationHeader(receive_data,
                                   0,
                                   receive_data->session_handle,
                                   kEncapsulationProtocolInvalidSessionHandle,
                                   outgoing_message);
-      return_value = kEipStatusOkSend;  /* TODO: Needs to be here if line with first TODO of this function is adjusted. */
+      return_value = kEipStatusOkSend; /* TODO: Needs to be here if line with first TODO of this function is adjusted. */
     }
   }
   return return_value;
@@ -656,30 +656,30 @@ EipStatus HandleReceivedSendRequestResponseDataCommand(
   const struct sockaddr *const originator_address,
   ENIPMessage *const outgoing_message) {
   EipStatus return_value = kEipStatusOkSend;
-  /* EipStatus*/ return_value = kEipStatusOk;   /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
+  /* EipStatus*/ return_value = kEipStatusOk; /* TODO: Shouldn't this be kEipStatusOk cause we must not send any response if data_length < 6? */
 
-  if (receive_data->data_length >= 6) {
+  if(receive_data->data_length >= 6) {
     /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
     /* don't use the data yet */
     GetDintFromMessage(
-      (const EipUint8 **const ) &receive_data->current_communication_buffer_position);                            /* skip over null interface handle*/
+       (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*/
-    ( (EncapsulationData *const)receive_data )->data_length -= 6;             /* the rest is in CPF format*/
+       (const EipUint8 **const ) &receive_data->current_communication_buffer_position );               /* skip over unused timeout value*/
+    ( (EncapsulationData *const ) 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*/
     {
       return_value = NotifyCommonPacketFormat(receive_data,
                                               originator_address,
                                               outgoing_message);
-    } else {             /* received a package with non registered session handle */
+    } else { /* received a package with non registered session handle */
       InitializeENIPMessage(outgoing_message);
       GenerateEncapsulationHeader(receive_data,
                                   0,
                                   receive_data->session_handle,
                                   kEncapsulationProtocolInvalidSessionHandle,
                                   outgoing_message);
-      return_value = kEipStatusOkSend;  /* TODO: Needs to be here if line with first TODO of this function is adjusted. */
+      return_value = kEipStatusOkSend; /* TODO: Needs to be here if line with first TODO of this function is adjusted. */
     }
   }
   return return_value;
@@ -704,10 +704,9 @@ EipStatus HandleReceivedInvalidCommand(
  *                      kInvalidSession .. no free session available
  */
 int GetFreeSessionIndex(void) {
-  for (size_t session_index = 0;
-       session_index < OPENER_NUMBER_OF_SUPPORTED_SESSIONS;
-       session_index++) {
-    if (kEipInvalidSocket == g_registered_sessions[session_index]) {
+  for(size_t session_index = 0;
+      session_index < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; session_index++) {
+    if(kEipInvalidSocket == g_registered_sessions[session_index]) {
       return session_index;
     }
   }
@@ -727,21 +726,20 @@ EipInt16 CreateEncapsulationStructure(const EipUint8 *receive_buffer,
                                       int receive_buffer_length,
                                       EncapsulationData *const encapsulation_data)
 {
-  encapsulation_data->communication_buffer_start =
-    (EipUint8 *) receive_buffer;
-  encapsulation_data->command_code = GetIntFromMessage(&receive_buffer);
-  encapsulation_data->data_length = GetIntFromMessage(&receive_buffer);
-  encapsulation_data->session_handle = GetDintFromMessage(&receive_buffer);
-  encapsulation_data->status = GetDintFromMessage(&receive_buffer);
+  encapsulation_data->communication_buffer_start = (EipUint8 *) receive_buffer;
+  encapsulation_data->command_code = GetUintFromMessage(&receive_buffer);
+  encapsulation_data->data_length = GetUintFromMessage(&receive_buffer);
+  encapsulation_data->session_handle = GetUdintFromMessage(&receive_buffer);
+  encapsulation_data->status = GetUdintFromMessage(&receive_buffer);
 
   memcpy(encapsulation_data->sender_context, receive_buffer,
          kSenderContextSize);
   receive_buffer += kSenderContextSize;
-  encapsulation_data->options = GetDintFromMessage(&receive_buffer);
+  encapsulation_data->options = GetUdintFromMessage(&receive_buffer);
   encapsulation_data->current_communication_buffer_position =
     (EipUint8 *) receive_buffer;
-  return (receive_buffer_length - ENCAPSULATION_HEADER_LENGTH
-          - encapsulation_data->data_length);
+  return (receive_buffer_length - ENCAPSULATION_HEADER_LENGTH -
+          encapsulation_data->data_length);
 }
 
 /** @brief Check if received package belongs to registered session.
@@ -751,11 +749,11 @@ EipInt16 CreateEncapsulationStructure(const EipUint8 *receive_buffer,
  */
 SessionStatus CheckRegisteredSessions(
   const EncapsulationData *const receive_data) {
-  if ( (0 < receive_data->session_handle) && (receive_data->session_handle <=
-                                              OPENER_NUMBER_OF_SUPPORTED_SESSIONS) )
+  if( (0 < receive_data->session_handle) && (receive_data->session_handle <=
+                                             OPENER_NUMBER_OF_SUPPORTED_SESSIONS) )
   {
-    if (kEipInvalidSocket
-        != g_registered_sessions[receive_data->session_handle - 1]) {
+    if(kEipInvalidSocket !=
+       g_registered_sessions[receive_data->session_handle - 1]) {
       return kSessionStatusValid;
     }
   }
@@ -773,33 +771,31 @@ void CloseSessionBySessionHandle(
 
 void CloseSession(int socket) {
   OPENER_TRACE_INFO("encap.c: Close session\n");
-  for (size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
-    if (g_registered_sessions[i] == socket) {
+  for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+    if(g_registered_sessions[i] == socket) {
       CloseTcpSocket(socket);
       g_registered_sessions[i] = kEipInvalidSocket;
       CloseClass3ConnectionBasedOnSession(i + 1);
       break;
     }
-  }
-  OPENER_TRACE_INFO("encap.c: Close session done\n");
+  } OPENER_TRACE_INFO("encap.c: Close session done\n");
 }
 
 void RemoveSession(const int socket) {
   OPENER_TRACE_INFO("encap.c: Removing session\n");
-  for (size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
-    if (g_registered_sessions[i] == socket) {
+  for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+    if(g_registered_sessions[i] == socket) {
       g_registered_sessions[i] = kEipInvalidSocket;
       CloseClass3ConnectionBasedOnSession(i + 1);
       break;
     }
-  }
-  OPENER_TRACE_INFO("encap.c: Session removed\n");
+  } OPENER_TRACE_INFO("encap.c: Session removed\n");
 }
 
 void EncapsulationShutDown(void) {
   OPENER_TRACE_INFO("encap.c: Encapsulation shutdown\n");
-  for (size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
-    if (kEipInvalidSocket != g_registered_sessions[i]) {
+  for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+    if(kEipInvalidSocket != g_registered_sessions[i]) {
       CloseTcpSocket(g_registered_sessions[i]);
       g_registered_sessions[i] = kEipInvalidSocket;
     }
@@ -807,11 +803,10 @@ void EncapsulationShutDown(void) {
 }
 
 void ManageEncapsulationMessages(const MilliSeconds elapsed_time) {
-  for (size_t i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES;
-       i++) {
-    if (kEipInvalidSocket != g_delayed_encapsulation_messages[i].socket) {
+  for(size_t i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
+    if(kEipInvalidSocket != g_delayed_encapsulation_messages[i].socket) {
       g_delayed_encapsulation_messages[i].time_out -= elapsed_time;
-      if (0 >= g_delayed_encapsulation_messages[i].time_out) {
+      if(0 >= g_delayed_encapsulation_messages[i].time_out) {
         /* If delay is reached or passed, send the UDP message */
         sendto(g_delayed_encapsulation_messages[i].socket,
                (char *) g_delayed_encapsulation_messages[i].outgoing_message.message_buffer,
@@ -828,13 +823,13 @@ void ManageEncapsulationMessages(const MilliSeconds elapsed_time) {
 
 void CloseEncapsulationSessionBySockAddr(
   const CipConnectionObject *const connection_object) {
-  for (size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
-    if (kEipInvalidSocket != g_registered_sessions[i]) {
+  for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+    if(kEipInvalidSocket != g_registered_sessions[i]) {
       struct sockaddr_in encapsulation_session_addr = { 0 };
       socklen_t addrlength = sizeof(encapsulation_session_addr);
-      if (getpeername(g_registered_sessions[i],
-                      (struct sockaddr *)&encapsulation_session_addr,
-                      &addrlength) < 0) {                   /* got error */
+      if(getpeername(g_registered_sessions[i],
+                     (struct sockaddr *) &encapsulation_session_addr,
+                     &addrlength) < 0) {                                                                           /* got error */
         int error_code = GetSocketErrorNumber();
         char *error_message = GetErrorMessage(error_code);
         OPENER_TRACE_ERR(
@@ -842,8 +837,8 @@ void CloseEncapsulationSessionBySockAddr(
           error_code, error_message);
         FreeErrorMessage(error_message);
       }
-      if (encapsulation_session_addr.sin_addr.s_addr
-          == connection_object->originator_address.sin_addr.s_addr) {
+      if(encapsulation_session_addr.sin_addr.s_addr ==
+         connection_object->originator_address.sin_addr.s_addr) {
         CloseSession(g_registered_sessions[i]);
       }
     }
@@ -851,8 +846,8 @@ void CloseEncapsulationSessionBySockAddr(
 }
 
 size_t GetSessionFromSocket(const int socket_handle) {
-  for (size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
-    if (socket_handle == g_registered_sessions[i]) {
+  for(size_t i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+    if(socket_handle == g_registered_sessions[i]) {
       return i;
     }
   }
@@ -861,13 +856,12 @@ size_t GetSessionFromSocket(const int socket_handle) {
 
 void CloseClass3ConnectionBasedOnSession(size_t encapsulation_session_handle) {
   DoublyLinkedListNode *node = connection_list.first;
-  while (NULL != node) {
+  while(NULL != node) {
     CipConnectionObject *connection_object = node->data;
-    if (kConnectionObjectTransportClassTriggerTransportClass3
-        == ConnectionObjectGetTransportClassTriggerTransportClass(
-          connection_object)
-        && connection_object->associated_encapsulation_session
-        == encapsulation_session_handle) {
+    if(kConnectionObjectTransportClassTriggerTransportClass3 ==
+       ConnectionObjectGetTransportClassTriggerTransportClass(connection_object)
+       && connection_object->associated_encapsulation_session ==
+       encapsulation_session_handle) {
       connection_object->connection_close_function(connection_object);
     }
     node = node->next;

+ 28 - 23
source/src/enet_encap/endianconv.c

@@ -26,7 +26,7 @@ OpenerEndianess g_opener_platform_endianess = kOpenerEndianessUnknown;
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT8 data value
  */
-EipUint8 GetSintFromMessage(const EipUint8 **const buffer) {
+CipSint GetSintFromMessage(const EipUint8 **const buffer) {
   const unsigned char *const buffer_address = (unsigned char *) *buffer;
   EipUint8 data = buffer_address[0];
   *buffer += 1;
@@ -54,7 +54,7 @@ CipUsint GetUsintFromMessage(const CipOctet **const buffer_address) {
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT16 data value
  */
-EipUint16 GetIntFromMessage(const EipUint8 **const buffer) {
+CipInt GetIntFromMessage(const EipUint8 **const buffer) {
   const unsigned char *const buffer_address = (unsigned char *) *buffer;
   EipUint16 data = buffer_address[0] | buffer_address[1] << 8;
   *buffer += 2;
@@ -80,7 +80,7 @@ CipWord GetWordFromMessage(const CipOctet **const buffer_address) {
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UNÍT32 value
  */
-EipUint32 GetDintFromMessage(const EipUint8 **const buffer) {
+CipDint 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;
   *buffer += 4;
@@ -95,6 +95,14 @@ CipUdint GetUdintFromMessage(const CipOctet **const buffer_address) {
   return data;
 }
 
+CipUdint GetDwordFromMessage(const CipOctet **const buffer_address) {
+  const CipOctet *buffer = *buffer_address;
+  CipDword data = buffer[0] | buffer[1] << 8 | buffer[2] << 16 | buffer[3] <<
+                  24;
+  *buffer_address += 4;
+  return data;
+}
+
 /**
  * @brief converts UINT8 data from host to little endian an writes it to buffer.
  * @param data value to be written
@@ -145,21 +153,18 @@ void AddDintToMessage(const EipUint32 data,
  */
 EipUint64 GetLintFromMessage(const EipUint8 **const buffer) {
   const EipUint8 *buffer_address = *buffer;
-  EipUint64 data = ( ( ( (EipUint64) buffer_address[0] ) << 56 )
-                     & 0xFF00000000000000LL )
-                   + ( ( ( (EipUint64) buffer_address[1] ) << 48 ) &
-                       0x00FF000000000000LL )
-                   + ( ( ( (EipUint64) buffer_address[2] ) << 40 ) &
-                       0x0000FF0000000000LL )
-                   + ( ( ( (EipUint64) buffer_address[3] ) << 32 ) &
-                       0x000000FF00000000LL )
-                   + ( ( ( (EipUint64) buffer_address[4] ) << 24 ) &
-                       0x00000000FF000000 )
-                   + ( ( ( (EipUint64) buffer_address[5] ) << 16 ) &
-                       0x0000000000FF0000 )
-                   + ( ( ( (EipUint64) buffer_address[6] ) << 8 ) &
-                       0x000000000000FF00 )
-                   + ( ( (EipUint64) buffer_address[7] ) & 0x00000000000000FF );
+  EipUint64 data =
+    ( ( ( (EipUint64) buffer_address[0] ) << 56 ) & 0xFF00000000000000LL ) +
+    ( ( ( (EipUint64) buffer_address[1] ) << 48 ) & 0x00FF000000000000LL )
+    + ( ( ( (EipUint64) buffer_address[2] ) << 40 ) &
+        0x0000FF0000000000LL ) +
+    ( ( ( (EipUint64) buffer_address[3] ) << 32 ) & 0x000000FF00000000LL )
+    + ( ( ( (EipUint64) buffer_address[4] ) << 24 ) &
+        0x00000000FF000000 ) +
+    ( ( ( (EipUint64) buffer_address[5] ) << 16 ) & 0x0000000000FF0000 )
+    + ( ( ( (EipUint64) buffer_address[6] ) << 8 ) &
+        0x000000000000FF00 ) +
+    ( ( (EipUint64) buffer_address[7] ) & 0x00000000000000FF );
   *buffer += 8;
   return data;
 }
@@ -187,13 +192,13 @@ void AddLintToMessage(const EipUint64 data,
 void EncapsulateIpAddress(EipUint16 port,
                           EipUint32 address,
                           ENIPMessage *const outgoing_message) {
-  if (kOpENerEndianessLittle == g_opener_platform_endianess) {
+  if(kOpENerEndianessLittle == g_opener_platform_endianess) {
     AddIntToMessage(htons(AF_INET), outgoing_message);
     AddIntToMessage(port, outgoing_message);
     AddDintToMessage(address, outgoing_message);
 
   } else {
-    if (kOpENerEndianessBig == g_opener_platform_endianess) {
+    if(kOpENerEndianessBig == g_opener_platform_endianess) {
 
       AddIntToMessage(htons(AF_INET), outgoing_message);
 
@@ -208,7 +213,7 @@ void EncapsulateIpAddress(EipUint16 port,
     } else {
       fprintf(stderr,
               "No endianess detected! Probably the DetermineEndianess function was not executed!");
-      exit (EXIT_FAILURE);
+      exit(EXIT_FAILURE);
     }
   }
 }
@@ -221,8 +226,8 @@ void EncapsulateIpAddress(EipUint16 port,
  */
 void DetermineEndianess() {
   int i = 1;
-  char *p = (char *) &i;
-  if (p[0] == 1) {
+  const char *const p = (char *) &i;
+  if(p[0] == 1) {
     g_opener_platform_endianess = kOpENerEndianessLittle;
   } else {
     g_opener_platform_endianess = kOpENerEndianessBig;

+ 5 - 3
source/src/enet_encap/endianconv.h

@@ -24,7 +24,7 @@ typedef enum {
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT8 data value
  */
-EipUint8 GetSintFromMessage(const EipUint8 **const buffer);
+CipSint GetSintFromMessage(const EipUint8 **const buffer);
 
 CipByte GetByteFromMessage(const CipOctet **const buffer_address);
 
@@ -36,7 +36,7 @@ CipUsint GetUsintFromMessage(const CipOctet **const buffer_address);
  * @param buffer Pointer to the network buffer array. This pointer will be incremented by 2!
  * @return Extracted 16 bit integer value
  */
-EipUint16 GetIntFromMessage(const EipUint8 **const buffer);
+CipInt GetIntFromMessage(const EipUint8 **const buffer);
 
 CipUint GetUintFromMessage(const CipOctet **const buffer_address);
 
@@ -48,10 +48,12 @@ CipWord GetWordFromMessage(const CipOctet **const buffer_address);
  * @param buffer pointer to the network buffer array. This pointer will be incremented by 4!
  * @return Extracted 32 bit integer value
  */
-EipUint32 GetDintFromMessage(const EipUint8 **const buffer);
+CipDint GetDintFromMessage(const EipUint8 **const buffer);
 
 CipUdint GetUdintFromMessage(const CipOctet **const buffer_address);
 
+CipUdint GetDwordFromMessage(const CipOctet **const buffer_address);
+
 /** @ingroup ENCAP
  *
  * @brief converts UINT8 data from host to little endian an writes it to buffer.

Dosya farkı çok büyük olduğundan ihmal edildi
+ 250 - 253
source/src/ports/generic_networkhandler.c


+ 1 - 0
source/tests/OpENerTests.h

@@ -7,6 +7,7 @@ IMPORT_TEST_GROUP (EndianConversion);
 IMPORT_TEST_GROUP (CipCommon);
 IMPORT_TEST_GROUP (CipEpath);
 IMPORT_TEST_GROUP (CipElectronicKey);
+IMPORT_TEST_GROUP (CipElectronicKeyFormat);
 IMPORT_TEST_GROUP (CipConnectionManager);
 IMPORT_TEST_GROUP (CipConnectionObject);
 IMPORT_TEST_GROUP (SocketTimer);

+ 1 - 1
source/tests/cip/CMakeLists.txt

@@ -8,7 +8,7 @@ opener_common_includes()
 #######################################
 opener_platform_support("INCLUDES")
 
-set( CipTestSrc cipepathtest.cpp cipelectronickeytest.cpp cipconnectionmanagertest.cpp cipconnectionobjecttest.cpp cipcommontests.cpp cipstringtests.cpp)
+set( CipTestSrc cipepathtest.cpp cipelectronickeytest.cpp  cipelectronickeyformattest.cpp cipconnectionmanagertest.cpp cipconnectionobjecttest.cpp cipcommontests.cpp cipstringtests.cpp)
 
 include_directories( ${SRC_DIR}/cip )
 

+ 181 - 0
source/tests/cip/cipelectronickeyformattest.cpp

@@ -0,0 +1,181 @@
+/*******************************************************************************
+ * Copyright (c) 2016, Rockwell Automation, Inc.
+ * All rights reserved.
+ *
+ ******************************************************************************/
+
+#include <CppUTest/TestHarness.h>
+#include <stdint.h>
+#include <string.h>
+
+extern "C" {
+
+#include "cipepath.h"
+#include "cipelectronickey.h"
+
+}
+
+TEST_GROUP(CipElectronicKeyFormat) {
+  ElectronicKeyFormat4 *key;
+
+  void setup() {
+    key = ElectronicKeyFormat4New();
+  }
+
+  void teardown() {
+    ElectronicKeyFormat4Delete (&key);
+  }
+
+};
+
+TEST(CipElectronicKeyFormat, CreateElectronicKey) {
+  CipOctet dummyArea[kElectronicKeyFormat4Size];
+  memset(dummyArea, 0, sizeof(dummyArea) );
+  MEMCMP_EQUAL(dummyArea, key, kElectronicKeyFormat4Size);
+};
+
+TEST(CipElectronicKeyFormat, DeleteElectronicKey) {
+  ElectronicKeyFormat4Delete(&key);
+  POINTERS_EQUAL(NULL, key);
+}
+
+TEST(CipElectronicKeyFormat, SetVendorID) {
+  CipOctet demoArea[kElectronicKeyFormat4Size];
+  memset(demoArea, 0, sizeof(demoArea) );
+  CipUint *vendor_id = (CipUint *)demoArea;
+  *vendor_id = 1;
+  ElectronicKeyFormat4SetVendorId(key, 1);
+
+  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
+}
+
+TEST(CipElectronicKeyFormat, GetVendorID) {
+  CipUint expected_vendor_id = 1;
+
+  CipUint *vendor_id_data = (CipUint *)key;
+  *vendor_id_data = expected_vendor_id;
+
+  CipUint vendor_id = ElectronicKeyFormat4GetVendorId(key);
+  CHECK_EQUAL(expected_vendor_id, vendor_id);
+}
+
+TEST(CipElectronicKeyFormat, SetDeviceType) {
+  CipOctet demoArea[kElectronicKeyFormat4Size];
+  memset(demoArea, 0, sizeof(demoArea) );
+  CipUint *device_type = (CipUint *)demoArea + 1;
+  *device_type = 1;
+
+  ElectronicKeyFormat4SetDeviceType(key, 1);
+  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
+}
+
+TEST(CipElectronicKeyFormat, GetDeviceType) {
+  CipUint expected_device_type = 1;
+
+  CipUint *device_type_data = (CipUint *)key + 1;
+  *device_type_data = expected_device_type;
+
+  CipUint device_type = ElectronicKeyFormat4GetDeviceType(key);
+  CHECK_EQUAL(expected_device_type, device_type);
+}
+
+TEST(CipElectronicKeyFormat, SetProductCode) {
+  CipOctet demoArea[kElectronicKeyFormat4Size];
+  memset(demoArea, 0, sizeof(demoArea) );
+  CipUint *product_code = (CipUint *)demoArea + 2;
+  *product_code = 1;
+
+  ElectronicKeyFormat4SetProductCode(key, 1);
+  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
+}
+
+TEST(CipElectronicKeyFormat, GetProductCode) {
+  CipUint expected_product_code = 1;
+
+  CipUint *product_code_data = (CipUint *)key + 2;
+  *product_code_data = expected_product_code;
+
+  CipUint product_code = ElectronicKeyFormat4GetProductCode(key);
+  CHECK_EQUAL(expected_product_code, product_code);
+}
+
+TEST(CipElectronicKeyFormat, SetMajorRevisionCompatibility) {
+  CipOctet demoArea[kElectronicKeyFormat4Size];
+  memset(demoArea, 0, sizeof(demoArea) );
+  CipByte *major_revision_compatiblitiy = (CipByte *)demoArea + 6;
+  *major_revision_compatiblitiy = 0x81;
+
+  ElectronicKeyFormat4SetMajorRevisionCompatibility(key, 0x81);
+  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
+}
+
+TEST(CipElectronicKeyFormat, GetMajorRevision) {
+  const CipUsint expected_major_revision = 0x1;
+
+  CipUsint set_major_revision = 0x1;
+  CipByte *expected_major_data = (CipByte *)key + 6;
+  *expected_major_data = set_major_revision;
+
+  CipUint product_code = ElectronicKeyFormat4GetMajorRevision(key);
+  CHECK_EQUAL(expected_major_revision, product_code);
+}
+
+TEST(CipElectronicKeyFormat, GetMajorRevisionCompatibility) {
+  const CipUsint expected_major_revision = 0x81;
+
+  CipByte *expected_major_data = (CipByte *)key + 6;
+  *expected_major_data = expected_major_revision;
+
+  bool compatibility = ElectronicKeyFormat4GetMajorRevisionCompatibility(key);
+  CHECK_TEXT(compatibility, "Compatibility flag not working");
+}
+
+TEST(CipElectronicKeyFormat, SetMinorRevision) {
+  CipOctet demoArea[kElectronicKeyFormat4Size];
+  memset(demoArea, 0, sizeof(demoArea) );
+  CipByte *minor_revision_compatiblitiy = (CipByte *)demoArea + 7;
+  *minor_revision_compatiblitiy = 0x81;
+
+  ElectronicKeyFormat4SetMinorRevision(key, 0x81);
+  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
+}
+
+TEST(CipElectronicKeyFormat, GetMinorRevision) {
+  CipUsint expected_minor_revision = 0x1;
+
+  CipByte *expected_minor_data = (CipByte *)key + 7;
+  *expected_minor_data = expected_minor_revision;
+
+  CipUint product_code = ElectronicKeyFormat4GetMinorRevision(key);
+  CHECK_EQUAL(expected_minor_revision, product_code);
+}
+
+TEST(CipElectronicKeyFormat, ParseElectronicKeyTest) {
+  /* Size of an electronic key is 1 + 1 + 8 (Segment, Key format, Key) */
+  const CipOctet message[] =
+  { 0x34, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x84, 0x05};
+  const CipOctet *message_buffer = message;
+  GetElectronicKeyFormat4FromMessage(&message_buffer, key);
+
+  message_buffer = message;
+  CHECK_EQUAL( 256, ElectronicKeyFormat4GetVendorId(key) );
+  CHECK_EQUAL( 512, ElectronicKeyFormat4GetDeviceType(key) );
+  CHECK_EQUAL( 768, ElectronicKeyFormat4GetProductCode(key) );
+  CHECK_TRUE( ElectronicKeyFormat4GetMajorRevisionCompatibility(key) );
+  CHECK_EQUAL( 0x04, ElectronicKeyFormat4GetMajorRevision(key) );
+  CHECK_EQUAL( 0x05, ElectronicKeyFormat4GetMinorRevision(key) );
+
+  MEMCMP_EQUAL(message_buffer + 2, key, 8);
+
+}
+
+//TEST(CipElectronicKeyFormat, CheckElectronicKeyWrongVendorId) {
+//	const CipOctet message [] = "\x34\x04\x02\x00\x0c\x00\xe9\xfd\x01\x02";
+//	const CipOctet *message_buffer = message;
+//	EipUint16 *extended_status = 0;
+//
+//	GetElectronicKeyFormat4FromMessage((const CipOctet**)&message_buffer, key);
+//
+//	CheckElectronicKeyData(4, key_data, extended_status);
+//
+//}

+ 18 - 154
source/tests/cip/cipelectronickeytest.cpp

@@ -1,5 +1,5 @@
 /*******************************************************************************
- * Copyright (c) 2016, Rockwell Automation, Inc.
+ * Copyright (c) 2020, Rockwell Automation, Inc.
  * All rights reserved.
  *
  ******************************************************************************/
@@ -15,167 +15,31 @@ extern "C" {
 
 }
 
-TEST_GROUP(CipElectronicKey) {
-  ElectronicKeyFormat4 *key;
+TEST_GROUP (CipElectronicKey) {
 
-  void setup() {
-    key = ElectronicKeyFormat4New();
-  }
-
-  void teardown() {
-    ElectronicKeyFormat4Delete(&key);
-  }
-
-};
-
-TEST(CipElectronicKey, CreateElectronicKey) {
-  char dummyArea[kElectronicKeyFormat4Size];
-  memset(dummyArea, 0, sizeof(dummyArea) );
-  MEMCMP_EQUAL(dummyArea, key, kElectronicKeyFormat4Size);
 };
 
-TEST(CipElectronicKey, DeleteElectronicKey) {
-  ElectronicKeyFormat4Delete(&key);
-  POINTERS_EQUAL(NULL, key);
-}
-
-TEST(CipElectronicKey, SetVendorID) {
-  char demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
-  CipUint *vendor_id = (CipUint *)demoArea;
-  *vendor_id = 1;
-  ElectronicKeyFormat4SetVendorId(key, 1);
-
-  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
-}
-
-TEST(CipElectronicKey, GetVendorID) {
-  CipUint expected_vendor_id = 1;
-
-  CipUint *vendor_id_data = (CipUint *)key;
-  *vendor_id_data = expected_vendor_id;
-
-  CipUint vendor_id = ElectronicKeyFormat4GetVendorId(key);
-  CHECK_EQUAL(expected_vendor_id, vendor_id);
-}
-
-TEST(CipElectronicKey, SetDeviceType) {
-  char demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
-  CipUint *device_type = (CipUint *)demoArea + 1;
-  *device_type = 1;
-
-  ElectronicKeyFormat4SetDeviceType(key, 1);
-  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
-}
-
-TEST(CipElectronicKey, GetDeviceType) {
-  CipUint expected_device_type = 1;
-
-  CipUint *device_type_data = (CipUint *)key + 1;
-  *device_type_data = expected_device_type;
-
-  CipUint device_type = ElectronicKeyFormat4GetDeviceType(key);
-  CHECK_EQUAL(expected_device_type, device_type);
-}
-
-TEST(CipElectronicKey, SetProductCode) {
-  char demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
-  CipUint *product_code = (CipUint *)demoArea + 2;
-  *product_code = 1;
-
-  ElectronicKeyFormat4SetProductCode(key, 1);
-  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
-}
-
-TEST(CipElectronicKey, GetProductCode) {
-  CipUint expected_product_code = 1;
-
-  CipUint *product_code_data = (CipUint *)key + 2;
-  *product_code_data = expected_product_code;
+TEST(CipElectronicKey, SetKeyFormat) {
+  CipElectronicKey key;
+  ElectronicKeySetKeyFormat(&key, 4);
+  CHECK_EQUAL(4, key.key_format);
 
-  CipUint product_code = ElectronicKeyFormat4GetProductCode(key);
-  CHECK_EQUAL(expected_product_code, product_code);
 }
 
-TEST(CipElectronicKey, SetMajorRevisionCompatibility) {
-  char demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
-  CipByte *major_revision_compatiblitiy = (CipByte *)demoArea + 6;
-  *major_revision_compatiblitiy = 0x81;
-
-  ElectronicKeyFormat4SetMajorRevisionCompatibility(key, 0x81);
-  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
+TEST(CipElectronicKey, GetKeyFormat) {
+  CipElectronicKey key = {.key_format = 4, .key_data = NULL};
+  CHECK_EQUAL(4, ElectronicKeyGetKeyFormat(&key) );
 }
 
-TEST(CipElectronicKey, GetMajorRevision) {
-  CipUint expected_major_revision = 0x1;
-
-  CipUint set_major_revision = 0x1;
-  CipByte *expected_major_data = (CipByte *)key + 6;
-  *expected_major_data = set_major_revision;
-
-  CipUint product_code = ElectronicKeyFormat4GetMajorRevision(key);
-  CHECK_EQUAL(expected_major_revision, product_code);
+TEST(CipElectronicKey, SetKeyData) {
+  char dummyFormatData[] = {0,1,2,3,4,5};
+  CipElectronicKey key;
+  ElectronicKeySetKeyData(&key, dummyFormatData);
+  POINTERS_EQUAL(dummyFormatData, key.key_data);
 }
 
-TEST(CipElectronicKey, GetMajorRevisionCompatibility) {
-  CipUint expected_major_revision = 0x81;
-
-  CipByte *expected_major_data = (CipByte *)key + 6;
-  *expected_major_data = expected_major_revision;
-
-  bool compatibility = ElectronicKeyFormat4GetMajorRevisionCompatibility(key);
-  CHECK_TEXT(compatibility, "Compatibility flag not working");
-}
-
-TEST(CipElectronicKey, SetMinorRevision) {
-  char demoArea[kElectronicKeyFormat4Size];
-  memset(demoArea, 0, sizeof(demoArea) );
-  CipByte *minor_revision_compatiblitiy = (CipByte *)demoArea + 7;
-  *minor_revision_compatiblitiy = 0x81;
-
-  ElectronicKeyFormat4SetMinorRevision(key, 0x81);
-  MEMCMP_EQUAL(demoArea, key, kElectronicKeyFormat4Size);
+TEST(CipElectronicKey, GetKeyData) {
+  char dummyFormatData[] = {0,1,2,3,4,5};
+  CipElectronicKey key = {.key_format = 0, .key_data = dummyFormatData};
+  POINTERS_EQUAL(dummyFormatData, ElectronicKeyGetKeyData(&key) );
 }
-
-TEST(CipElectronicKey, GetMinorRevision) {
-  CipUint expected_minor_revision = 0x1;
-
-  CipByte *expected_minor_data = (CipByte *)key + 7;
-  *expected_minor_data = expected_minor_revision;
-
-  CipUint product_code = ElectronicKeyFormat4GetMinorRevision(key);
-  CHECK_EQUAL(expected_minor_revision, product_code);
-}
-
-TEST(CipElectronicKey, ParseElectronicKeyTest) {
-  /* Size of an electronic key is 1 + 1 + 8 (Segment, Key format, Key) */
-  const CipOctet message[] =
-  {0x34, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x84, 0x05};
-  const CipOctet *message_buffer = message;
-  GetElectronicKeyFormat4FromMessage( (const CipOctet **)&message_buffer, key );
-
-  message_buffer = message;
-  CHECK_EQUAL( 256, ElectronicKeyFormat4GetVendorId(key) );
-  CHECK_EQUAL( 512, ElectronicKeyFormat4GetDeviceType(key) );
-  CHECK_EQUAL( 768, ElectronicKeyFormat4GetProductCode(key) );
-  CHECK_TRUE( ElectronicKeyFormat4GetMajorRevisionCompatibility(key) );
-  CHECK_EQUAL( 0x04, ElectronicKeyFormat4GetMajorRevision(key) );
-  CHECK_EQUAL( 0x05, ElectronicKeyFormat4GetMinorRevision(key) );
-
-  MEMCMP_EQUAL(message_buffer + 2, key, 8);
-
-}
-
-//TEST(CipElectronicKey, CheckElectronicKeyWrongVendorId) {
-//	const CipOctet message [] = "\x34\x04\x02\x00\x0c\x00\xe9\xfd\x01\x02";
-//	const CipOctet *message_buffer = message;
-//	EipUint16 *extended_status = 0;
-//
-//	GetElectronicKeyFormat4FromMessage((const CipOctet**)&message_buffer, key);
-//
-//	CheckElectronicKeyData(4, key_data, extended_status);
-//
-//}

+ 172 - 3
source/tests/cip/cipepathtest.cpp

@@ -14,7 +14,7 @@ extern "C" {
 
 }
 
-TEST_GROUP(CipEpath) {
+TEST_GROUP (CipEpath) {
 
 };
 
@@ -229,6 +229,69 @@ TEST(CipEpath, GetLogicalSegmentLogicalTypeExtendedLogical) {
   CHECK_EQUAL(kLogicalSegmentLogicalTypeExtendedLogical, type);
 }
 
+TEST(CipEpath, SetLogicalSegmentLogicalTypeClassId) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeClassId, message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_CLASS_ID,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalTypeInstanceId) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeInstanceId,
+                                   message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_INSTANCE_ID,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalTypeMemberId) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeMemberId, message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_MEMBER_ID,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalTypeConnectionPoint) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeConnectionPoint,
+                                   message);
+  CHECK_EQUAL(
+    SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_CONNECTION_POINT,
+    message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalTypeAttributeId) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeAttributeId,
+                                   message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_ATTRIBUTE_ID,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalTypeSpecial) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeSpecial, message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_SPECIAL,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalTypeServiceId) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeServiceId,
+                                   message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_SERVICE_ID,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalTypeExtendedLogicalPath) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalType(kLogicalSegmentLogicalTypeExtendedLogical,
+                                   message);
+  CHECK_EQUAL(
+    SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_TYPE_EXTENDED_LOGICAL,
+    message[0]);
+}
+
 TEST(CipEpath, GetLogicalSegmentLogicalFormatEightBits) {
   const unsigned char message[] = {0x20};
   const LogicalSegmentLogicalFormat format = GetPathLogicalSegmentLogicalFormat(
@@ -250,6 +313,113 @@ TEST(CipEpath, GetLogicalSegmentLogicalFormatThirtyTwoBits) {
   CHECK_EQUAL(kLogicalSegmentLogicalFormatThirtyTwoBit, format);
 }
 
+TEST(CipEpath, SetLogicalSegmentLogicalFormatEightBits) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalFormat(kLogicalSegmentLogicalFormatEightBit,
+                                     message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_FORMAT_EIGHT_BIT,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalFormatSixteenBits) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalFormat(kLogicalSegmentLogicalFormatSixteenBit,
+                                     message);
+  CHECK_EQUAL(SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT,
+              message[0]);
+}
+
+TEST(CipEpath, SetLogicalSegmentLogicalFormatThirtyTwoBits) {
+  CipOctet message[] = {SEGMENT_TYPE_LOGICAL_SEGMENT};
+  SetPathLogicalSegmentLogicalFormat(kLogicalSegmentLogicalFormatThirtyTwoBit,
+                                     message);
+  CHECK_EQUAL(
+    SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_FORMAT_THIRTY_TWO_BIT,
+    message[0]);
+}
+
+TEST(CipEpath, GetLogicalValue8Bit) {
+  CipOctet *message = (CipOctet *)calloc (6, sizeof(CipOctet) );
+  CipOctet *original_address = message;
+  message[0] = SEGMENT_TYPE_LOGICAL_SEGMENT | LOGICAL_SEGMENT_FORMAT_EIGHT_BIT;
+  message[1] = 20;
+  message[2] = 21;
+  message[3] = 22;
+  message[4] = 23;
+  message[5] = 24;
+  CipDword result = CipEpathGetLogicalValue( (const CipOctet **)&message );
+  CHECK_EQUAL(20, result);
+  free(original_address);
+}
+
+TEST(CipEpath, GetLogicalValue16Bit) {
+  CipOctet *message = (CipOctet *)calloc (6, sizeof(CipOctet) );
+  CipOctet *original_address = message;
+  message[0] = SEGMENT_TYPE_LOGICAL_SEGMENT |
+               LOGICAL_SEGMENT_FORMAT_SIXTEEN_BIT;
+  message[1] = 0;
+  message[2] = 21;
+  message[3] = 22;
+  message[4] = 23;
+  message[5] = 24;
+  CipDword result = CipEpathGetLogicalValue( (const CipOctet **)&message );
+  CHECK_EQUAL(5653, result);
+  free(original_address);
+}
+
+TEST(CipEpath, GetLogicalValue32Bit) {
+  CipOctet *message = (CipOctet *)calloc (6, sizeof(CipOctet) );
+  CipOctet *original_address = message;
+  message[0] = SEGMENT_TYPE_LOGICAL_SEGMENT |
+               LOGICAL_SEGMENT_FORMAT_THIRTY_TWO_BIT;
+  message[1] = 0;
+  message[2] = 21;
+  message[3] = 22;
+  message[4] = 23;
+  message[5] = 24;
+  CipDword result = CipEpathGetLogicalValue( (const CipOctet **)&message );
+  CHECK_EQUAL(404166165, result);
+  free(original_address);
+}
+
+TEST(CipEpath, SetLogicalValue8Bit) {
+  const CipUsint value = 54;
+  CipMessageRouterResponse response = {0};
+  response.message.current_message_position = response.message.message_buffer;
+  CipEpathSetLogicalValue(value, kLogicalSegmentLogicalFormatEightBit,
+                          &response);
+  CHECK_EQUAL(value, *response.message.message_buffer);
+}
+
+TEST(CipEpath, SetLogicalValue16Bit) {
+  const CipUsint value = 54;
+  CipMessageRouterResponse response = {0};
+  response.message.current_message_position = response.message.message_buffer;
+  CipEpathSetLogicalValue(value,
+                          kLogicalSegmentLogicalFormatSixteenBit,
+                          &response);
+  CHECK_EQUAL(value, *(response.message.message_buffer + 1) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 2) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 3) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 4) );
+}
+
+TEST(CipEpath, SetLogicalValue32Bit) {
+  const CipUsint value = 54;
+  CipMessageRouterResponse response = {0};
+  response.message.current_message_position = response.message.message_buffer;
+  CipEpathSetLogicalValue(value,
+                          kLogicalSegmentLogicalFormatThirtyTwoBit,
+                          &response);
+  CHECK_EQUAL(value, *(response.message.message_buffer + 1) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 2) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 3) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 4) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 5) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 6) );
+  CHECK_EQUAL(0, *(response.message.message_buffer + 7) );
+}
+
 TEST(CipEpath, GetLogicalSegmentExtendedLogicalTypeReserved) {
   const unsigned char message[] = {0x3C, 0x00};
   const LogicalSegmentExtendedLogicalType extended_type =
@@ -335,7 +505,7 @@ TEST(CipEpath, GetElectronicKeyFormat4FromMessage) {
 TEST(CipEpath, GetLogicalSegmentElectronicKeyFormat4) {
   /* Size of an electronic key is 1 + 1 + 8 (Segment, Key format, Key) */
   const CipOctet message[] =
-  {0x34, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x04, 0x05};
+  { 0x34, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x04, 0x05};
   const CipOctet *message_pp = (const CipOctet *)message;
   const CipOctet *message_buffer = message;
   ElectronicKeyFormat4 *electronic_key = ElectronicKeyFormat4New();
@@ -430,7 +600,6 @@ TEST(CipEpath, GetPathDataSegmentSimpleDataWordLength) {
   CHECK_EQUAL(37, length);
 }
 
-
 TEST(CipEpath, GetPathSymbolicSegmentFormatASCII) {
   const unsigned char message[] = {0x61};
   SymbolicSegmentFormat format = GetPathSymbolicSegmentFormat(message);

+ 76 - 16
source/tests/enet_encap/endianconvtest.cpp

@@ -19,44 +19,104 @@ extern "C" {
 
 }
 
-TEST_GROUP(EndianConversion) {
+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);
+  const CipOctet test_message[] = {8};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipSint returned_value = GetSintFromMessage(message);
+
+  LONGS_EQUAL(8, returned_value);
+  POINTERS_EQUAL(test_message + 1, *message);
+}
+
+TEST(EndianConversion, GetUsintFromMessage) {
+  const CipOctet test_message[] = {8};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipUsint returned_value = GetUsintFromMessage(message);
+
+  LONGS_EQUAL(8, returned_value);
+  POINTERS_EQUAL(test_message + 1, *message);
+}
+
+TEST(EndianConversion, GetByteFromMessage) {
+  const CipOctet test_message[] = {8};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipByte returned_value = GetByteFromMessage(message);
 
   LONGS_EQUAL(8, returned_value);
   POINTERS_EQUAL(test_message + 1, *message);
 }
 
 TEST(EndianConversion, GetIntFromMessage) {
-  const EipUint8 test_message[] = { 8, 60 };
-  const EipUint8 *message_pointer = test_message;
-  const EipUint8 **const message = &message_pointer;
-  EipUint16 returned_value = GetIntFromMessage(message);
+  const CipOctet test_message[] = {8, 60};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipInt returned_value = GetIntFromMessage(message);
+
+  LONGS_EQUAL(15368, returned_value);
+  POINTERS_EQUAL(test_message + 2, *message);
+}
+
+TEST(EndianConversion, GetUintFromMessage) {
+  const CipOctet test_message[] = {8, 60};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipUint returned_value = GetUintFromMessage(message);
+
+  LONGS_EQUAL(15368, returned_value);
+  POINTERS_EQUAL(test_message + 2, *message);
+}
+
+TEST(EndianConversion, GetWordFromMessage) {
+  const CipOctet test_message[] = {8, 60};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipWord returned_value = GetWordFromMessage(message);
 
   LONGS_EQUAL(15368, returned_value);
   POINTERS_EQUAL(test_message + 2, *message);
 }
 
 TEST(EndianConversion, GetDintFromMessage) {
-  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);
+  const CipOctet test_message[] = {28, 53, 41, 37};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipDint returned_value = GetDintFromMessage(message);
+
+  LONGS_EQUAL(623457564, returned_value);
+  POINTERS_EQUAL(test_message + 4, *message);
+}
+
+TEST(EndianConversion, GetUdintFromMessage) {
+  const CipOctet test_message[] = {28, 53, 41, 37};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipUdint returned_value = GetUdintFromMessage(message);
+
+  LONGS_EQUAL(623457564, returned_value);
+  POINTERS_EQUAL(test_message + 4, *message);
+}
+
+TEST(EndianConversion, GetDwordFromMessage) {
+  const CipOctet test_message[] = {28, 53, 41, 37};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
+  CipDword returned_value = GetDwordFromMessage(message);
 
   LONGS_EQUAL(623457564, returned_value);
   POINTERS_EQUAL(test_message + 4, *message);
 }
 
 TEST(EndianConversion, GetLintFromMessage) {
-  const EipUint8 test_message[] = { 81, 126, 166, 15, 70, 97, 208, 236 };
-  const EipUint8 *message_pointer = test_message;
-  const EipUint8 **const message = &message_pointer;
+  const CipOctet test_message[] = {81, 126, 166, 15, 70, 97, 208, 236};
+  const CipOctet *message_pointer = test_message;
+  const CipOctet **const message = &message_pointer;
   EipUint64 returned_value = GetLintFromMessage(message);
 
   LONGS_EQUAL(5872313548673241324, returned_value);

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor