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

Merge pull request #328 from EIPStackGroup/CorrectEndianConv

Correct endian conv
Martin Melik-Merkumians 5 лет назад
Родитель
Сommit
1f10ff3155

+ 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;
 }
 
@@ -334,9 +336,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;
@@ -348,25 +350,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,
@@ -374,46 +374,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;
   }
 }
@@ -421,9 +418,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;
@@ -469,9 +466,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,
@@ -479,11 +476,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,
@@ -596,8 +593,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);
     }
   }
@@ -626,23 +623,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;
     }
   }
 }
@@ -677,8 +680,8 @@ int DecodeData(const EipUint8 cip_data_type,
                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):
@@ -692,7 +695,7 @@ int DecodeData(const EipUint8 cip_data_type,
     case (kCipInt):
     case (kCipUint):
     case (kCipWord):
-      (*(EipUint16 *) (cip_data) ) = GetIntFromMessage(cip_message);
+      (*(EipUint16 *) (cip_data) ) = GetUintFromMessage(cip_message);
       number_of_decoded_bytes = 2;
       break;
 
@@ -700,7 +703,7 @@ int DecodeData(const EipUint8 cip_data_type,
     case (kCipUdint):
     case (kCipDword):
     case (kCipReal):
-      (*(EipUint32 *) (cip_data) ) = GetDintFromMessage(cip_message);
+      (*(EipUint32 *) (cip_data) ) = GetUdintFromMessage(cip_message);
       number_of_decoded_bytes = 4;
       break;
 
@@ -714,13 +717,13 @@ int DecodeData(const EipUint8 cip_data_type,
 
     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++;
       }
@@ -749,10 +752,10 @@ int DecodeData(const EipUint8 cip_data_type,
 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++;
   }
@@ -766,12 +769,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;
@@ -780,13 +783,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;
 
@@ -804,19 +806,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;
@@ -827,8 +829,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;
@@ -842,7 +844,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,
@@ -852,20 +854,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);
@@ -875,7 +876,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;
 
@@ -888,7 +889,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;
 
@@ -901,12 +902,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 +
@@ -922,7 +923,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) {

Разница между файлами не показана из-за своего большого размера
+ 272 - 307
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;

+ 10 - 10
source/src/cip/cipepath.c

@@ -287,15 +287,15 @@ CipDword CipEpathGetLogicalValue(const EipUint8 **message) {
   (*message) += 1; /* Move to logical value */
   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! */
@@ -406,12 +406,12 @@ void GetElectronicKeyFormat4FromMessage(const CipOctet **const message,
                   *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 ***/
@@ -492,7 +492,7 @@ CipUdint GetPathNetworkSegmentProductionInhibitTimeInMicroseconds(
   OPENER_ASSERT(2 == *(cip_path + 1) );
 
   const unsigned char *message_runner = cip_path + 2;
-  return GetDintFromMessage(&message_runner);
+  return GetUdintFromMessage(&message_runner);
 }
 
 /*** Network Segment ***/
@@ -604,7 +604,7 @@ CipUsint GetPathDataSegmentSimpleDataWordLength(
                 GetPathDataSegmentSubtype(cip_path) );
 
   const unsigned char *message_runner = cip_path + 1;
-  return GetSintFromMessage(&message_runner);
+  return GetUsintFromMessage(&message_runner);
 }
 
 /*** End Data Segment ***/

+ 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;

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

@@ -26,9 +26,9 @@ OpenerEndianess g_opener_platform_endianess = kOpenerEndianessUnknown;
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT8 data value
  */
-CipSint GetSintFromMessage(const CipOctet **const buffer) {
-  const CipOctet *buffer_address = (unsigned char *) *buffer;
-  CipSint data = buffer_address[0];
+CipSint GetSintFromMessage(const EipUint8 **const buffer) {
+  const unsigned char *const buffer_address = (unsigned char *) *buffer;
+  EipUint8 data = buffer_address[0];
   *buffer += 1;
   return data;
 }
@@ -54,7 +54,7 @@ CipUsint GetUsintFromMessage(const CipOctet **const buffer_address) {
  *   @param buffer pointer where data should be reed.
  *   @return EIP_UINT16 data value
  */
-CipInt GetIntFromMessage(const CipOctet **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
  */
-CipDint GetDintFromMessage(const CipOctet **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;

+ 3 - 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
  */
-CipSint GetSintFromMessage(const CipOctet **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
  */
-CipInt GetIntFromMessage(const CipOctet **const buffer);
+CipInt GetIntFromMessage(const EipUint8 **const buffer);
 
 CipUint GetUintFromMessage(const CipOctet **const buffer_address);
 
@@ -48,7 +48,7 @@ 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
  */
-CipDint GetDintFromMessage(const CipOctet **const buffer);
+CipDint GetDintFromMessage(const EipUint8 **const buffer);
 
 CipUdint GetUdintFromMessage(const CipOctet **const buffer_address);
 

Разница между файлами не показана из-за своего большого размера
+ 250 - 253
source/src/ports/generic_networkhandler.c


Некоторые файлы не были показаны из-за большого количества измененных файлов