Переглянути джерело

reworked tracing facilities to create better code especially for production code

Alois Zoitl 16 роки тому
батько
коміт
1b2e106d07

+ 8 - 2
.cproject

@@ -135,7 +135,6 @@
 <buildTargets>
 <target name="all" path="bin/pc" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
 <buildCommand>make</buildCommand>
-<buildArguments/>
 <buildTarget>all</buildTarget>
 <stopOnError>true</stopOnError>
 <useDefaultCommand>true</useDefaultCommand>
@@ -143,12 +142,19 @@
 </target>
 <target name="clean" path="bin/pc" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
 <buildCommand>make</buildCommand>
-<buildArguments/>
 <buildTarget>clean</buildTarget>
 <stopOnError>true</stopOnError>
 <useDefaultCommand>true</useDefaultCommand>
 <runAllBuilders>true</runAllBuilders>
 </target>
+<target name="all_release" path="bin/pc" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
+<buildCommand>make</buildCommand>
+<buildArguments>-f Makefile.release</buildArguments>
+<buildTarget>all</buildTarget>
+<stopOnError>true</stopOnError>
+<useDefaultCommand>false</useDefaultCommand>
+<runAllBuilders>true</runAllBuilders>
+</target>
 </buildTargets>
 </storageModule>
 </cconfiguration>

+ 1 - 3
TODO

@@ -8,9 +8,7 @@ This file serves as brainstorming buffer for ideas to improve and enhance OpENer
 
 
 * Improvements and Optimizations
-  - test exclusive owner connections (inputs/outputs)
-  - Handle errno == EINTR do continue else 
-  - Rework logging and tracing facility
+  - Test exclusive owner connections (inputs/outputs)
   - Remove the need for the response buffer in the explicit message handling (zero copy stack)
   - Rework I/O message handling:
      - own buffers for each connection that are preconfigured and only runtime data needs to be changed.

+ 3 - 7
bin/pc/Makefile

@@ -5,10 +5,6 @@
 # * Contributors:
 # *     <date>: <author>, <author email> - changes
 # ******************************************************************************
-SILENT=0		# do not print, terminal is not available
-TERSE=1			# error and connection up/down messages only
-VERBOSE=2		# running commentary
-VVERBOSE=3		# commentary plus message dumps
 
 CFLAGS= \
 	-g \
@@ -17,7 +13,8 @@ CFLAGS= \
 	-I ../../src/enet_encap \
 	-I ../../src/cip \
 	-I ../../src/ports/platform-pc \
-	-DEIP_DEBUG=$(VERBOSE) \
+	-DOPENER_WITH_TRACES \
+	-DOPENER_TRACE_LEVEL=0xFF \
 	-W -Wall -ansi
 
 LDFLAGS=
@@ -49,8 +46,7 @@ OBJECTS= \
 	../../src/cip/cipethernetlink.o \
 	../../src/enet_encap/cpf.o \
 	../../src/enet_encap/endianconv.o \
-	../../src/enet_encap/encap.o \
-	../../src/ports/platform-pc/stubs.o
+	../../src/enet_encap/encap.o
 
 
 EXECUTABLE=opener

+ 84 - 0
bin/pc/Makefile.release

@@ -0,0 +1,84 @@
+#*******************************************************************************
+# * Copyright (c) 2009, Rockwell Automation, Inc.
+# * All rights reserved. 
+# *
+# * Contributors:
+# *     <date>: <author>, <author email> - changes
+# ******************************************************************************
+
+CFLAGS= \
+	-O2 \
+	-I . \
+	-I ../../src \
+	-I ../../src/enet_encap \
+	-I ../../src/cip \
+	-I ../../src/ports/platform-pc \
+	-W -Wall -ansi
+
+LDFLAGS=
+
+SOURCES= \
+	../../src/ports/platform-pc/main.c \
+	../../src/cip/cipconnectionmanager.c	\
+	../../src/cip/cipcommon.c \
+	../../src/cip/cipmessagerouter.c \
+	../../src/cip/cipassembly.c \
+	../../src/cip/ciptcpipinterface.c \
+	../../src/cip/cipidentity.c \
+	../../src/cip/cipethernetlink.c \
+	../../src/enet_encap/cpf.c \
+	../../src/enet_encap/endianconv.c \
+	../../src/enet_encap/encap.c \
+	../../src/ports/platform-pc/networkhandler.c
+
+
+OBJECTS= \
+	../../src/ports/platform-pc/main.o \
+	../../src/ports/platform-pc/networkhandler.o \
+	../../src/cip/cipconnectionmanager.o \
+	../../src/cip/cipcommon.o \
+	../../src/cip/cipmessagerouter.o \
+	../../src/cip/cipassembly.o \
+	../../src/cip/ciptcpipinterface.o \
+	../../src/cip/cipidentity.o \
+	../../src/cip/cipethernetlink.o \
+	../../src/enet_encap/cpf.o \
+	../../src/enet_encap/endianconv.o \
+	../../src/enet_encap/encap.o
+
+
+EXECUTABLE=opener_rel
+
+
+all: $(SOURCES) $(EXECUTABLE)
+	
+$(EXECUTABLE): $(OBJECTS) Makefile
+	@echo "  [LD]	" $@
+	@$(CC) $(LDFLAGS) $(OBJECTS) -o $@
+
+# pull in dependency info for *existing* .o files
+-include ./.deps/*.d
+-include ../ethernet/.deps/*.d
+-include ../cip/.deps/*.d
+
+# compile and generate dependency info;
+# see http://www.cs.berkeley.edu/~smcpeak/autodepend/autodepend.html
+
+DEP="`dirname $*`/.deps/`basename $*.d`"
+
+%.o: %.c Makefile
+	@echo "  [CC]	" $*.c
+	@$(CC) -c $(CFLAGS) $*.c -o $*.o
+	@install -d `dirname $*`/.deps
+	@$(CC) -MM $(CFLAGS) $*.c > $(DEP)
+	@mv -f $(DEP) $(DEP).tmp
+	@sed -e 's|.*:|$*.o:|' < $(DEP).tmp > $(DEP)
+	@sed -e 's/.*://' -e 's/\\$$//' < $(DEP).tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $(DEP)
+	@rm -f $(DEP).tmp
+
+
+clean :
+	@echo "  [CLEAN]"
+	@-rm -f $(EXECUTABLE) $(OBJECTS)
+	@-find .. -name .deps | xargs rm -rf
+

+ 63 - 60
src/cip/cipassembly.c

@@ -10,74 +10,77 @@
 #include "cipassembly.h"
 #include "cipcommon.h"
 #include "opener_api.h"
+#include "trace.h"
 
+S_CIP_Class *
+createAssemblyClass()
+{ /* create the CIP Assembly object with zero instances */
+  return createCIPClass(CIP_ASSEMBLY_CLASS_CODE, 0, /* # class attributes*/
+  0xffffffff, /* class getAttributeAll mask*/
+  0, /* # class services*/
+  1, /* # instance attributes*/
+  0xffffffff, /* instance getAttributeAll mask*/
+  0, /* # instance services*/
+  0, /* # instances*/
+  "assembly", 1);
+}
 
-S_CIP_Class *createAssemblyClass()
-  { /* create the CIP Assembly object with zero instances */
-    return createCIPClass(CIP_ASSEMBLY_CLASS_CODE, 0, /* # class attributes*/
-            0xffffffff, /* class getAttributeAll mask*/
-            0, /* # class services*/
-            1, /* # instance attributes*/
-            0xffffffff, /* instance getAttributeAll mask*/
-            0, /* # instance services*/
-            0, /* # instances*/
-            "assembly", 1);
-  }
+EIP_STATUS
+CIP_Assembly_Init()
+{ /* create the CIP Assembly object with zero instances */
+  return createAssemblyClass() ? EIP_OK : EIP_ERROR;
+}
 
+S_CIP_Instance *
+createAssemblyObject(EIP_UINT8 pa_nInstanceID, EIP_BYTE * pa_data,
+    EIP_UINT16 pa_datalength)
+{
+  S_CIP_Class *pstAssemblyClass;
+  S_CIP_Instance *pstAssemblyInstance;
+  S_CIP_Byte_Array *stAssemblyByteArray;
 
-EIP_STATUS CIP_Assembly_Init()
-  { /* create the CIP Assembly object with zero instances */
-    return createAssemblyClass() ? EIP_OK : EIP_ERROR;
-  }
+  if (0 == (pstAssemblyClass = getCIPClass(CIP_ASSEMBLY_CLASS_CODE)))
+    {
+      if (0 == (pstAssemblyClass = createAssemblyClass()))
+        {
+          return 0;
+        }
+    }
 
-S_CIP_Instance *createAssemblyObject(EIP_UINT8 pa_nInstanceID,
-    EIP_BYTE * pa_data, EIP_UINT16 pa_datalength)
-  {
-    S_CIP_Class *pstAssemblyClass;
-    S_CIP_Instance *pstAssemblyInstance;
-    S_CIP_Byte_Array *stAssemblyByteArray;
+  pstAssemblyInstance = addCIPInstance(pstAssemblyClass, pa_nInstanceID); /* add instances (always succeeds (or asserts))*/
 
-    if (0 == (pstAssemblyClass = getCIPClass(CIP_ASSEMBLY_CLASS_CODE)))
-      {
-        if (0 == (pstAssemblyClass = createAssemblyClass()))
-          {
-            return 0;
-          }
-      }
+  if ((stAssemblyByteArray = (S_CIP_Byte_Array *) IApp_CipCalloc(1,
+      sizeof(S_CIP_Byte_Array))) == 0)
+    {
+      return 0; /*TODO remove assembly instance in case of error*/
+    }
 
-    pstAssemblyInstance = addCIPInstance(pstAssemblyClass, pa_nInstanceID); /* add instances (always succeeds (or asserts))*/
+  stAssemblyByteArray->len = pa_datalength;
+  stAssemblyByteArray->Data = pa_data;
+  insertAttribute(pstAssemblyInstance, 3, CIP_BYTE_ARRAY, stAssemblyByteArray);
 
-    if ((stAssemblyByteArray = (S_CIP_Byte_Array *)IApp_CipCalloc(1, sizeof(S_CIP_Byte_Array))) == 0)
-      {
-        return 0; /*TODO remove assembly instance in case of error*/
-      }
+  return pstAssemblyInstance;
+}
 
-    stAssemblyByteArray->len = pa_datalength;
-    stAssemblyByteArray->Data = pa_data;
-    insertAttribute(pstAssemblyInstance, 3, CIP_BYTE_ARRAY, stAssemblyByteArray);
+EIP_STATUS
+notifyAssemblyConnectedDataReceived(S_CIP_Instance * pa_pstInstance,
+    EIP_UINT8 * pa_pnData, EIP_UINT16 pa_nDataLength)
+{
+  S_CIP_Byte_Array *p;
 
-    return pstAssemblyInstance;
-  }
+  /* empty path (path size = 0) need to be checked and taken care of in future */
+  /* copy received data to Attribute 3 */
+  p = (S_CIP_Byte_Array *) pa_pstInstance->pstAttributes->pt2data;
+  if (p->len < pa_nDataLength)
+    {
+      OPENER_TRACE_ERR("too much data arrived\n");
+      return EIP_ERROR; /*TODO question should we notify the application that wrong data has been recieved???*/
+    }
+  else
+    {
+      memcpy(p->Data, pa_pnData, pa_nDataLength);
+      /* call the application that new data arrived */
+    }
 
-EIP_STATUS notifyAssemblyConnectedDataReceived(S_CIP_Instance * pa_pstInstance,
-    EIP_UINT8 * pa_pnData, EIP_UINT16 pa_nDataLength)
-  {
-    S_CIP_Byte_Array *p;
-    
-    /* empty path (path size = 0) need to be checked and taken care of in future */
-    /* copy received data to Attribute 3 */
-    p = (S_CIP_Byte_Array *)pa_pstInstance->pstAttributes->pt2data;
-    if (p->len < pa_nDataLength)
-      {
-        if (EIP_DEBUG>EIP_VERBOSE)
-          printf("too much data arrived\n");
-        return EIP_ERROR; /*TODO question should we notify the application that wrong data has been recieved???*/
-      }
-    else
-      {
-        memcpy(p->Data, pa_pnData, pa_nDataLength);
-        /* call the application that new data arrived */
-      }
-    
-    return IApp_AfterAssemblyDataReceived(pa_pstInstance);
-  }
+  return IApp_AfterAssemblyDataReceived(pa_pstInstance);
+}

+ 555 - 560
src/cip/cipcommon.c

@@ -22,6 +22,7 @@
 #include "cipassembly.h"
 #include "cipmessagerouter.h"
 #include "cpf.h"
+#include "trace.h"
 
 /* global public variables */
 EIP_UINT8 g_acMessageDataReplyBuffer[OPENER_MESSAGE_DATA_REPLY_BUFFER];
@@ -34,582 +35,576 @@ EIP_UINT8 g_acMessageDataReplyBuffer[OPENER_MESSAGE_DATA_REPLY_BUFFER];
  *  @return length of attribute in bytes
  *          -1 .. error
  */
-int outputAttribute(S_CIP_attribute_struct *pa_ptstAttribute,
-    EIP_UINT8 *pa_pnMsg);
-
-void CIP_Init(void)
-  {
-    printf("CIP_Init: calling encapInit\n");
-    encapInit();
-    /* The message router is the first CIP object that has to be initialized first!!! */
-    assert(CIP_MessageRouter_Init() == EIP_OK);
-    assert(CIP_Identity_Init() == EIP_OK);
-    assert(CIP_TCPIP_Interface_Init() == EIP_OK);
-    assert(CIP_Ethernet_Link_Init() == EIP_OK);
-    assert(Connection_Manager_Init() == EIP_OK);
-    assert(CIP_Assembly_Init() == EIP_OK);
-    /* the application has to be initiliazed at last */
-    assert(IApp_Init() == EIP_OK);
-  }
-
-EIP_STATUS notifyClass(S_CIP_Class * pt2Class, 
-    S_CIP_MR_Request * pa_MRRequest, 
+int
+outputAttribute(S_CIP_attribute_struct *pa_ptstAttribute, EIP_UINT8 *pa_pnMsg);
+
+void
+CIP_Init(void)
+{
+  encapInit();
+  /* The message router is the first CIP object that has to be initialized first!!! */
+  assert(CIP_MessageRouter_Init() == EIP_OK);
+  assert(CIP_Identity_Init() == EIP_OK);
+  assert(CIP_TCPIP_Interface_Init() == EIP_OK);
+  assert(CIP_Ethernet_Link_Init() == EIP_OK);
+  assert(Connection_Manager_Init() == EIP_OK);
+  assert(CIP_Assembly_Init() == EIP_OK);
+  /* the application has to be initiliazed at last */
+  assert(IApp_Init() == EIP_OK);
+}
+
+EIP_STATUS
+notifyClass(S_CIP_Class * pt2Class, S_CIP_MR_Request * pa_MRRequest,
     S_CIP_MR_Response * pa_MRResponse)
-  {
-    int i;
-    S_CIP_Instance *pstInstance;
-    S_CIP_service_struct *p;
-    unsigned instNr; /* my instance number */
-
-    /* find the instance: if instNr==0, the class is addressed, else find the instance */
-    instNr = pa_MRRequest->RequestPath.InstanceNr; /* get the instance number */
-    pstInstance = getCIPInstance(pt2Class, instNr); /* look up the instance (note that if inst==0 this will be the class itself) */
-    if (pstInstance) /* if instance is found */
-      {
-        if (EIP_DEBUG >= EIP_VVERBOSE)
-          {
-            printf("notify: found instance %d%s\n", instNr,
-                instNr==0 ? " (class object)" : "");
-          }
-        p = pstInstance->pstClass->pstServices; /* get pointer to array of services */
-        if (p) /* if services are defined */
-          {
-            for (i = 0; i < pstInstance->pstClass->nNr_of_Services; i++) /* seach the services list */
-              {
-                if (pa_MRRequest->Service == p->CIP_ServiceNr) /* if match is found */
-                  {
-                    pa_MRResponse->Data = &g_acMessageDataReplyBuffer[0]; /* set reply buffer, using a fixed buffer (about 100 bytes) */
-                    /* call the service, and return what it returns */
-                    if (EIP_DEBUG>=EIP_VERBOSE)
-                      printf("notify: calling %s service\n", p->name);
-                    assert(p->m_ptfuncService);
-                    return p->m_ptfuncService(pstInstance, pa_MRRequest,
-                        pa_MRResponse, &g_acMessageDataReplyBuffer[0]);
-                  }
-                else
-                  p++;
-              }
-          }
-        if (EIP_DEBUG>=EIP_TERSE)
-          printf("notify: service 0x%x not supported\n", pa_MRRequest->Service);
-        pa_MRResponse->GeneralStatus = CIP_ERROR_SERVICE_NOT_SUPPORTED; /* if no services or service not found, return an error reply*/
-      }
-    else
-      {
-        if (EIP_DEBUG>=EIP_TERSE)
-          printf("notify: instance number %d unknown\n", instNr);
-        /* if instance not found, return an error reply*/
-        pa_MRResponse->GeneralStatus = CIP_ERROR_PATH_DESTINATION_UNKNOWN; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
-      }
-
-    /* handle error replies*/
-    pa_MRResponse->SizeofAdditionalStatus = 0; /* fill in the rest of the reply with not much of anything*/
-    pa_MRResponse->DataLength = 0;
-    pa_MRResponse->ReplyService = (0x80 | pa_MRRequest->Service); /* except the reply code is an echo of the command + the reply flag */
-
-    return EIP_OK_SEND;
-  }
-
-S_CIP_Instance *addCIPInstances(S_CIP_Class * pa_pstCIPClass,  int pa_nNr_of_Instances) 
-  {
-    S_CIP_Instance *first, *p, **pp;
-    int i;
-    int inst=1; /* the first instance is number 1 */
-
-    if (EIP_DEBUG>=EIP_VERBOSE)
-      printf("adding %d instances to class %s\n", pa_nNr_of_Instances,
-          pa_pstCIPClass->acName);
-
-    pp = &pa_pstCIPClass->pstInstances; /* get address of pointer to head of chain */
-    while (*pp) /* as long as what pp points to is not zero */
-      {
-        pp = &(*pp)->pstNext; /*    follow the chain until pp points to pointer that contains a zero */
-        inst++; /*    keep track of what the first new instance number will be */
-      }
-
-    first = p = (S_CIP_Instance *) IApp_CipCalloc(pa_nNr_of_Instances, sizeof(S_CIP_Instance)); /* allocate a block of memory for all created instances*/
-    assert(p);
-    /* fail if run out of memory */
-
-    pa_pstCIPClass->nNr_of_Instances += pa_nNr_of_Instances; /* add the number of instances just created to the total recorded by the class */
-
-    for (i = 0; i < pa_nNr_of_Instances; i++) /* initialize all the new instances */
-      {
-        *pp = p; /* link the previous pointer to this new node */
-
-        p->nInstanceNr = inst; /* assign the next sequential instance number */
-        p->pstClass = pa_pstCIPClass; /* point each instance to its class */
-
-        if (pa_pstCIPClass->nNr_of_Attributes) /* if the class calls for instance attributes */
-          { /* then allocate storage for the attribute array */
-            p->pstAttributes = (S_CIP_attribute_struct*)IApp_CipCalloc(
-                pa_pstCIPClass->nNr_of_Attributes,
-                sizeof(S_CIP_attribute_struct));
-          }
-
-        pp = &p->pstNext; /* update pp to point to the next link of the current node */
-        inst++; /* update to the number of the next node*/
-        p++; /* point to the next node in the calloc'ed array*/
-      }
-
-    return first;
-  }
-
-S_CIP_Instance *addCIPInstance(S_CIP_Class * pa_pstCIPClass,  EIP_UINT32 pa_nInstanceId)
-  {
-    S_CIP_Instance *pstInstance =
-        getCIPInstance(pa_pstCIPClass, pa_nInstanceId);
-
-    if (0 == pstInstance)
-      { /*we have no instance with given id*/
-        pstInstance = addCIPInstances(pa_pstCIPClass, 1);
-        pstInstance->nInstanceNr = pa_nInstanceId;
-      }
-    return pstInstance;
-  }
-
-S_CIP_Class *createCIPClass(EIP_UINT32 pa_nClassID,
-    int pa_nNr_of_ClassAttributes, EIP_UINT32 pa_nClassGetAttrAllMask,
-    int pa_nNr_of_ClassServices, int pa_nNr_of_InstanceAttributes,
-    EIP_UINT32 pa_nInstGetAttrAllMask, int pa_nNr_of_InstanceServices,
-    int pa_nNr_of_Instances, char *pa_acName, EIP_UINT16 pa_nRevision)
-  {
-    S_CIP_Class *pt2Class; /* pointer to the class struct */
-    S_CIP_Class *pt2MetaClass; /* pointer to the metaclass struct */
-
-    printf("creating class '%s' with id: 0x%lx\n", pa_acName, pa_nClassID);
-
-    pt2Class = getCIPClass(pa_nClassID); /* check if an class with the ClassID already exists */
-    assert(pt2Class==0);
-    /* 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*/
-
-    pt2Class = (S_CIP_Class*)IApp_CipCalloc(1, sizeof(S_CIP_Class)); /* create the class object*/
-    pt2MetaClass = (S_CIP_Class*)IApp_CipCalloc(1, sizeof(S_CIP_Class)); /* create the metaclass object*/
-
-    /* initialize the class-specific fields of the Class struct*/
-    pt2Class->nClassID = pa_nClassID; /* the class remembers the class ID */
-    pt2Class->nRevision = pa_nRevision; /* the class remembers the class ID */
-    pt2Class->nNr_of_Instances = 0; /* the number of instances initially zero (more created below) */
-    pt2Class->pstInstances = 0; 
-    pt2Class->nNr_of_Attributes = pa_nNr_of_InstanceAttributes; /* the class remembers the number of instances of that class */
-    pt2Class->nGetAttrAllMask = pa_nInstGetAttrAllMask; /* indicate which attributes are included in instance getAttributeAll */
-    pt2Class->nNr_of_Services = pa_nNr_of_InstanceServices+2; /* the class manages the behavior of the instances */
-    pt2Class->pstServices = 0; 
-    pt2Class->acName = pa_acName; /* initialize the class-specific fields of the metaClass struct */
-    pt2MetaClass->nClassID = 0xffffffff; /* set metaclass ID (this should never be referenced) */
-    pt2MetaClass->nNr_of_Instances = 1; /* the class object is the only instance of the metaclass */
-    pt2MetaClass->pstInstances = (S_CIP_Instance *)pt2Class; 
-    pt2MetaClass->nNr_of_Attributes = pa_nNr_of_ClassAttributes+5; /* the metaclass remembers how many class attributes exist*/
-    pt2MetaClass->nGetAttrAllMask = pa_nClassGetAttrAllMask; /* indicate which attributes are included in class getAttributeAll*/
-    pt2MetaClass->nNr_of_Services = pa_nNr_of_ClassServices+2; /* the metaclass manages the behavior of the class itself */
-    pt2Class->pstServices = 0; 
-    pt2MetaClass->acName = (char *)IApp_CipCalloc(1, strlen(pa_acName)+6); /* fabricate the name "meta<classname>"*/
-    strcpy(pt2MetaClass->acName, "meta-");
-    strcat(pt2MetaClass->acName, pa_acName);
-
-    /* initialize the instance-specific fields of the Class struct*/
-    pt2Class->nInstanceNr = 0; /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
-    pt2Class->pstAttributes = 0; /* this will later point to the class attibutes*/
-    pt2Class->pstClass = pt2MetaClass; /* the class's class is the metaclass (like SmallTalk)*/
-    pt2Class->pstNext = 0; /* the next link will always be zero, sinc there is only one instance of any particular class object */
-
-    pt2MetaClass->nInstanceNr = 0xffffffff; /*the metaclass object does not really have a valid instance number*/
-    pt2MetaClass->pstAttributes = 0; /* the metaclass has no attributes*/
-    pt2MetaClass->pstClass = 0; /* the metaclass has no class*/
-    pt2MetaClass->pstNext = 0; /* the next link will always be zero, since there is only one instance of any particular metaclass object*/
-
-
-    /* further initialization of the class object*/
-
-    pt2Class->pstAttributes = (S_CIP_attribute_struct *)IApp_CipCalloc(pa_nNr_of_ClassAttributes+5,
-        sizeof(S_CIP_attribute_struct));
-    /* TODO -- check that we didn't run out of memory?*/
-
-    pt2MetaClass->pstServices = (S_CIP_service_struct *)IApp_CipCalloc(pa_nNr_of_ClassServices+2,
-        sizeof(S_CIP_service_struct));
-
-    pt2Class->pstServices = (S_CIP_service_struct *)IApp_CipCalloc(pa_nNr_of_InstanceServices+2,
-        sizeof(S_CIP_service_struct));
-
-    if (pa_nNr_of_Instances > 0)
-      {
-        addCIPInstances(pt2Class, pa_nNr_of_Instances); /*TODO handle return value and clean up if necessary*/
-      }
-
-    if ((registerClass(pt2Class)) == EIP_ERROR)
-      { /* no memory to register class in Message Router */
-        return 0; /*TODO handle return value and clean up if necessary*/
-      }
-
-    /* create the standard class attributes*/
-    insertAttribute((S_CIP_Instance *)pt2Class, 1, CIP_UINT,
-        (void *)&pt2Class->nRevision); /* revision */
-    insertAttribute((S_CIP_Instance *)pt2Class, 2, CIP_UINT,
-        (void *)&pt2Class->nNr_of_Instances); /*  largest instance number */
-    insertAttribute((S_CIP_Instance *)pt2Class, 3, CIP_UINT,
-        (void *)&pt2Class->nNr_of_Instances); /* number of instances currently existing*/
-    insertAttribute((S_CIP_Instance *)pt2Class, 6, CIP_UINT,
-        (void *)&pt2MetaClass->nMaxAttribute); /* max class attribute number*/
-    insertAttribute((S_CIP_Instance *)pt2Class, 7, CIP_UINT,
-        (void *)&pt2Class->nMaxAttribute); /* max instance attribute number*/
-
-
-    /* create the standard class services*/
-    insertService(pt2MetaClass, CIP_GET_ATTRIBUTE_ALL, &getAttributeAll,
-        "GetAttributeAll"); /* bind instance services to the metaclass*/
-    insertService(pt2MetaClass, CIP_GET_ATTRIBUTE_SINGLE, &getAttributeSingle,
-        "GetAttributeSingle");
-
-    /* create the standard instance services*/
-    insertService(pt2Class, CIP_GET_ATTRIBUTE_ALL, &getAttributeAll,
-        "GetAttributeAll"); /* bind instance services to the class*/
-    insertService(pt2Class, CIP_GET_ATTRIBUTE_SINGLE, &getAttributeSingle,
-        "GetAttributeSingle");
-
-    return pt2Class;
-  }
-
-void insertAttribute(S_CIP_Instance * pa_pInstance, EIP_UINT8 pa_nAttributeNr, EIP_UINT8 pa_nCIP_Type,  void *pa_pt2data) 
-  {
-    int i;
-    S_CIP_attribute_struct *p;
-
-    p = pa_pInstance->pstAttributes;
-    assert(p!=0);
-    /* adding a attribute to a class that was not declared to have any attributes is not allowed */
-    for (i = 0; i < pa_pInstance->pstClass->nNr_of_Attributes; i++)
-      {
-        if (p->pt2data == 0)
-          { /* found non set attribute */
-            p->CIP_AttributNr = pa_nAttributeNr;
-            p->CIP_Type = pa_nCIP_Type;
-            p->pt2data = pa_pt2data;
-
-            if (pa_nAttributeNr > pa_pInstance->pstClass->nMaxAttribute) /* remember the max attribute number that was defined*/
-              {
-                pa_pInstance->pstClass->nMaxAttribute = pa_nAttributeNr;
-              }
-            return;
-          }
-        p++;
-      }
-    assert(0);
-    /* trying to insert too mmany attributes*/
-  }
-
-void insertService(S_CIP_Class * pa_pClass,  EIP_UINT8 pa_nServiceNr,  
+{
+  int i;
+  S_CIP_Instance *pstInstance;
+  S_CIP_service_struct *p;
+  unsigned instNr; /* my instance number */
+
+  /* find the instance: if instNr==0, the class is addressed, else find the instance */
+  instNr = pa_MRRequest->RequestPath.InstanceNr; /* get the instance number */
+  pstInstance = getCIPInstance(pt2Class, instNr); /* look up the instance (note that if inst==0 this will be the class itself) */
+  if (pstInstance) /* if instance is found */
+    {
+      OPENER_TRACE_INFO("notify: found instance %d%s\n", instNr,
+          instNr == 0 ? " (class object)" : "");
+
+      p = pstInstance->pstClass->pstServices; /* get pointer to array of services */
+      if (p) /* if services are defined */
+        {
+          for (i = 0; i < pstInstance->pstClass->nNr_of_Services; i++) /* seach the services list */
+            {
+              if (pa_MRRequest->Service == p->CIP_ServiceNr) /* if match is found */
+                {
+                  pa_MRResponse->Data = &g_acMessageDataReplyBuffer[0]; /* set reply buffer, using a fixed buffer (about 100 bytes) */
+                  /* call the service, and return what it returns */
+                  OPENER_TRACE_INFO("notify: calling %s service\n", p->name);
+                  assert(p->m_ptfuncService);
+                  return p->m_ptfuncService(pstInstance, pa_MRRequest,
+                      pa_MRResponse, &g_acMessageDataReplyBuffer[0]);
+                }
+              else
+                p++;
+            }
+        }OPENER_TRACE_WARN("notify: service 0x%x not supported\n",
+          pa_MRRequest->Service);
+      pa_MRResponse->GeneralStatus = CIP_ERROR_SERVICE_NOT_SUPPORTED; /* if no services or service not found, return an error reply*/
+    }
+  else
+    {
+      OPENER_TRACE_WARN("notify: instance number %d unknown\n", instNr);
+      /* if instance not found, return an error reply*/
+      pa_MRResponse->GeneralStatus = CIP_ERROR_PATH_DESTINATION_UNKNOWN; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
+    }
+
+  /* handle error replies*/
+  pa_MRResponse->SizeofAdditionalStatus = 0; /* fill in the rest of the reply with not much of anything*/
+  pa_MRResponse->DataLength = 0;
+  pa_MRResponse->ReplyService = (0x80 | pa_MRRequest->Service); /* except the reply code is an echo of the command + the reply flag */
+
+  return EIP_OK_SEND;
+}
+
+S_CIP_Instance *
+addCIPInstances(S_CIP_Class * pa_pstCIPClass, int pa_nNr_of_Instances)
+{
+  S_CIP_Instance *first, *p, **pp;
+  int i;
+  int inst = 1; /* the first instance is number 1 */
+
+  OPENER_TRACE_INFO("adding %d instances to class %s\n", pa_nNr_of_Instances,
+      pa_pstCIPClass->acName);
+
+  pp = &pa_pstCIPClass->pstInstances; /* get address of pointer to head of chain */
+  while (*pp) /* as long as what pp points to is not zero */
+    {
+      pp = &(*pp)->pstNext; /*    follow the chain until pp points to pointer that contains a zero */
+      inst++; /*    keep track of what the first new instance number will be */
+    }
+
+  first = p = (S_CIP_Instance *) IApp_CipCalloc(pa_nNr_of_Instances,
+      sizeof(S_CIP_Instance)); /* allocate a block of memory for all created instances*/
+  assert(p);
+  /* fail if run out of memory */
+
+  pa_pstCIPClass->nNr_of_Instances += pa_nNr_of_Instances; /* add the number of instances just created to the total recorded by the class */
+
+  for (i = 0; i < pa_nNr_of_Instances; i++) /* initialize all the new instances */
+    {
+      *pp = p; /* link the previous pointer to this new node */
+
+      p->nInstanceNr = inst; /* assign the next sequential instance number */
+      p->pstClass = pa_pstCIPClass; /* point each instance to its class */
+
+      if (pa_pstCIPClass->nNr_of_Attributes) /* if the class calls for instance attributes */
+        { /* then allocate storage for the attribute array */
+          p->pstAttributes
+              = (S_CIP_attribute_struct*) IApp_CipCalloc(
+                  pa_pstCIPClass->nNr_of_Attributes,
+                  sizeof(S_CIP_attribute_struct));
+        }
+
+      pp = &p->pstNext; /* update pp to point to the next link of the current node */
+      inst++; /* update to the number of the next node*/
+      p++; /* point to the next node in the calloc'ed array*/
+    }
+
+  return first;
+}
+
+S_CIP_Instance *
+addCIPInstance(S_CIP_Class * pa_pstCIPClass, EIP_UINT32 pa_nInstanceId)
+{
+  S_CIP_Instance *pstInstance = getCIPInstance(pa_pstCIPClass, pa_nInstanceId);
+
+  if (0 == pstInstance)
+    { /*we have no instance with given id*/
+      pstInstance = addCIPInstances(pa_pstCIPClass, 1);
+      pstInstance->nInstanceNr = pa_nInstanceId;
+    }
+  return pstInstance;
+}
+
+S_CIP_Class *
+createCIPClass(EIP_UINT32 pa_nClassID, int pa_nNr_of_ClassAttributes,
+    EIP_UINT32 pa_nClassGetAttrAllMask, int pa_nNr_of_ClassServices,
+    int pa_nNr_of_InstanceAttributes, EIP_UINT32 pa_nInstGetAttrAllMask,
+    int pa_nNr_of_InstanceServices, int pa_nNr_of_Instances, char *pa_acName,
+    EIP_UINT16 pa_nRevision)
+{
+  S_CIP_Class *pt2Class; /* pointer to the class struct */
+  S_CIP_Class *pt2MetaClass; /* pointer to the metaclass struct */
+
+  OPENER_TRACE_INFO("creating class '%s' with id: 0x%lx\n", pa_acName, pa_nClassID);
+
+  pt2Class = getCIPClass(pa_nClassID); /* check if an class with the ClassID already exists */
+  assert(pt2Class==0);
+  /* 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*/
+
+  pt2Class = (S_CIP_Class*) IApp_CipCalloc(1, sizeof(S_CIP_Class)); /* create the class object*/
+  pt2MetaClass = (S_CIP_Class*) IApp_CipCalloc(1, sizeof(S_CIP_Class)); /* create the metaclass object*/
+
+  /* initialize the class-specific fields of the Class struct*/
+  pt2Class->nClassID = pa_nClassID; /* the class remembers the class ID */
+  pt2Class->nRevision = pa_nRevision; /* the class remembers the class ID */
+  pt2Class->nNr_of_Instances = 0; /* the number of instances initially zero (more created below) */
+  pt2Class->pstInstances = 0;
+  pt2Class->nNr_of_Attributes = pa_nNr_of_InstanceAttributes; /* the class remembers the number of instances of that class */
+  pt2Class->nGetAttrAllMask = pa_nInstGetAttrAllMask; /* indicate which attributes are included in instance getAttributeAll */
+  pt2Class->nNr_of_Services = pa_nNr_of_InstanceServices + 2; /* the class manages the behavior of the instances */
+  pt2Class->pstServices = 0;
+  pt2Class->acName = pa_acName; /* initialize the class-specific fields of the metaClass struct */
+  pt2MetaClass->nClassID = 0xffffffff; /* set metaclass ID (this should never be referenced) */
+  pt2MetaClass->nNr_of_Instances = 1; /* the class object is the only instance of the metaclass */
+  pt2MetaClass->pstInstances = (S_CIP_Instance *) pt2Class;
+  pt2MetaClass->nNr_of_Attributes = pa_nNr_of_ClassAttributes + 5; /* the metaclass remembers how many class attributes exist*/
+  pt2MetaClass->nGetAttrAllMask = pa_nClassGetAttrAllMask; /* indicate which attributes are included in class getAttributeAll*/
+  pt2MetaClass->nNr_of_Services = pa_nNr_of_ClassServices + 2; /* the metaclass manages the behavior of the class itself */
+  pt2Class->pstServices = 0;
+  pt2MetaClass->acName = (char *) IApp_CipCalloc(1, strlen(pa_acName) + 6); /* fabricate the name "meta<classname>"*/
+  strcpy(pt2MetaClass->acName, "meta-");
+  strcat(pt2MetaClass->acName, pa_acName);
+
+  /* initialize the instance-specific fields of the Class struct*/
+  pt2Class->nInstanceNr = 0; /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
+  pt2Class->pstAttributes = 0; /* this will later point to the class attibutes*/
+  pt2Class->pstClass = pt2MetaClass; /* the class's class is the metaclass (like SmallTalk)*/
+  pt2Class->pstNext = 0; /* the next link will always be zero, sinc there is only one instance of any particular class object */
+
+  pt2MetaClass->nInstanceNr = 0xffffffff; /*the metaclass object does not really have a valid instance number*/
+  pt2MetaClass->pstAttributes = 0; /* the metaclass has no attributes*/
+  pt2MetaClass->pstClass = 0; /* the metaclass has no class*/
+  pt2MetaClass->pstNext = 0; /* the next link will always be zero, since there is only one instance of any particular metaclass object*/
+
+  /* further initialization of the class object*/
+
+  pt2Class->pstAttributes = (S_CIP_attribute_struct *) IApp_CipCalloc(
+      pa_nNr_of_ClassAttributes + 5, sizeof(S_CIP_attribute_struct));
+  /* TODO -- check that we didn't run out of memory?*/
+
+  pt2MetaClass->pstServices = (S_CIP_service_struct *) IApp_CipCalloc(
+      pa_nNr_of_ClassServices + 2, sizeof(S_CIP_service_struct));
+
+  pt2Class->pstServices = (S_CIP_service_struct *) IApp_CipCalloc(
+      pa_nNr_of_InstanceServices + 2, sizeof(S_CIP_service_struct));
+
+  if (pa_nNr_of_Instances > 0)
+    {
+      addCIPInstances(pt2Class, pa_nNr_of_Instances); /*TODO handle return value and clean up if necessary*/
+    }
+
+  if ((registerClass(pt2Class)) == EIP_ERROR)
+    { /* no memory to register class in Message Router */
+      return 0; /*TODO handle return value and clean up if necessary*/
+    }
+
+  /* create the standard class attributes*/
+  insertAttribute((S_CIP_Instance *) pt2Class, 1, CIP_UINT,
+      (void *) &pt2Class->nRevision); /* revision */
+  insertAttribute((S_CIP_Instance *) pt2Class, 2, CIP_UINT,
+      (void *) &pt2Class->nNr_of_Instances); /*  largest instance number */
+  insertAttribute((S_CIP_Instance *) pt2Class, 3, CIP_UINT,
+      (void *) &pt2Class->nNr_of_Instances); /* number of instances currently existing*/
+  insertAttribute((S_CIP_Instance *) pt2Class, 6, CIP_UINT,
+      (void *) &pt2MetaClass->nMaxAttribute); /* max class attribute number*/
+  insertAttribute((S_CIP_Instance *) pt2Class, 7, CIP_UINT,
+      (void *) &pt2Class->nMaxAttribute); /* max instance attribute number*/
+
+  /* create the standard class services*/
+  insertService(pt2MetaClass, CIP_GET_ATTRIBUTE_ALL, &getAttributeAll,
+      "GetAttributeAll"); /* bind instance services to the metaclass*/
+  insertService(pt2MetaClass, CIP_GET_ATTRIBUTE_SINGLE, &getAttributeSingle,
+      "GetAttributeSingle");
+
+  /* create the standard instance services*/
+  insertService(pt2Class, CIP_GET_ATTRIBUTE_ALL, &getAttributeAll,
+      "GetAttributeAll"); /* bind instance services to the class*/
+  insertService(pt2Class, CIP_GET_ATTRIBUTE_SINGLE, &getAttributeSingle,
+      "GetAttributeSingle");
+
+  return pt2Class;
+}
+
+void
+insertAttribute(S_CIP_Instance * pa_pInstance, EIP_UINT8 pa_nAttributeNr,
+    EIP_UINT8 pa_nCIP_Type, void *pa_pt2data)
+{
+  int i;
+  S_CIP_attribute_struct *p;
+
+  p = pa_pInstance->pstAttributes;
+  assert(p!=0);
+  /* adding a attribute to a class that was not declared to have any attributes is not allowed */
+  for (i = 0; i < pa_pInstance->pstClass->nNr_of_Attributes; i++)
+    {
+      if (p->pt2data == 0)
+        { /* found non set attribute */
+          p->CIP_AttributNr = pa_nAttributeNr;
+          p->CIP_Type = pa_nCIP_Type;
+          p->pt2data = pa_pt2data;
+
+          if (pa_nAttributeNr > pa_pInstance->pstClass->nMaxAttribute) /* remember the max attribute number that was defined*/
+            {
+              pa_pInstance->pstClass->nMaxAttribute = pa_nAttributeNr;
+            }
+          return;
+        }
+      p++;
+    }
+  assert(0);
+  /* trying to insert too mmany attributes*/
+}
+
+void
+insertService(S_CIP_Class * pa_pClass, EIP_UINT8 pa_nServiceNr,
     TCIPServiceFunc pa_ptfuncService, char *name)
-  {
-    int i;
-    S_CIP_service_struct *p;
-
-    p = pa_pClass->pstServices; /* get a pointer to the service array*/
-    assert(p!=0);
-    /* adding a service to a class that was not declared to have services is not allowed*/
-    for (i = 0; i < pa_pClass->nNr_of_Services; i++) /* Iterate over all service slots attached to the class */
-      {
-        if (p->CIP_ServiceNr == pa_nServiceNr || p->m_ptfuncService == 0) /* found undefined service slot*/
-          {
-            p->CIP_ServiceNr = pa_nServiceNr; /* fill in service number*/
-            p->m_ptfuncService = pa_ptfuncService; /* fill in function address*/
-            p->name = name;
-            return;
-          }
+{
+  int i;
+  S_CIP_service_struct *p;
+
+  p = pa_pClass->pstServices; /* get a pointer to the service array*/
+  assert(p!=0);
+  /* adding a service to a class that was not declared to have services is not allowed*/
+  for (i = 0; i < pa_pClass->nNr_of_Services; i++) /* Iterate over all service slots attached to the class */
+    {
+      if (p->CIP_ServiceNr == pa_nServiceNr || p->m_ptfuncService == 0) /* found undefined service slot*/
+        {
+          p->CIP_ServiceNr = pa_nServiceNr; /* fill in service number*/
+          p->m_ptfuncService = pa_ptfuncService; /* fill in function address*/
+          p->name = name;
+          return;
+        }
+      p++;
+    }
+  assert(0);
+  /* adding more services than were declared is a no-no*/
+}
+
+S_CIP_attribute_struct *
+getAttribute(S_CIP_Instance * pa_pInstance, EIP_UINT8 pa_nAttributeNr)
+{
+  int i;
+  S_CIP_attribute_struct *p = pa_pInstance->pstAttributes; /* init pointer to array of attributes*/
+  for (i = 0; i < pa_pInstance->pstClass->nNr_of_Attributes; i++)
+    {
+      if (pa_nAttributeNr == p->CIP_AttributNr)
+        return p;
+      else
         p++;
-      }
-    assert(0);
-    /* adding more services than were declared is a no-no*/
-  }
-
-S_CIP_attribute_struct *getAttribute(S_CIP_Instance * pa_pInstance,
-    EIP_UINT8 pa_nAttributeNr)
-  {
-    int i;
-    S_CIP_attribute_struct *p = pa_pInstance->pstAttributes; /* init pointer to array of attributes*/
-    for (i = 0; i < pa_pInstance->pstClass->nNr_of_Attributes; i++)
-      {
-        if (pa_nAttributeNr == p->CIP_AttributNr)
-          return p;
-        else
-          p++;
-      }
-    if (EIP_DEBUG>=EIP_TERSE)
-      printf("attribute %d not defined\n", pa_nAttributeNr);
-    return 0;
-  }
+    }OPENER_TRACE_WARN("attribute %d not defined\n", pa_nAttributeNr);
+  return 0;
+}
 
 /* TODO this needs to check for buffer overflow*/
-EIP_STATUS getAttributeSingle(S_CIP_Instance * pa_pInstance, 
-    S_CIP_MR_Request * pa_stMRRequest, 
-    S_CIP_MR_Response * pa_stMRResponse, 
-    EIP_UINT8 * pa_msg) 
-  {
-    S_CIP_attribute_struct *p = getAttribute(pa_pInstance,
-        pa_stMRRequest->RequestPath.AttributNr);
-
-    if ((p != 0) && (p->pt2data != 0))
-      {
-        if (EIP_DEBUG>=EIP_VERBOSE)
-          printf("getAttribute %ld\n", pa_stMRRequest->RequestPath.AttributNr); /* create a reply message containing the data*/
-        pa_stMRResponse->DataLength = outputAttribute(p, pa_msg);
-        pa_stMRResponse->ReplyService = (0x80 | pa_stMRRequest->Service);
-        pa_stMRResponse->GeneralStatus = CIP_ERROR_SUCCESS;
-        pa_stMRResponse->SizeofAdditionalStatus = 0;
-        return (EIP_STATUS)pa_stMRResponse->DataLength;
-      }
-
-    pa_stMRResponse->DataLength = 0;
-    pa_stMRResponse->ReplyService = (0x80 | pa_stMRRequest->Service);
-    pa_stMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SUPPORTED;
-    pa_stMRResponse->SizeofAdditionalStatus = 0;
-    return EIP_OK;
-  }
-
-int outputAttribute(S_CIP_attribute_struct *pa_ptstAttribute,
-    EIP_UINT8 *pa_pnMsg)
-  {
-    int j;
-    int counter=0;
-
-    switch (pa_ptstAttribute->CIP_Type)
-      /* check the datatype of attribute */
-      {
-    case (CIP_BOOL):
-    case (CIP_SINT):
-    case (CIP_USINT):
-    case (CIP_BYTE):
-      *pa_pnMsg++ = *(EIP_UINT8 *) (pa_ptstAttribute->pt2data);
-      counter = 1;
+EIP_STATUS
+getAttributeSingle(S_CIP_Instance * pa_pInstance,
+    S_CIP_MR_Request * pa_stMRRequest, S_CIP_MR_Response * pa_stMRResponse,
+    EIP_UINT8 * pa_msg)
+{
+  S_CIP_attribute_struct *p = getAttribute(pa_pInstance,
+      pa_stMRRequest->RequestPath.AttributNr);
+
+  if ((p != 0) && (p->pt2data != 0))
+    {
+      OPENER_TRACE_INFO("getAttribute %ld\n",
+          pa_stMRRequest->RequestPath.AttributNr); /* create a reply message containing the data*/
+      pa_stMRResponse->DataLength = outputAttribute(p, pa_msg);
+      pa_stMRResponse->ReplyService = (0x80 | pa_stMRRequest->Service);
+      pa_stMRResponse->GeneralStatus = CIP_ERROR_SUCCESS;
+      pa_stMRResponse->SizeofAdditionalStatus = 0;
+      return (EIP_STATUS) pa_stMRResponse->DataLength;
+    }
+
+  pa_stMRResponse->DataLength = 0;
+  pa_stMRResponse->ReplyService = (0x80 | pa_stMRRequest->Service);
+  pa_stMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SUPPORTED;
+  pa_stMRResponse->SizeofAdditionalStatus = 0;
+  return EIP_OK;
+}
+
+int
+outputAttribute(S_CIP_attribute_struct *pa_ptstAttribute, EIP_UINT8 *pa_pnMsg)
+{
+  int j;
+  int counter = 0;
+
+  switch (pa_ptstAttribute->CIP_Type)
+    /* check the datatype of attribute */
+    {
+  case (CIP_BOOL):
+  case (CIP_SINT):
+  case (CIP_USINT):
+  case (CIP_BYTE):
+    *pa_pnMsg++ = *(EIP_UINT8 *) (pa_ptstAttribute->pt2data);
+    counter = 1;
+    break;
+
+  case (CIP_INT):
+  case (CIP_UINT):
+  case (CIP_WORD):
+    htols(*(EIP_UINT16 *) (pa_ptstAttribute->pt2data), &pa_pnMsg);
+    counter = 2;
+    break;
+
+  case (CIP_DINT):
+  case (CIP_UDINT):
+  case (CIP_DWORD):
+    htoll(*(EIP_UINT32 *) (pa_ptstAttribute->pt2data), &pa_pnMsg);
+    counter = 4;
+    break;
+
+  case (CIP_LINT):
+  case (CIP_ULINT):
+  case (CIP_LWORD):
+    break;
+
+  case (CIP_REAL):
+  case (CIP_LREAL):
+  case (CIP_STIME):
+  case (CIP_DATE):
+  case (CIP_TIME_OF_DAY):
+  case (CIP_DATE_AND_TIME):
+    break;
+  case (CIP_STRING):
+    {
+      S_CIP_String *s = (S_CIP_String *) pa_ptstAttribute->pt2data;
+
+      htols(*(EIP_UINT16 *) &(s->Length), &pa_pnMsg);
+      for (j = 0; j < s->Length; j++)
+        {
+          *pa_pnMsg++ = s->String[j];
+        }
+      counter = s->Length + 2; /* we have a two byte length field */
+      if (counter & 0x01)
+        {
+          /* we have an odd byte count */
+          *pa_pnMsg++ = 0;
+          counter++;
+        }
       break;
-
-    case (CIP_INT):
-    case (CIP_UINT):
-    case (CIP_WORD):
-      htols(*(EIP_UINT16 *) (pa_ptstAttribute->pt2data), &pa_pnMsg);
-      counter = 2;
+    }
+  case (CIP_STRING2):
+  case (CIP_FTIME):
+  case (CIP_LTIME):
+  case (CIP_ITIME):
+  case (CIP_STRINGN):
+    break;
+
+  case (CIP_SHORT_STRING):
+    {
+      S_CIP_Short_String *ss = (S_CIP_Short_String *) pa_ptstAttribute->pt2data;
+
+      *pa_pnMsg++ = ss->Length;
+      for (j = 0; j < ss->Length; j++)
+        {
+          *pa_pnMsg++ = ss->String[j];
+        }
+      counter = ss->Length + 1;
       break;
+    }
 
-    case (CIP_DINT):
-    case (CIP_UDINT):
-    case (CIP_DWORD):
-      htoll(*(EIP_UINT32 *) (pa_ptstAttribute->pt2data), &pa_pnMsg);
-      counter = 4;
-      break;
+  case (CIP_TIME):
+    break;
 
-    case (CIP_LINT):
-    case (CIP_ULINT):
-    case (CIP_LWORD):
-      break;
+  case (CIP_EPATH):
+    {
+      EIP_UINT16 *p = (EIP_UINT16 *) pa_ptstAttribute->pt2data;
+      EIP_UINT16 len;
+      EIP_UINT16 data;
 
-    case (CIP_REAL):
-    case (CIP_LREAL):
-    case (CIP_STIME):
-    case (CIP_DATE):
-    case (CIP_TIME_OF_DAY):
-    case (CIP_DATE_AND_TIME):
-        break;
-    case (CIP_STRING):
-      {
-        S_CIP_String *s = (S_CIP_String *)pa_ptstAttribute->pt2data;
-
-        htols(*(EIP_UINT16 *) &(s->Length), &pa_pnMsg);
-        for (j = 0; j < s->Length; j++)
-          {
-            *pa_pnMsg++ = s->String[j];
-          }
-        counter = s->Length + 2; /* we have a two byte length field */
-        if (counter & 0x01)
-          {
-            /* we have an odd byte count */
-            *pa_pnMsg++ = 0;
-            counter++;
-          }
-        break;
-      }
-    case (CIP_STRING2):
-    case (CIP_FTIME):
-    case (CIP_LTIME):
-    case (CIP_ITIME):
-    case (CIP_STRINGN):
+      len = *p++;
+      htols(len, &pa_pnMsg);
+      counter = 2;
+      while (len--)
+        {
+          data = *p++;
+          htols(data, &pa_pnMsg);
+          counter += 2;
+        }
+    }
+    break;
+
+  case (CIP_ENGUNIT):
+    break;
+
+  case (CIP_USINT_USINT):
+    {
+      S_CIP_Revision *rv = (S_CIP_Revision *) pa_ptstAttribute->pt2data;
+
+      *pa_pnMsg++ = rv->MajorRevision;
+      *pa_pnMsg++ = rv->MinorRevision;
+      counter = 2;
       break;
+    }
+
+  case (CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING):
+    {
+      EIP_UINT32 *p = (EIP_UINT32 *) pa_ptstAttribute->pt2data;
+      S_CIP_String *s;
+
+      htoll(p[0], &pa_pnMsg);
+      htoll(p[1], &pa_pnMsg);
+      htoll(p[2], &pa_pnMsg);
+      htoll(p[3], &pa_pnMsg);
+      htoll(p[4], &pa_pnMsg);
+      counter = 20;
+      /* handle the string */
+      /*TODO Think on how to use the string encoding mechanism*/
+      s = (S_CIP_String *) &p[5];
+      htols(s->Length, &pa_pnMsg); /* length of string*/
+      counter++;
+      for (j = 0; j < s->Length; j++)
+        {
+          *pa_pnMsg++ = s->String[j];
+          counter++;
+        }
+
+      if (counter & 1)
+        { /* odd bytes in string -> insert pad byte */
+          *pa_pnMsg++ = 0;
+          counter++;
+        }
+      break;
+    }
 
-    case (CIP_SHORT_STRING):
-      {
-        S_CIP_Short_String *ss = (S_CIP_Short_String *)pa_ptstAttribute->pt2data;
-
-        *pa_pnMsg++ = ss->Length;
-        for (j = 0; j < ss->Length; j++)
-          {
-            *pa_pnMsg++ = ss->String[j];
-          }
-        counter = ss->Length + 1;
-        break;
-      }
+  case (CIP_6USINT):
+    {
+      EIP_UINT8 *p = (EIP_UINT8 *) pa_ptstAttribute->pt2data;
 
-    case (CIP_TIME):
+      for (j = 0; j < 6; j++)
+        {
+          *pa_pnMsg++ = p[j];
+        }
+      counter = 6;
       break;
+    }
 
-    case (CIP_EPATH):
-      {
-        EIP_UINT16 *p = (EIP_UINT16 *)pa_ptstAttribute->pt2data;
-        EIP_UINT16 len;
-        EIP_UINT16 data;
-
-        len = *p++;
-        htols(len, &pa_pnMsg);
-        counter = 2;
-        while (len--)
-          {
-            data = *p++;
-            htols(data, &pa_pnMsg);
-            counter += 2;
-          }
-      }
-      break;
+  case (CIP_MEMBER_LIST):
+    break;
 
-    case (CIP_ENGUNIT):
-      break;
+  case (CIP_BYTE_ARRAY):
+    break;
 
-    case (CIP_USINT_USINT):
-      {
-        S_CIP_Revision *rv = (S_CIP_Revision *)pa_ptstAttribute->pt2data;
-
-        *pa_pnMsg++ = rv->MajorRevision;
-        *pa_pnMsg++ = rv->MinorRevision;
-        counter = 2;
-        break;
-      }
-
-    case (CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING):
-      {
-        EIP_UINT32 *p = (EIP_UINT32 *)pa_ptstAttribute->pt2data;
-        S_CIP_String *s;
-
-        htoll(p[0], &pa_pnMsg);
-        htoll(p[1], &pa_pnMsg);
-        htoll(p[2], &pa_pnMsg);
-        htoll(p[3], &pa_pnMsg);
-        htoll(p[4], &pa_pnMsg);
-        counter = 20;
-        /* handle the string */
-        /*TODO Think on how to use the string encoding mechanism*/
-        s = (S_CIP_String *)&p[5];
-        htols(s->Length, &pa_pnMsg); /* length of string*/
-        counter++;
-        for (j = 0; j < s->Length; j++)
-          {
-            *pa_pnMsg++ = s->String[j];
-            counter++;
-          }
-
-        if (counter&1)
-          { /* odd bytes in string -> insert pad byte */
-            *pa_pnMsg++ = 0;
-            counter++;
-          }
-        break;
-      }
-
-    case (CIP_6USINT):
-      {
-        EIP_UINT8 *p = (EIP_UINT8 *)pa_ptstAttribute->pt2data;
-
-        for (j = 0; j < 6; j++)
-          {
-            *pa_pnMsg++ = p[j];
-          }
-        counter = 6;
-        break;
-      }
-
-    case (CIP_MEMBER_LIST):
-      break;
+  case (INTERNAL_UINT16_6): /* TODO for port class attribute 9, hopefully we can find a better way to do this*/
+    {
+      EIP_UINT16 *p = (EIP_UINT16 *) pa_ptstAttribute->pt2data;
 
-    case (CIP_BYTE_ARRAY):
+      htols(p[0], &pa_pnMsg);
+      htols(p[1], &pa_pnMsg);
+      htols(p[2], &pa_pnMsg);
+      htols(p[3], &pa_pnMsg);
+      htols(p[4], &pa_pnMsg);
+      htols(p[5], &pa_pnMsg);
+      counter = 12;
       break;
-
-    case (INTERNAL_UINT16_6): /* TODO for port class attribute 9, hopefully we can find a better way to do this*/
-      { 
-        EIP_UINT16 *p = (EIP_UINT16 *)pa_ptstAttribute->pt2data;
-
-        htols(p[0], &pa_pnMsg);
-        htols(p[1], &pa_pnMsg);
-        htols(p[2], &pa_pnMsg);
-        htols(p[3], &pa_pnMsg);
-        htols(p[4], &pa_pnMsg);
-        htols(p[5], &pa_pnMsg);
-        counter = 12;
-        break;
-      }
-
-      }
-
-    return counter;
-  }
-
-EIP_STATUS getAttributeAll(S_CIP_Instance * pa_pstInstance, 
-    S_CIP_MR_Request * pa_stMRRequest,
-    S_CIP_MR_Response * pa_stMRResponse,
-    EIP_UINT8 * pa_msg) 
-  {
-    int i, j;
-    EIP_UINT8 *ptmp;
-    S_CIP_attribute_struct *p_attr;
-    S_CIP_service_struct *p_service;
-
-    ptmp = pa_msg; /* pointer into the reply */
-    p_attr = pa_pstInstance->pstAttributes; /* pointer to list of attributes*/
-    p_service = pa_pstInstance->pstClass->pstServices; /* pointer to list of services*/
-
-    if (pa_pstInstance->nInstanceNr==2)
-      {
-        if (EIP_DEBUG>=EIP_VERBOSE)
-          printf("GetAttributeAll: instance number 2\n");
-      }
-
-    for (i = 0; i < pa_pstInstance->pstClass->nNr_of_Services; i++) /* hunt for the GET_ATTRIBUTE_SINGLE service*/
-      {
-        if (p_service->CIP_ServiceNr == CIP_GET_ATTRIBUTE_SINGLE) /* found the service */
-          {
-            if (0 == pa_pstInstance->pstClass->nNr_of_Attributes)
-              {
-                pa_stMRResponse->DataLength = 0; /*there are no attributes to be sent back*/
-                pa_stMRResponse->ReplyService
-                    = (0x80 | pa_stMRRequest->Service);
-                pa_stMRResponse->GeneralStatus
-                    = CIP_ERROR_SERVICE_NOT_SUPPORTED;
-                pa_stMRResponse->SizeofAdditionalStatus = 0;
-              }
-            else
-              {
-                for (j = 0; j < pa_pstInstance->pstClass->nNr_of_Attributes; j++) /* for each instance attribute of this class */
-                  {
-                    int attrNum = p_attr->CIP_AttributNr;
-                    if (attrNum<32
-                        && (pa_pstInstance->pstClass->nGetAttrAllMask & 1
-                            <<attrNum)) /* only return attributes that are flagged as being part of GetAttributeALl */
-                      {
-                        pa_stMRRequest->RequestPath.AttributNr = attrNum;
-                        pa_msg += p_service->m_ptfuncService(pa_pstInstance,
-                            pa_stMRRequest, pa_stMRResponse, pa_msg);
-                        if (pa_stMRResponse->GeneralStatus != CIP_ERROR_SUCCESS)
-                          {
-                            return EIP_ERROR;
-                          }
-                      }
-                    p_attr++;
-                  }
-                pa_stMRResponse->DataLength = pa_msg - ptmp;
-              }
-            return (EIP_STATUS)pa_stMRResponse->DataLength;
-          }
-        p_service++;
-      }
-    return EIP_OK; /* reurn 0 if cannot find GET_ATTRIBUTE_SINGLE service*/
-  }
+    }
+
+    }
+
+  return counter;
+}
+
+EIP_STATUS
+getAttributeAll(S_CIP_Instance * pa_pstInstance,
+    S_CIP_MR_Request * pa_stMRRequest, S_CIP_MR_Response * pa_stMRResponse,
+    EIP_UINT8 * pa_msg)
+{
+  int i, j;
+  EIP_UINT8 *ptmp;
+  S_CIP_attribute_struct *p_attr;
+  S_CIP_service_struct *p_service;
+
+  ptmp = pa_msg; /* pointer into the reply */
+  p_attr = pa_pstInstance->pstAttributes; /* pointer to list of attributes*/
+  p_service = pa_pstInstance->pstClass->pstServices; /* pointer to list of services*/
+
+  if (pa_pstInstance->nInstanceNr == 2)
+    {
+      OPENER_TRACE_INFO("GetAttributeAll: instance number 2\n");
+    }
+
+  for (i = 0; i < pa_pstInstance->pstClass->nNr_of_Services; i++) /* hunt for the GET_ATTRIBUTE_SINGLE service*/
+    {
+      if (p_service->CIP_ServiceNr == CIP_GET_ATTRIBUTE_SINGLE) /* found the service */
+        {
+          if (0 == pa_pstInstance->pstClass->nNr_of_Attributes)
+            {
+              pa_stMRResponse->DataLength = 0; /*there are no attributes to be sent back*/
+              pa_stMRResponse->ReplyService = (0x80 | pa_stMRRequest->Service);
+              pa_stMRResponse->GeneralStatus = CIP_ERROR_SERVICE_NOT_SUPPORTED;
+              pa_stMRResponse->SizeofAdditionalStatus = 0;
+            }
+          else
+            {
+              for (j = 0; j < pa_pstInstance->pstClass->nNr_of_Attributes; j++) /* for each instance attribute of this class */
+                {
+                  int attrNum = p_attr->CIP_AttributNr;
+                  if (attrNum < 32
+                      && (pa_pstInstance->pstClass->nGetAttrAllMask & 1
+                          << attrNum)) /* only return attributes that are flagged as being part of GetAttributeALl */
+                    {
+                      pa_stMRRequest->RequestPath.AttributNr = attrNum;
+                      pa_msg += p_service->m_ptfuncService(pa_pstInstance,
+                          pa_stMRRequest, pa_stMRResponse, pa_msg);
+                      if (pa_stMRResponse->GeneralStatus != CIP_ERROR_SUCCESS)
+                        {
+                          return EIP_ERROR;
+                        }
+                    }
+                  p_attr++;
+                }
+              pa_stMRResponse->DataLength = pa_msg - ptmp;
+            }
+          return (EIP_STATUS) pa_stMRResponse->DataLength;
+        }
+      p_service++;
+    }
+  return EIP_OK; /* reurn 0 if cannot find GET_ATTRIBUTE_SINGLE service*/
+}

Різницю між файлами не показано, бо вона завелика
+ 699 - 671
src/cip/cipconnectionmanager.c


+ 233 - 220
src/cip/cipmessagerouter.c

@@ -13,6 +13,7 @@
 #include "cipmessagerouter.h"
 #include "endianconv.h"
 #include "ciperror.h"
+#include "trace.h"
 
 S_CIP_MR_Request gMRRequest;
 S_CIP_MR_Response gMRResponse;
@@ -24,21 +25,22 @@ S_CIP_MR_Response gMRResponse;
  * memory. The size of the array could be a paramter in the platform config file.
  */
 typedef struct CIP_MR_Object
-  {
-    struct CIP_MR_Object *next; /*< link */
-    S_CIP_Class *pt2Class; /*< object */
-  } S_CIP_MR_Object;
+{
+  struct CIP_MR_Object *next; /*< link */
+  S_CIP_Class *pt2Class; /*< object */
+} S_CIP_MR_Object;
 
 /* pointer to first registered object in MessageRouter*/
 S_CIP_MR_Object *g_pt2firstObject = 0;
-  
+
 /*! Register an Class to the message router
  *  @param pa_pt2Class     pointer to a class object to be registered.
  *  @return status      0 .. success
  *                     -1 .. error no memory available to register more objects
  */
-EIP_STATUS registerClass(S_CIP_Class * pa_pt2Class);     
-  
+EIP_STATUS
+registerClass(S_CIP_Class * pa_pt2Class);
+
 /*!  Create MRRequest structure out of the recieved data.
  * 
  * Parses the UCMM header consisting of: service, IOI size, IOI, data into a request structure
@@ -48,34 +50,35 @@ EIP_STATUS registerClass(S_CIP_Class * pa_pt2Class);
  * @return status  0 .. success
  *                 -1 .. error
  */
-EIP_BYTE createMRRequeststructure(EIP_UINT8 * pa_pnData, EIP_INT16 pa_nLength, S_CIP_MR_Request * pa_pstMRReqdata);
-
-
-
-EIP_STATUS CIP_MessageRouter_Init()
-  {
-    /* init the list of available objects*/ 
-    g_pt2firstObject = 0;
-
-    S_CIP_Class *pstMessageRouter;
-
-    pstMessageRouter = createCIPClass(CIP_MESSAGE_ROUTER_CLASS_CODE, /* class ID*/
-        0, /* # of class attributes */
-        0xffffffff, /* class getAttributeAll mask*/
-        0, /* # of class services*/
-        0, /* # of instance attributes*/
-        0xffffffff, /* instance getAttributeAll mask*/
-        0, /* # of instance services*/
-        1, /* # of instances*/
-        "message router", /* class name*/
-        1); /* revision */
-    if (pstMessageRouter==0)
-      return EIP_ERROR;
-
-    /* reserved for future use -> set to zero */
-    gMRResponse.Reserved = 0;
-    return EIP_OK;
-  }
+EIP_BYTE
+createMRRequeststructure(EIP_UINT8 * pa_pnData, EIP_INT16 pa_nLength,
+    S_CIP_MR_Request * pa_pstMRReqdata);
+
+EIP_STATUS
+CIP_MessageRouter_Init()
+{
+  /* init the list of available objects*/
+  g_pt2firstObject = 0;
+
+  S_CIP_Class *pstMessageRouter;
+
+  pstMessageRouter = createCIPClass(CIP_MESSAGE_ROUTER_CLASS_CODE, /* class ID*/
+  0, /* # of class attributes */
+  0xffffffff, /* class getAttributeAll mask*/
+  0, /* # of class services*/
+  0, /* # of instance attributes*/
+  0xffffffff, /* instance getAttributeAll mask*/
+  0, /* # of instance services*/
+  1, /* # of instances*/
+  "message router", /* class name*/
+  1); /* revision */
+  if (pstMessageRouter == 0)
+    return EIP_ERROR;
+
+  /* reserved for future use -> set to zero */
+  gMRResponse.Reserved = 0;
+  return EIP_OK;
+}
 
 /*! get the registered MessageRouter object corresponding to ClassID.
  *  given a class ID, return a pointer to the registration node for that object
@@ -83,197 +86,207 @@ EIP_STATUS CIP_MessageRouter_Init()
  *  @return pointer to registered MR object
  *      0 .. Class not registered
  */
-S_CIP_MR_Object *getRegisteredObject(EIP_UINT32 pa_nClassID)
-  {
-    S_CIP_MR_Object *p = g_pt2firstObject; /* get pointer to head of class registration list */
-
-    while (p) /* for each entry in list*/
-      {
-        assert(p->pt2Class!=0);
-        if (p->pt2Class->nClassID == pa_nClassID)
-          return p; /* return registration node if it matches class ID*/
-        p = p->next;
-      }
+S_CIP_MR_Object *
+getRegisteredObject(EIP_UINT32 pa_nClassID)
+{
+  S_CIP_MR_Object *p = g_pt2firstObject; /* get pointer to head of class registration list */
+
+  while (p) /* for each entry in list*/
+    {
+      assert(p->pt2Class != 0);
+      if (p->pt2Class->nClassID == pa_nClassID)
+        return p; /* return registration node if it matches class ID*/
+      p = p->next;
+    }
+  return 0;
+}
+
+S_CIP_Class *
+getCIPClass(EIP_UINT32 pa_nClassID)
+{
+  S_CIP_MR_Object *p = getRegisteredObject(pa_nClassID);
+
+  if (p)
+    return p->pt2Class;
+  else
     return 0;
-  }
-
-S_CIP_Class *getCIPClass(EIP_UINT32 pa_nClassID)
-  {
-    S_CIP_MR_Object *p = getRegisteredObject(pa_nClassID);
-
-    if (p)
-      return p->pt2Class;
-    else
-      return 0;
-  }
-
-S_CIP_Instance *getCIPInstance(S_CIP_Class * pa_pstClass,
-    EIP_UINT16 pa_nInstanceNr)
-  {
-    S_CIP_Instance *p; /* pointer to linked list of instances from the class object*/
-
-    if (pa_nInstanceNr==0)
-      return (S_CIP_Instance *)pa_pstClass; /* if the instance number is zero, return the class object itself*/
-
-    for (p = pa_pstClass->pstInstances; p; p = p->pstNext) /* follow the list*/
-      {
-        if (p->nInstanceNr == pa_nInstanceNr)
-          return p; /* if the number matches, return the instance*/
-      }
-
-    return 0;
-  }
-
-EIP_STATUS registerClass(S_CIP_Class * pa_pt2Class)     
-  {
-    S_CIP_MR_Object **p = &g_pt2firstObject;
-
-    while (*p)
-      p = &(*p)->next; /* follow the list until p points to an empty link (list end)*/
-
-    *p = (S_CIP_MR_Object *)IApp_CipCalloc(1, sizeof(S_CIP_MR_Object)); /* create a new node at the end of the list*/
-    if (*p == 0)
-      return EIP_ERROR; /* check for memory error*/
-
-    (*p)->pt2Class = pa_pt2Class; /* fill in the new node*/
-
-    return EIP_OK;
-  }
-
-EIP_STATUS notifyMR(EIP_UINT8 * pa_pnData, int pa_nDataLength)
-  {
-    EIP_STATUS nRetVal = EIP_OK;
-
-    EIP_BYTE nStatus;
-    if (EIP_DEBUG>=EIP_VERBOSE)
-      printf("notifyMR: routing unconnected message\n");
-    if (CIP_ERROR_SUCCESS != (nStatus = createMRRequeststructure(pa_pnData,
-            pa_nDataLength, &gMRRequest)))
-      { /* error from create MR structure*/
-        if (EIP_DEBUG>=EIP_TERSE)
-          printf("notifyMR: error from createMRRequeststructure\n");
-        gMRResponse.GeneralStatus = nStatus;
-        gMRResponse.SizeofAdditionalStatus = 0;
-        gMRResponse.Reserved = 0;
-        gMRResponse.DataLength = 0;
-        gMRResponse.ReplyService = (0x80 | gMRRequest.Service);
-      }
-    else
-      {
-        /* forward request to appropriate Object if it is registered*/
-        S_CIP_MR_Object *pt2regObject;
-
-        pt2regObject = getRegisteredObject(gMRRequest.RequestPath.ClassID);
-        if (pt2regObject == 0)
-          {
-            if (EIP_DEBUG>=EIP_TERSE)
-              printf(
-                  "notifyMR: sending CIP_ERROR_OBJECT_DOES_NOT_EXIST reply, class id 0x%x is not registered\n",
-                  (unsigned)gMRRequest.RequestPath.ClassID);
-            gMRResponse.GeneralStatus = CIP_ERROR_PATH_DESTINATION_UNKNOWN; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
-            gMRResponse.SizeofAdditionalStatus = 0;
-            gMRResponse.Reserved = 0;
-            gMRResponse.DataLength = 0;
-            gMRResponse.ReplyService = (0x80 | gMRRequest.Service);
-          }
-        else
-          {
-            /* call notify function from Object with ClassID (gMRRequest.RequestPath.ClassID)
-             object will or will not make an reply into gMRResponse*/
-            gMRResponse.Reserved = 0;
-            assert(pt2regObject->pt2Class);
-            if (EIP_DEBUG>=EIP_VERBOSE)
-              printf("notifyMR: calling notify function of class '%s'\n",
-                  pt2regObject->pt2Class->acName);
-            nRetVal = notifyClass(pt2regObject->pt2Class, &gMRRequest,
-                &gMRResponse);
-
-            if (EIP_DEBUG<EIP_VERBOSE)
-              {
-              }
-            else if (nRetVal == EIP_ERROR)
-              printf(
+}
+
+S_CIP_Instance *
+getCIPInstance(S_CIP_Class * pa_pstClass, EIP_UINT16 pa_nInstanceNr)
+{
+  S_CIP_Instance *p; /* pointer to linked list of instances from the class object*/
+
+  if (pa_nInstanceNr == 0)
+    return (S_CIP_Instance *) pa_pstClass; /* if the instance number is zero, return the class object itself*/
+
+  for (p = pa_pstClass->pstInstances; p; p = p->pstNext) /* follow the list*/
+    {
+      if (p->nInstanceNr == pa_nInstanceNr)
+        return p; /* if the number matches, return the instance*/
+    }
+
+  return 0;
+}
+
+EIP_STATUS
+registerClass(S_CIP_Class * pa_pt2Class)
+{
+  S_CIP_MR_Object **p = &g_pt2firstObject;
+
+  while (*p)
+    p = &(*p)->next; /* follow the list until p points to an empty link (list end)*/
+
+  *p = (S_CIP_MR_Object *) IApp_CipCalloc(1, sizeof(S_CIP_MR_Object)); /* create a new node at the end of the list*/
+  if (*p == 0)
+    return EIP_ERROR; /* check for memory error*/
+
+  (*p)->pt2Class = pa_pt2Class; /* fill in the new node*/
+
+  return EIP_OK;
+}
+
+EIP_STATUS
+notifyMR(EIP_UINT8 * pa_pnData, int pa_nDataLength)
+{
+  EIP_STATUS nRetVal = EIP_OK;
+
+  EIP_BYTE nStatus;
+  OPENER_TRACE_INFO("notifyMR: routing unconnected message\n");
+  if (CIP_ERROR_SUCCESS != (nStatus = createMRRequeststructure(pa_pnData,
+      pa_nDataLength, &gMRRequest)))
+    { /* error from create MR structure*/
+      OPENER_TRACE_ERR("notifyMR: error from createMRRequeststructure\n");
+      gMRResponse.GeneralStatus = nStatus;
+      gMRResponse.SizeofAdditionalStatus = 0;
+      gMRResponse.Reserved = 0;
+      gMRResponse.DataLength = 0;
+      gMRResponse.ReplyService = (0x80 | gMRRequest.Service);
+    }
+  else
+    {
+      /* forward request to appropriate Object if it is registered*/
+      S_CIP_MR_Object *pt2regObject;
+
+      pt2regObject = getRegisteredObject(gMRRequest.RequestPath.ClassID);
+      if (pt2regObject == 0)
+        {
+          OPENER_TRACE_ERR(
+              "notifyMR: sending CIP_ERROR_OBJECT_DOES_NOT_EXIST reply, class id 0x%x is not registered\n",
+              (unsigned) gMRRequest.RequestPath.ClassID);
+          gMRResponse.GeneralStatus = CIP_ERROR_PATH_DESTINATION_UNKNOWN; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
+          gMRResponse.SizeofAdditionalStatus = 0;
+          gMRResponse.Reserved = 0;
+          gMRResponse.DataLength = 0;
+          gMRResponse.ReplyService = (0x80 | gMRRequest.Service);
+        }
+      else
+        {
+          /* call notify function from Object with ClassID (gMRRequest.RequestPath.ClassID)
+           object will or will not make an reply into gMRResponse*/
+          gMRResponse.Reserved = 0;
+          assert(pt2regObject->pt2Class);
+          OPENER_TRACE_INFO(
+              "notifyMR: calling notify function of class '%s'\n",
+              pt2regObject->pt2Class->acName);
+          nRetVal = notifyClass(pt2regObject->pt2Class, &gMRRequest,
+              &gMRResponse);
+
+#ifdef OPENER_TRACE_ENABLED
+          if (nRetVal == EIP_ERROR)
+            {
+              OPENER_TRACE_ERR(
                   "notifyMR: notify function of class '%s' returned an error\n",
                   pt2regObject->pt2Class->acName);
-            else if (nRetVal == EIP_OK)
-              printf(
+            }
+          else if (nRetVal == EIP_OK)
+            {
+              OPENER_TRACE_INFO(
                   "notifyMR: notify function of class '%s' returned no reply\n",
                   pt2regObject->pt2Class->acName);
-            else
-              printf(
+            }
+          else
+            {
+              OPENER_TRACE_INFO(
                   "notifyMR: notify function of class '%s' returned a reply\n",
                   pt2regObject->pt2Class->acName);
-          }
-      }
-    return nRetVal;
-  }
-
-EIP_BYTE createMRRequeststructure(EIP_UINT8 * pa_pnData, EIP_INT16 pa_nLength, S_CIP_MR_Request * pa_pstMRReqdata)
-  {
-    int i;
-
-    pa_pstMRReqdata->Service = *pa_pnData;
-    pa_pnData++;
-    pa_pstMRReqdata->RequestPath.PathSize = *pa_pnData;
-    pa_pnData++;
-    /* copy path to structure, in version 0.1 only 8 bit for Class,Instance and Attribut, need to be replaced with function */
-    pa_pstMRReqdata->RequestPath.ClassID = 0;
-    pa_pstMRReqdata->RequestPath.InstanceNr = 0;
-    pa_pstMRReqdata->RequestPath.AttributNr = 0;
-
-    for(i = 0; i < pa_pstMRReqdata->RequestPath.PathSize; i++)
-      {
-        if(0xE0 == ((*pa_pnData) & 0xE0))
-          {
-            /*Invalid segment type*/
-            return CIP_ERROR_PATH_SEGMENT_ERROR;
-          }
-        switch (*pa_pnData)
-          {
-            case 0x20: /* classID */
-            pa_pstMRReqdata->RequestPath.ClassID = *(EIP_UINT8 *) (pa_pnData + 1);
-            pa_pnData += 2;
-            break;
-
-            case 0x21: /*classID 16Bit */
-            pa_pnData += 2;
-            pa_pstMRReqdata->RequestPath.ClassID = ltohs(&(pa_pnData));
-            i++;
-            break;
-
-            case 0x24: /* InstanceNr */
-            pa_pstMRReqdata->RequestPath.InstanceNr = *(EIP_UINT8 *) (pa_pnData + 1);
-            pa_pnData += 2;
-            break;
-
-            case 0x25: /* InstanceNr 16Bit */
-            pa_pnData += 2;
-            pa_pstMRReqdata->RequestPath.InstanceNr = ltohs(&(pa_pnData));
-            i++;
-            break;
-
-            case 0x30: /* AttributeNr */
-            pa_pstMRReqdata->RequestPath.AttributNr = *(EIP_UINT8 *) (pa_pnData + 1);
-            pa_pnData += 2;
-            break;
-
-            case 0x31: /* AttributeNr 16Bit */
-            pa_pnData += 2;
-            pa_pstMRReqdata->RequestPath.AttributNr = ltohs(&(pa_pnData));
-            i++;
-
-            default:
-              printf("wrong path requested\n");
-              return CIP_ERROR_PATH_SEGMENT_ERROR;
-              break;
-          }
-      }
-
-    pa_pstMRReqdata->Data = pa_pnData;
-    pa_pstMRReqdata->DataLength = pa_nLength - ((pa_pstMRReqdata->RequestPath.PathSize)
-        * 2 + 2);
-    if (pa_pstMRReqdata->DataLength < 0)
+            }
+#endif
+        }
+    }
+  return nRetVal;
+}
+
+EIP_BYTE
+createMRRequeststructure(EIP_UINT8 * pa_pnData, EIP_INT16 pa_nLength,
+    S_CIP_MR_Request * pa_pstMRReqdata)
+{
+  int i;
+
+  pa_pstMRReqdata->Service = *pa_pnData;
+  pa_pnData++;
+  pa_pstMRReqdata->RequestPath.PathSize = *pa_pnData;
+  pa_pnData++;
+  /* copy path to structure, in version 0.1 only 8 bit for Class,Instance and Attribut, need to be replaced with function */
+  pa_pstMRReqdata->RequestPath.ClassID = 0;
+  pa_pstMRReqdata->RequestPath.InstanceNr = 0;
+  pa_pstMRReqdata->RequestPath.AttributNr = 0;
+
+  for (i = 0; i < pa_pstMRReqdata->RequestPath.PathSize; i++)
+    {
+      if (0xE0 == ((*pa_pnData) & 0xE0))
+        {
+          /*Invalid segment type*/
+          return CIP_ERROR_PATH_SEGMENT_ERROR;
+        }
+      switch (*pa_pnData)
+        {
+      case 0x20: /* classID */
+        pa_pstMRReqdata->RequestPath.ClassID = *(EIP_UINT8 *) (pa_pnData + 1);
+        pa_pnData += 2;
+        break;
+
+      case 0x21: /*classID 16Bit */
+        pa_pnData += 2;
+        pa_pstMRReqdata->RequestPath.ClassID = ltohs(&(pa_pnData));
+        i++;
+        break;
+
+      case 0x24: /* InstanceNr */
+        pa_pstMRReqdata->RequestPath.InstanceNr
+            = *(EIP_UINT8 *) (pa_pnData + 1);
+        pa_pnData += 2;
+        break;
+
+      case 0x25: /* InstanceNr 16Bit */
+        pa_pnData += 2;
+        pa_pstMRReqdata->RequestPath.InstanceNr = ltohs(&(pa_pnData));
+        i++;
+        break;
+
+      case 0x30: /* AttributeNr */
+        pa_pstMRReqdata->RequestPath.AttributNr
+            = *(EIP_UINT8 *) (pa_pnData + 1);
+        pa_pnData += 2;
+        break;
+
+      case 0x31: /* AttributeNr 16Bit */
+        pa_pnData += 2;
+        pa_pstMRReqdata->RequestPath.AttributNr = ltohs(&(pa_pnData));
+        i++;
+
+      default:
+        OPENER_TRACE_ERR("wrong path requested\n");
+        return CIP_ERROR_PATH_SEGMENT_ERROR;
+        break;
+        }
+    }
+
+  pa_pstMRReqdata->Data = pa_pnData;
+  pa_pstMRReqdata->DataLength = pa_nLength
+      - ((pa_pstMRReqdata->RequestPath.PathSize) * 2 + 2);
+  if (pa_pstMRReqdata->DataLength < 0)
     return CIP_ERROR_PATH_SIZE_INVALID;
-    else
+  else
     return CIP_ERROR_SUCCESS;
-  }
+}

+ 9 - 7
src/cip/cipmessagerouter.h

@@ -23,8 +23,9 @@ extern S_CIP_MR_Response gMRResponse;
 /* public functions */
 
 /*!Initialize the data structures of the message router
- */ 
-EIP_STATUS CIP_MessageRouter_Init(void);
+ */
+EIP_STATUS
+CIP_MessageRouter_Init(void);
 
 /*! Notify the MessageRouter that an explicit message (connected or unnconnected)
  *  has been recieved. This function will be called from the encapsulation layer.
@@ -34,8 +35,9 @@ EIP_STATUS CIP_MessageRouter_Init(void);
  *  @param pa_nDataLength number of bytes in the data buffer
  *  @return  EIP_ERROR on fault
  *           EIP_OK on success           
- */ 
-EIP_STATUS notifyMR(EIP_UINT8 *pa_pnData, int pa_nDataLength);
+ */
+EIP_STATUS
+notifyMR(EIP_UINT8 *pa_pnData, int pa_nDataLength);
 
 /*! Register a class at the message router.
  *  In order that the message router can deliver
@@ -44,8 +46,8 @@ EIP_STATUS notifyMR(EIP_UINT8 *pa_pnData, int pa_nDataLength);
  *  createCIPClass.
  *  @param pa_pt2Object cip class to be registered
  *  @return EIP_OK on success
- */ 
-EIP_STATUS registerClass(S_CIP_Class *pa_pt2Object);
-
+ */
+EIP_STATUS
+registerClass(S_CIP_Class *pa_pt2Object);
 
 #endif /*CIPMESSAGEROUTER_H_*/

+ 125 - 123
src/cip/ciptcpipinterface.c

@@ -18,16 +18,15 @@
 #include "cipethernetlink.h"
 #include "opener_api.h"
 
-EIP_UINT32 TCP_Status = 0;                   /* #1  This is a TCPIP object attribute. For now it is always zero. */
-EIP_UINT32 Configuration_Capability = 0x04;  /* #2  This is a default value meaning that it is a DHCP client see 5-3.2.2.2 EIP spec*/
-EIP_UINT32 Configuration_Control = 0;        /* #3  This is a TCPIP object attribute. For now it is always zero and is not used for anything. */
+EIP_UINT32 TCP_Status = 0; /* #1  This is a TCPIP object attribute. For now it is always zero. */
+EIP_UINT32 Configuration_Capability = 0x04; /* #2  This is a default value meaning that it is a DHCP client see 5-3.2.2.2 EIP spec*/
+EIP_UINT32 Configuration_Control = 0; /* #3  This is a TCPIP object attribute. For now it is always zero and is not used for anything. */
 S_CIP_EPATH Physical_Link_Object = /* #4 */
   { 2, /* EIP_UINT8 PathSize*/
-      CIP_ETHERNETLINK_CLASS_CODE, /* EIP_UINT32 ClassID*/
-      1, /* EIP_UINT32 InstanceNr*/
-      0 /* EIP_UINT32 AttributNr (not used as this is the EPATH the EthernetLink object)*/
-    }; /* it was not initilized in the original code*/
-
+  CIP_ETHERNETLINK_CLASS_CODE, /* EIP_UINT32 ClassID*/
+  1, /* EIP_UINT32 InstanceNr*/
+  0 /* EIP_UINT32 AttributNr (not used as this is the EPATH the EthernetLink object)*/
+  }; /* it was not initilized in the original code*/
 
 S_CIP_TCPIPNetworkInterfaceConfiguration Interface_Configuration = /* #5 */
   { 0, /* default IP address */
@@ -36,9 +35,7 @@ S_CIP_TCPIPNetworkInterfaceConfiguration Interface_Configuration = /* #5 */
   0, /* NameServer */
   0, /* NameServer2 */
     { /* DomainName */
-    0, 0, 
-}
-};
+    0, 0, } };
 
 S_CIP_String Hostname = /* #6 */
   { 0, 0 };
@@ -46,117 +43,122 @@ S_CIP_String Hostname = /* #6 */
 /*!Multicast address to be used for I/O connections*/
 EIP_UINT32 g_nMultiCastAddress;
 
-
-EIP_STATUS configureNetworkInterface(const char *pa_acIpAdress,
+EIP_STATUS
+configureNetworkInterface(const char *pa_acIpAdress,
     const char *pa_acSubNetMask, const char *pa_acGateway)
-  {
-    Interface_Configuration.IPAddress = inet_addr(pa_acIpAdress);
-    Interface_Configuration.NetworkMask = inet_addr(pa_acSubNetMask);
-    Interface_Configuration.Gateway = inet_addr(pa_acGateway);
-
-    /* calculate the CIP multicast address. The multicast address is calculated, not input*/
-    unsigned nHostId = ntohl(Interface_Configuration.IPAddress)
-        & ~ntohl(Interface_Configuration.NetworkMask); /* see CIP spec 3-5.3 for multicast address algorithm*/
-    nHostId -= 1;
-    nHostId &= 0x3ff;
-    g_nMultiCastAddress = htonl(ntohl(inet_addr("239.192.1.0")) | nHostId << 5);
-
-    return EIP_OK;
-  }
-
-void configureDomainName(const char *pa_acDomainName)
-  {
-    if (0 != Interface_Configuration.DomainName.String)
-      {
-        free(Interface_Configuration.DomainName.String);
-      }
-    Interface_Configuration.DomainName.Length = strlen(pa_acDomainName);
-    if (Interface_Configuration.DomainName.Length)
-      {
-        Interface_Configuration.DomainName.String = (EIP_INT8 *)IApp_CipCalloc(
-            Interface_Configuration.DomainName.Length + 1, sizeof(EIP_INT8));
-        strcpy(Interface_Configuration.DomainName.String, pa_acDomainName);
-      }
-    else
-      {
-        Interface_Configuration.DomainName.String = 0;
-      }
-  }
-
-void configureHostName(const char *pa_acHostName)
-  {
-    if (0 != Hostname.String)
-      {
-        free(Hostname.String);
-      }
-    Hostname.Length = strlen(pa_acHostName);
-    if (Hostname.Length)
-      {
-        Hostname.String = (EIP_INT8 *)IApp_CipCalloc(Hostname.Length + 1, sizeof(EIP_INT8));
-        strcpy(Hostname.String, pa_acHostName);
-      }
-    else
-      {
-        Hostname.String = 0;
-      }
-  }
-
-EIP_STATUS setAttributeSingleTCP(S_CIP_Instance *pa_pstObjectInstance, /* pointer to instance*/
-    S_CIP_MR_Request *pa_pstMRRequest, /* pointer to message router request */
-    S_CIP_MR_Response *pa_pstMRResponse, /* pointer to message router response*/
-    EIP_UINT8 *pa_msg)
-  {
-    pa_pstObjectInstance = 0; /*surrpress compiler warning */
-    pa_msg = 0;  /*surrpress compiler warning */  
-    
-    if((1 <= pa_pstMRRequest->RequestPath.AttributNr) &&
-        (pa_pstMRRequest->RequestPath.AttributNr <= 6))
-      {
-          /* it is an attribute we currently support, however no attribute is setable */
-          /*TODO if you like to have a device that can be configured via this CIP object add your code here */
-        pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SETTABLE;
-        
-      }
-    else
-      {
-        /* we don't have this attribute */
-        pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SUPPORTED;
-      }
-    
-    pa_pstMRResponse->SizeofAdditionalStatus = 0;
-    pa_pstMRResponse->DataLength = 0;
-    pa_pstMRResponse->ReplyService = (0x80 | pa_pstMRRequest->Service);
-    return EIP_OK_SEND;
-  }
-
-EIP_STATUS CIP_TCPIP_Interface_Init()
-  {
-    S_CIP_Class *p_stTCPIPClass;
-    S_CIP_Instance *pstInstance;
-
-    if ((p_stTCPIPClass = createCIPClass(CIP_TCPIPINTERFACE_CLASS_CODE, 0, /* # class attributes*/
-        0xffffffff, /* class getAttributeAll mask*/
-        0, /* # class services*/
-        6, /* # instance attributes*/
-        0xffffffff, /* instance getAttributeAll mask*/
-        1, /* # instance services*/
-        1, /* # instances*/
-        "TCP/IP interface", 1)) == 0)
-      return EIP_ERROR;
-
-    pstInstance = getCIPInstance(p_stTCPIPClass, 1); /* bind attributes to the instance #1 that was created above*/
-
-    insertAttribute(pstInstance, 1, CIP_DWORD, (void *)&TCP_Status);
-    insertAttribute(pstInstance, 2, CIP_DWORD,
-        (void *)&Configuration_Capability);
-    insertAttribute(pstInstance, 3, CIP_DWORD, (void *)&Configuration_Control);
-    insertAttribute(pstInstance, 4, CIP_EPATH, &Physical_Link_Object);
-    insertAttribute(pstInstance, 5, CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING,
-        &Interface_Configuration);
-    insertAttribute(pstInstance, 6, CIP_STRING, (void *)&Hostname);
-
-    insertService(p_stTCPIPClass, CIP_SET_ATTRIBUTE_SINGLE, &setAttributeSingleTCP, "SetAttributeSingle");
-    
-    return EIP_OK;
-  }
+{
+  Interface_Configuration.IPAddress = inet_addr(pa_acIpAdress);
+  Interface_Configuration.NetworkMask = inet_addr(pa_acSubNetMask);
+  Interface_Configuration.Gateway = inet_addr(pa_acGateway);
+
+  /* calculate the CIP multicast address. The multicast address is calculated, not input*/
+  unsigned nHostId = ntohl(Interface_Configuration.IPAddress) & ~ntohl(
+      Interface_Configuration.NetworkMask); /* see CIP spec 3-5.3 for multicast address algorithm*/
+  nHostId -= 1;
+  nHostId &= 0x3ff;
+  g_nMultiCastAddress = htonl(ntohl(inet_addr("239.192.1.0")) | nHostId << 5);
+
+  return EIP_OK;
+}
+
+void
+configureDomainName(const char *pa_acDomainName)
+{
+  if (0 != Interface_Configuration.DomainName.String)
+    {
+      free(Interface_Configuration.DomainName.String);
+    }
+  Interface_Configuration.DomainName.Length = strlen(pa_acDomainName);
+  if (Interface_Configuration.DomainName.Length)
+    {
+      Interface_Configuration.DomainName.String = (EIP_INT8 *) IApp_CipCalloc(
+          Interface_Configuration.DomainName.Length + 1, sizeof(EIP_INT8));
+      strcpy(Interface_Configuration.DomainName.String, pa_acDomainName);
+    }
+  else
+    {
+      Interface_Configuration.DomainName.String = 0;
+    }
+}
+
+void
+configureHostName(const char *pa_acHostName)
+{
+  if (0 != Hostname.String)
+    {
+      free(Hostname.String);
+    }
+  Hostname.Length = strlen(pa_acHostName);
+  if (Hostname.Length)
+    {
+      Hostname.String = (EIP_INT8 *) IApp_CipCalloc(Hostname.Length + 1,
+          sizeof(EIP_INT8));
+      strcpy(Hostname.String, pa_acHostName);
+    }
+  else
+    {
+      Hostname.String = 0;
+    }
+}
+
+EIP_STATUS
+setAttributeSingleTCP(S_CIP_Instance *pa_pstObjectInstance, /* pointer to instance*/
+S_CIP_MR_Request *pa_pstMRRequest, /* pointer to message router request */
+S_CIP_MR_Response *pa_pstMRResponse, /* pointer to message router response*/
+EIP_UINT8 *pa_msg)
+{
+  pa_pstObjectInstance = 0; /*surrpress compiler warning */
+  pa_msg = 0; /*surrpress compiler warning */
+
+  if ((1 <= pa_pstMRRequest->RequestPath.AttributNr)
+      && (pa_pstMRRequest->RequestPath.AttributNr <= 6))
+    {
+      /* it is an attribute we currently support, however no attribute is setable */
+      /*TODO if you like to have a device that can be configured via this CIP object add your code here */
+      pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SETTABLE;
+
+    }
+  else
+    {
+      /* we don't have this attribute */
+      pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SUPPORTED;
+    }
+
+  pa_pstMRResponse->SizeofAdditionalStatus = 0;
+  pa_pstMRResponse->DataLength = 0;
+  pa_pstMRResponse->ReplyService = (0x80 | pa_pstMRRequest->Service);
+  return EIP_OK_SEND;
+}
+
+EIP_STATUS
+CIP_TCPIP_Interface_Init()
+{
+  S_CIP_Class *p_stTCPIPClass;
+  S_CIP_Instance *pstInstance;
+
+  if ((p_stTCPIPClass = createCIPClass(CIP_TCPIPINTERFACE_CLASS_CODE, 0, /* # class attributes*/
+  0xffffffff, /* class getAttributeAll mask*/
+  0, /* # class services*/
+  6, /* # instance attributes*/
+  0xffffffff, /* instance getAttributeAll mask*/
+  1, /* # instance services*/
+  1, /* # instances*/
+  "TCP/IP interface", 1)) == 0)
+    return EIP_ERROR;
+
+  pstInstance = getCIPInstance(p_stTCPIPClass, 1); /* bind attributes to the instance #1 that was created above*/
+
+  insertAttribute(pstInstance, 1, CIP_DWORD, (void *) &TCP_Status);
+  insertAttribute(pstInstance, 2, CIP_DWORD, (void *) &Configuration_Capability);
+  insertAttribute(pstInstance, 3, CIP_DWORD, (void *) &Configuration_Control);
+  insertAttribute(pstInstance, 4, CIP_EPATH, &Physical_Link_Object);
+  insertAttribute(pstInstance, 5, CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING,
+      &Interface_Configuration);
+  insertAttribute(pstInstance, 6, CIP_STRING, (void *) &Hostname);
+
+  insertService(p_stTCPIPClass, CIP_SET_ATTRIBUTE_SINGLE,
+      &setAttributeSingleTCP, "SetAttributeSingle");
+
+  return EIP_OK;
+}
 

+ 279 - 273
src/enet_encap/cpf.c

@@ -15,91 +15,94 @@
 #include "ciperror.h"
 #include "cpf.h"
 #include "cipconnectionmanager.h"
+#include "trace.h"
 
 /* CPF global data items */
 S_CIP_CPF_Data g_stCPFDataItem;
 
-int notifyCPF(EIP_UINT8 * pa_nData, /* message data*/
-    EIP_INT16 pa_nData_length, /* data length*/
-    EIP_UINT8 * pa_replybuf) /* reply buffer*/
-  {
-    EIP_STATUS res;
+int
+notifyCPF(EIP_UINT8 * pa_nData, /* message data*/
+EIP_INT16 pa_nData_length, /* data length*/
+EIP_UINT8 * pa_replybuf) /* reply buffer*/
+{
+  EIP_STATUS res;
 
-    if ((createCPFstructure(pa_nData, pa_nData_length, &g_stCPFDataItem))
-        == EIP_ERROR)
-      {
-        if (EIP_DEBUG>=EIP_TERSE)
-          printf("notifyMR: error from createCPFstructure\n");
-        return EIP_ERROR; /* error from createCPFstructure */
-      }
+  if ((createCPFstructure(pa_nData, pa_nData_length, &g_stCPFDataItem))
+      == EIP_ERROR)
+    {
+      OPENER_TRACE_ERR("notifyMR: error from createCPFstructure\n");
+      return EIP_ERROR; /* error from createCPFstructure */
+    }
 
-    if (g_stCPFDataItem.stAddr_Item.TypeID == CIP_ITEM_ID_NULL) /* check if NullAddressItem received, otherwise it is no unconnected message and should not be here*/
-      { /* found null address item*/
-        if (g_stCPFDataItem.stDataI_Item.TypeID == CIP_ITEM_ID_UNCONNECTEDMESSAGE)
-          { /* unconnected data item received*/
-            res = notifyMR(g_stCPFDataItem.stDataI_Item.Data,
-                g_stCPFDataItem.stDataI_Item.Length);
-            if (res == EIP_ERROR)
-              return EIP_ERROR;
-
-            return assembleLinearMsg(&gMRResponse, &g_stCPFDataItem, pa_replybuf);
-          }
-        /* wrong data item detected*/
-        if (EIP_DEBUG>=EIP_TERSE)
-          printf("notifyMR: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
-        return EIP_ERROR;
-      }
+  if (g_stCPFDataItem.stAddr_Item.TypeID == CIP_ITEM_ID_NULL) /* check if NullAddressItem received, otherwise it is no unconnected message and should not be here*/
+    { /* found null address item*/
+      if (g_stCPFDataItem.stDataI_Item.TypeID == CIP_ITEM_ID_UNCONNECTEDMESSAGE)
+        { /* unconnected data item received*/
+          res = notifyMR(g_stCPFDataItem.stDataI_Item.Data,
+              g_stCPFDataItem.stDataI_Item.Length);
+          if (res == EIP_ERROR)
+            return EIP_ERROR;
 
-    if (EIP_DEBUG>=EIP_TERSE)
-      printf("notifyMR: got something besides the expected CIP_ITEM_ID_NULL\n");
-    return EIP_ERROR;
-  }
+          return assembleLinearMsg(&gMRResponse, &g_stCPFDataItem, pa_replybuf);
+        }
+      /* wrong data item detected*/
+      OPENER_TRACE_ERR(
+          "notifyMR: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
+      return EIP_ERROR;
+    }
 
-int notifyConnectedCPF(EIP_UINT8 * pa_nData, /* message data*/
-    EIP_INT16 pa_nData_length, /* data length*/
-    EIP_UINT8 * pa_replybuf) /* reply buffer*/
-  {
-    EIP_STATUS res;
-    S_CIP_ConnectionObject *pstConnectionObject;
+  OPENER_TRACE_ERR("notifyMR: got something besides the expected CIP_ITEM_ID_NULL\n");
+  return EIP_ERROR;
+}
 
-    if ((createCPFstructure(pa_nData, pa_nData_length, &g_stCPFDataItem))
-        == EIP_ERROR)
-      {
-        if (EIP_DEBUG>=EIP_TERSE)
-          printf("notifyMR: error from createCPFstructure\n");
-        return EIP_ERROR; /* error from createCPFstructure*/
-      }
+int
+notifyConnectedCPF(EIP_UINT8 * pa_nData, /* message data*/
+EIP_INT16 pa_nData_length, /* data length*/
+EIP_UINT8 * pa_replybuf) /* reply buffer*/
+{
+  EIP_STATUS res;
+  S_CIP_ConnectionObject *pstConnectionObject;
 
-    if (g_stCPFDataItem.stAddr_Item.TypeID == CIP_ITEM_ID_CONNECTIONBASED) /* check if ConnectedAddressItem received, otherwise it is no connected message and should not be here*/
-      { /* ConnectedAddressItem item */      
-        pstConnectionObject = getConnectedObject(g_stCPFDataItem.stAddr_Item.Data.ConnectionIdentifier);
-        if (pstConnectionObject == 0)
-          return EIP_ERROR;
-        
-        /* reset the watchdogtimer */
-        pstConnectionObject->InnacitvityWatchdogTimer = (pstConnectionObject->O_to_T_RPI / 1000) << 2; 
-      
-        /*TODO check connection id  and sequence count    */    
-        if (g_stCPFDataItem.stDataI_Item.TypeID == CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET)
-          { /* connected data item received*/
-            EIP_UINT8 *pnBuf = g_stCPFDataItem.stDataI_Item.Data;
-            g_stCPFDataItem.stAddr_Item.Data.SequenceNumber = (EIP_UINT32)ltohs(&pnBuf);              
-            res = notifyMR(pnBuf, g_stCPFDataItem.stDataI_Item.Length - 2);
-            if (res == -1)
-              return EIP_ERROR;
+  if ((createCPFstructure(pa_nData, pa_nData_length, &g_stCPFDataItem))
+      == EIP_ERROR)
+    {
+      OPENER_TRACE_ERR("notifyMR: error from createCPFstructure\n");
+      return EIP_ERROR; /* error from createCPFstructure*/
+    }
 
-            return assembleLinearMsg(&gMRResponse, &g_stCPFDataItem, pa_replybuf);
-          }
-        /* wrong data item detected*/
-        if (EIP_DEBUG>=EIP_TERSE)
-          printf("notifyMR: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
+  if (g_stCPFDataItem.stAddr_Item.TypeID == CIP_ITEM_ID_CONNECTIONBASED) /* check if ConnectedAddressItem received, otherwise it is no connected message and should not be here*/
+    { /* ConnectedAddressItem item */
+      pstConnectionObject = getConnectedObject(
+          g_stCPFDataItem.stAddr_Item.Data.ConnectionIdentifier);
+      if (pstConnectionObject == 0)
         return EIP_ERROR;
-      }
 
-    if (EIP_DEBUG>=EIP_TERSE)
-      printf("notifyMR: got something besides the expected CIP_ITEM_ID_NULL\n");
-    return EIP_ERROR;
-  }
+      /* reset the watchdogtimer */
+      pstConnectionObject->InnacitvityWatchdogTimer
+          = (pstConnectionObject->O_to_T_RPI / 1000) << 2;
+
+      /*TODO check connection id  and sequence count    */
+      if (g_stCPFDataItem.stDataI_Item.TypeID
+          == CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET)
+        { /* connected data item received*/
+          EIP_UINT8 *pnBuf = g_stCPFDataItem.stDataI_Item.Data;
+          g_stCPFDataItem.stAddr_Item.Data.SequenceNumber = (EIP_UINT32) ltohs(
+              &pnBuf);
+          res = notifyMR(pnBuf, g_stCPFDataItem.stDataI_Item.Length - 2);
+          if (res == -1)
+            return EIP_ERROR;
+
+          return assembleLinearMsg(&gMRResponse, &g_stCPFDataItem, pa_replybuf);
+        }
+      /* wrong data item detected*/
+      OPENER_TRACE_ERR(
+          "notifyMR: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
+      return EIP_ERROR;
+    }
+
+  OPENER_TRACE_ERR("notifyMR: got something besides the expected CIP_ITEM_ID_NULL\n");
+  return EIP_ERROR;
+}
 
 /*   INT16 createCPFstructure(INT8 *pa_Data, INT16 pa_DataLength, S_CIP_CPF_Data *pa_CPF_data)
  *   create CPF structure out of pa_data.
@@ -110,94 +113,94 @@ int notifyConnectedCPF(EIP_UINT8 * pa_nData, /* message data*/
  * 		0 .. success
  * 	       -1 .. error
  */
-EIP_STATUS createCPFstructure(EIP_UINT8 * pa_Data, int pa_DataLength,
+EIP_STATUS
+createCPFstructure(EIP_UINT8 * pa_Data, int pa_DataLength,
     S_CIP_CPF_Data * pa_CPF_data)
-  {
-    int len_count, i, j;
-    
-    pa_CPF_data->AddrInfo[0].TypeID = 0;
-    pa_CPF_data->AddrInfo[1].TypeID = 0;
+{
+  int len_count, i, j;
 
-    len_count = 0;
-    pa_CPF_data->ItemCount = ltohs(&pa_Data);
-    len_count += 2;
-    if (pa_CPF_data->ItemCount >= 1)
-      {
-        pa_CPF_data->stAddr_Item.TypeID = ltohs(&pa_Data);
-        pa_CPF_data->stAddr_Item.Length = ltohs(&pa_Data);
-        len_count += 4;
-        if (pa_CPF_data->stAddr_Item.Length >= 4)
-          {
-            pa_CPF_data->stAddr_Item.Data.ConnectionIdentifier
-                = ltohl(&pa_Data);
-            len_count += 4;
-          }
-        if (pa_CPF_data->stAddr_Item.Length == 8)
-          {
-            pa_CPF_data->stAddr_Item.Data.SequenceNumber = ltohl(&pa_Data);
-            len_count += 4;
-          }
-      }
-    if (pa_CPF_data->ItemCount >= 2)
-      {
-        pa_CPF_data->stDataI_Item.TypeID = ltohs(&pa_Data);
-        pa_CPF_data->stDataI_Item.Length = ltohs(&pa_Data);
-        pa_CPF_data->stDataI_Item.Data = pa_Data;
-        pa_Data += pa_CPF_data->stDataI_Item.Length;
-        len_count += (4 + pa_CPF_data->stDataI_Item.Length);
-      }
-    for (j = 0; j < (pa_CPF_data->ItemCount - 2); j++) /* TODO there needs to be a limit check here???*/
-      {
-        pa_CPF_data->AddrInfo[j].TypeID = ltohs(&pa_Data);
-        if ((pa_CPF_data->AddrInfo[j].TypeID == CIP_ITEM_ID_SOCKADDRINFO_O_TO_T)
-            || (pa_CPF_data->AddrInfo[j].TypeID
-                == CIP_ITEM_ID_SOCKADDRINFO_T_TO_O))
-          {
-            len_count += 16;
-            pa_CPF_data->AddrInfo[j].Length = ltohs(&pa_Data);
-            pa_CPF_data->AddrInfo[j].nsin_family = ltohs(&pa_Data);
-            pa_CPF_data->AddrInfo[j].nsin_port = ltohs(&pa_Data);
-            pa_CPF_data->AddrInfo[j].nsin_addr = ltohl(&pa_Data);
-            for (i = 0; i < 8; i++)
-              {
-                pa_CPF_data->AddrInfo[j].nasin_zero[i] = *pa_Data;
-                pa_Data++;
-              }
-            len_count += 16;
-          }
-        else
-          { /* no sockaddr item found */
-            pa_CPF_data->AddrInfo[j].TypeID = 0; /* mark as not set */
-            pa_Data -= 2;
-          }
-      }
-    /* set the addressInfoItems to not set if they werent received */
-    if (pa_CPF_data->ItemCount < 4)
-      {
-        pa_CPF_data->AddrInfo[1].TypeID = 0;
-        if (pa_CPF_data->ItemCount < 3)
-          {
-            pa_CPF_data->AddrInfo[0].TypeID = 0;
-          }
-      }
-    if (len_count == pa_DataLength)
-      { /* length of data is equal to length of Addr and length of Data */
-        return EIP_OK;
-      }
-    else
-      {
-        printf("something is wrong with the length in MR @ createCPFstructure\n");
-        if (pa_CPF_data->ItemCount > 2)
-          {
-            /* there is an optional packet in data stream which is not sockaddr item */
-            return EIP_OK;
-          }
-        else
-          { /* something with the length was wrong */
-            return EIP_ERROR;
-          }
-      }
-  }
+  pa_CPF_data->AddrInfo[0].TypeID = 0;
+  pa_CPF_data->AddrInfo[1].TypeID = 0;
+
+  len_count = 0;
+  pa_CPF_data->ItemCount = ltohs(&pa_Data);
+  len_count += 2;
+  if (pa_CPF_data->ItemCount >= 1)
+    {
+      pa_CPF_data->stAddr_Item.TypeID = ltohs(&pa_Data);
+      pa_CPF_data->stAddr_Item.Length = ltohs(&pa_Data);
+      len_count += 4;
+      if (pa_CPF_data->stAddr_Item.Length >= 4)
+        {
+          pa_CPF_data->stAddr_Item.Data.ConnectionIdentifier = ltohl(&pa_Data);
+          len_count += 4;
+        }
+      if (pa_CPF_data->stAddr_Item.Length == 8)
+        {
+          pa_CPF_data->stAddr_Item.Data.SequenceNumber = ltohl(&pa_Data);
+          len_count += 4;
+        }
+    }
+  if (pa_CPF_data->ItemCount >= 2)
+    {
+      pa_CPF_data->stDataI_Item.TypeID = ltohs(&pa_Data);
+      pa_CPF_data->stDataI_Item.Length = ltohs(&pa_Data);
+      pa_CPF_data->stDataI_Item.Data = pa_Data;
+      pa_Data += pa_CPF_data->stDataI_Item.Length;
+      len_count += (4 + pa_CPF_data->stDataI_Item.Length);
+    }
+  for (j = 0; j < (pa_CPF_data->ItemCount - 2); j++) /* TODO there needs to be a limit check here???*/
+    {
+      pa_CPF_data->AddrInfo[j].TypeID = ltohs(&pa_Data);
+      if ((pa_CPF_data->AddrInfo[j].TypeID == CIP_ITEM_ID_SOCKADDRINFO_O_TO_T)
+          || (pa_CPF_data->AddrInfo[j].TypeID
+              == CIP_ITEM_ID_SOCKADDRINFO_T_TO_O))
+        {
+          len_count += 16;
+          pa_CPF_data->AddrInfo[j].Length = ltohs(&pa_Data);
+          pa_CPF_data->AddrInfo[j].nsin_family = ltohs(&pa_Data);
+          pa_CPF_data->AddrInfo[j].nsin_port = ltohs(&pa_Data);
+          pa_CPF_data->AddrInfo[j].nsin_addr = ltohl(&pa_Data);
+          for (i = 0; i < 8; i++)
+            {
+              pa_CPF_data->AddrInfo[j].nasin_zero[i] = *pa_Data;
+              pa_Data++;
+            }
+          len_count += 16;
+        }
+      else
+        { /* no sockaddr item found */
+          pa_CPF_data->AddrInfo[j].TypeID = 0; /* mark as not set */
+          pa_Data -= 2;
+        }
+    }
+  /* set the addressInfoItems to not set if they werent received */
+  if (pa_CPF_data->ItemCount < 4)
+    {
+      pa_CPF_data->AddrInfo[1].TypeID = 0;
+      if (pa_CPF_data->ItemCount < 3)
+        {
+          pa_CPF_data->AddrInfo[0].TypeID = 0;
+        }
+    }
+  if (len_count == pa_DataLength)
+    { /* length of data is equal to length of Addr and length of Data */
+      return EIP_OK;
+    }
+  else
+    {
+      OPENER_TRACE_WARN("something is wrong with the length in MR @ createCPFstructure\n");
+      if (pa_CPF_data->ItemCount > 2)
+        {
+          /* there is an optional packet in data stream which is not sockaddr item */
+          return EIP_OK;
+        }
+      else
+        { /* something with the length was wrong */
+          return EIP_ERROR;
+        }
+    }
+}
 
 /*   INT8 assembleLinearMsg(S_CIP_MR_Response *pa_MRResponse, S_CIP_CPF_Data *pa_CPFDataItem, INT8 *pa_msg)
  *   copy data from MRResponse struct and CPFDataItem into linear memory in pa_msg for transmission over in encapsulation.
@@ -207,125 +210,128 @@ EIP_STATUS createCPFstructure(EIP_UINT8 * pa_Data, int pa_DataLength,
  *  return length of reply in pa_msg in bytes
  * 			-1 .. error
  */
-int assembleLinearMsg(S_CIP_MR_Response * pa_MRResponse,
+int
+assembleLinearMsg(S_CIP_MR_Response * pa_MRResponse,
     S_CIP_CPF_Data * pa_CPFDataItem, EIP_UINT8 * pa_msg)
-  {
-    int i, j, size;
+{
+  int i, j, size;
+
+  size = 0;
+  if (pa_MRResponse)
+    {
+      /* add Interface Handle and Timeout = 0 -> only for SendRRData and SendUnitData necessary */
+      htoll(0, &pa_msg);
+      htols(0, &pa_msg);
+      size += 6;
+    }
+
+  htols(pa_CPFDataItem->ItemCount, &pa_msg); /* item count */
+  size += 2;
+  /* process Address Item */
+  if (pa_CPFDataItem->stAddr_Item.TypeID == CIP_ITEM_ID_NULL)
+    { /* null address item -> address length set to 0 */
+      htols(CIP_ITEM_ID_NULL, &pa_msg);
+      htols(0, &pa_msg);
+      size += 4;
+    }
+  if (pa_CPFDataItem->stAddr_Item.TypeID == CIP_ITEM_ID_CONNECTIONBASED)
+    { /* connected data item -> address length set to 4 and copy ConnectionIdentifier */
+      htols(CIP_ITEM_ID_CONNECTIONBASED, &pa_msg);
+      htols(4, &pa_msg);
+      htoll(pa_CPFDataItem->stAddr_Item.Data.ConnectionIdentifier, &pa_msg);
+      size += 8;
+    }
+  /* sequencenumber????? */
+  if (pa_CPFDataItem->stAddr_Item.TypeID == CIP_ITEM_ID_SEQUENCEDADDRESS)
+    { /* sequenced address item -> address length set to 8 and copy ConnectionIdentifier and SequenceNumber */
+      htols(CIP_ITEM_ID_SEQUENCEDADDRESS, &pa_msg);
+      htols(8, &pa_msg);
+      htoll(pa_CPFDataItem->stAddr_Item.Data.ConnectionIdentifier, &pa_msg);
+      htoll(pa_CPFDataItem->stAddr_Item.Data.SequenceNumber, &pa_msg);
+      size += 12;
+    }
+
+  /* process Data Item */
+  if ((pa_CPFDataItem->stDataI_Item.TypeID == CIP_ITEM_ID_UNCONNECTEDMESSAGE)
+      || (pa_CPFDataItem->stDataI_Item.TypeID
+          == CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET))
+    {
+      if (pa_MRResponse)
+        {
+          htols(pa_CPFDataItem->stDataI_Item.TypeID, &pa_msg);
 
-    size = 0;
-    if (pa_MRResponse)
-      {
-        /* add Interface Handle and Timeout = 0 -> only for SendRRData and SendUnitData necessary */
-        htoll(0, &pa_msg);
-        htols(0, &pa_msg);
-        size += 6;
-      }
+          if (pa_CPFDataItem->stDataI_Item.TypeID
+              == CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET)
+            {
+              htols((EIP_UINT16) (pa_MRResponse->DataLength + 4 + 2 + (2
+                  * pa_MRResponse->SizeofAdditionalStatus)), &pa_msg);
 
-    htols(pa_CPFDataItem->ItemCount, &pa_msg); /* item count */
-    size += 2;
-    /* process Address Item */
-    if (pa_CPFDataItem->stAddr_Item.TypeID == CIP_ITEM_ID_NULL)
-      { /* null address item -> address length set to 0 */
-        htols(CIP_ITEM_ID_NULL, &pa_msg);
-        htols(0, &pa_msg);
-        size += 4;
-      }
-    if (pa_CPFDataItem->stAddr_Item.TypeID == CIP_ITEM_ID_CONNECTIONBASED)
-      { /* connected data item -> address length set to 4 and copy ConnectionIdentifier */
-        htols(CIP_ITEM_ID_CONNECTIONBASED, &pa_msg);
-        htols(4, &pa_msg);
-        htoll(pa_CPFDataItem->stAddr_Item.Data.ConnectionIdentifier, &pa_msg);
-        size += 8;
-      }
-    /* sequencenumber????? */
-    if (pa_CPFDataItem->stAddr_Item.TypeID == CIP_ITEM_ID_SEQUENCEDADDRESS)
-      { /* sequenced address item -> address length set to 8 and copy ConnectionIdentifier and SequenceNumber */
-        htols(CIP_ITEM_ID_SEQUENCEDADDRESS, &pa_msg);
-        htols(8, &pa_msg);
-        htoll(pa_CPFDataItem->stAddr_Item.Data.ConnectionIdentifier, &pa_msg);
-        htoll(pa_CPFDataItem->stAddr_Item.Data.SequenceNumber, &pa_msg);
-        size += 12;
-      }
+              htols(
+                  (EIP_UINT16) g_stCPFDataItem.stAddr_Item.Data.SequenceNumber,
+                  &pa_msg);
 
-    /* process Data Item */
-    if ((pa_CPFDataItem->stDataI_Item.TypeID == CIP_ITEM_ID_UNCONNECTEDMESSAGE)
-        || (pa_CPFDataItem->stDataI_Item.TypeID
-            == CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET))
-      {
-        if (pa_MRResponse)
-          {
-            htols(pa_CPFDataItem->stDataI_Item.TypeID, &pa_msg);
-            
-            if(pa_CPFDataItem->stDataI_Item.TypeID == CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET)
-              {
-                htols((EIP_UINT16)(pa_MRResponse->DataLength + 4 + 2 + (2
-                                                * pa_MRResponse->SizeofAdditionalStatus)), &pa_msg);
-                
-                htols((EIP_UINT16)g_stCPFDataItem.stAddr_Item.Data.SequenceNumber, &pa_msg);
-                
-                size += (4 + pa_MRResponse->DataLength + 4 + 2 + (2
-                                * pa_MRResponse->SizeofAdditionalStatus));
-              }
-            else
-              {
-                htols((EIP_UINT16)(pa_MRResponse->DataLength + 4 + (2
-                                * pa_MRResponse->SizeofAdditionalStatus)), &pa_msg);
-                size += (4 + pa_MRResponse->DataLength + 4 + (2
-                                * pa_MRResponse->SizeofAdditionalStatus));
-              }
-              
+              size += (4 + pa_MRResponse->DataLength + 4 + 2 + (2
+                  * pa_MRResponse->SizeofAdditionalStatus));
+            }
+          else
+            {
+              htols((EIP_UINT16) (pa_MRResponse->DataLength + 4 + (2
+                  * pa_MRResponse->SizeofAdditionalStatus)), &pa_msg);
+              size += (4 + pa_MRResponse->DataLength + 4 + (2
+                  * pa_MRResponse->SizeofAdditionalStatus));
+            }
 
-            /* write MR Response into linear memory */
-            *pa_msg = pa_MRResponse->ReplyService;
-            pa_msg++;
-            *pa_msg = pa_MRResponse->Reserved; /* reserved = 0 */
-            pa_msg++;
-            *pa_msg = pa_MRResponse->GeneralStatus;
-            pa_msg++;
-            *pa_msg = pa_MRResponse->SizeofAdditionalStatus;
-            pa_msg++;
-            for (i = 0; i < pa_MRResponse->SizeofAdditionalStatus; i++)
-              htols(pa_MRResponse->AdditionalStatus[i], &pa_msg);
+          /* write MR Response into linear memory */
+          *pa_msg = pa_MRResponse->ReplyService;
+          pa_msg++;
+          *pa_msg = pa_MRResponse->Reserved; /* reserved = 0 */
+          pa_msg++;
+          *pa_msg = pa_MRResponse->GeneralStatus;
+          pa_msg++;
+          *pa_msg = pa_MRResponse->SizeofAdditionalStatus;
+          pa_msg++;
+          for (i = 0; i < pa_MRResponse->SizeofAdditionalStatus; i++)
+            htols(pa_MRResponse->AdditionalStatus[i], &pa_msg);
 
-            for (i = 0; i < pa_MRResponse->DataLength; i++)
-              {
-                *pa_msg = (EIP_UINT8) * (pa_MRResponse->Data + i);
-                pa_msg++;
-              }            
-          }
-        else
-          { /* connected IO Message to send */
-            htols(pa_CPFDataItem->stDataI_Item.TypeID, &pa_msg);
-            htols(pa_CPFDataItem->stDataI_Item.Length, &pa_msg);
-            for (i = 0; i < pa_CPFDataItem->stDataI_Item.Length; i++)
-              {
-                *pa_msg = (EIP_UINT8) * (pa_CPFDataItem->stDataI_Item.Data + i);
-                pa_msg++;
-              }
-            size += (pa_CPFDataItem->stDataI_Item.Length + 4);
-          }
-      }
-    /* process SockAddr Info Items */
-    for (j = 0; j < 2; j++)
-      {
-        if ((pa_CPFDataItem->AddrInfo[j].TypeID
-            == CIP_ITEM_ID_SOCKADDRINFO_O_TO_T)
-            || (pa_CPFDataItem->AddrInfo[j].TypeID
-                == CIP_ITEM_ID_SOCKADDRINFO_T_TO_O))
-          {
-            htols(pa_CPFDataItem->AddrInfo[j].TypeID, &pa_msg);
-            htols(pa_CPFDataItem->AddrInfo[j].Length, &pa_msg);
-            htols(pa_CPFDataItem->AddrInfo[j].nsin_family, &pa_msg);
-            htols(pa_CPFDataItem->AddrInfo[j].nsin_port, &pa_msg);
-            htoll(pa_CPFDataItem->AddrInfo[j].nsin_addr, &pa_msg);
-            for (i = 0; i < 8; i++)
-              {
-                *pa_msg = 0; /* sin_zero */
-                pa_msg++;
-              }
-            size += 20;
-          }
-      }
-    return size;
-  }
+          for (i = 0; i < pa_MRResponse->DataLength; i++)
+            {
+              *pa_msg = (EIP_UINT8) *(pa_MRResponse->Data + i);
+              pa_msg++;
+            }
+        }
+      else
+        { /* connected IO Message to send */
+          htols(pa_CPFDataItem->stDataI_Item.TypeID, &pa_msg);
+          htols(pa_CPFDataItem->stDataI_Item.Length, &pa_msg);
+          for (i = 0; i < pa_CPFDataItem->stDataI_Item.Length; i++)
+            {
+              *pa_msg = (EIP_UINT8) *(pa_CPFDataItem->stDataI_Item.Data + i);
+              pa_msg++;
+            }
+          size += (pa_CPFDataItem->stDataI_Item.Length + 4);
+        }
+    }
+  /* process SockAddr Info Items */
+  for (j = 0; j < 2; j++)
+    {
+      if ((pa_CPFDataItem->AddrInfo[j].TypeID
+          == CIP_ITEM_ID_SOCKADDRINFO_O_TO_T)
+          || (pa_CPFDataItem->AddrInfo[j].TypeID
+              == CIP_ITEM_ID_SOCKADDRINFO_T_TO_O))
+        {
+          htols(pa_CPFDataItem->AddrInfo[j].TypeID, &pa_msg);
+          htols(pa_CPFDataItem->AddrInfo[j].Length, &pa_msg);
+          htols(pa_CPFDataItem->AddrInfo[j].nsin_family, &pa_msg);
+          htols(pa_CPFDataItem->AddrInfo[j].nsin_port, &pa_msg);
+          htoll(pa_CPFDataItem->AddrInfo[j].nsin_addr, &pa_msg);
+          for (i = 0; i < 8; i++)
+            {
+              *pa_msg = 0; /* sin_zero */
+              pa_msg++;
+            }
+          size += 20;
+        }
+    }
+  return size;
+}
 

+ 390 - 365
src/enet_encap/encap.c

@@ -19,7 +19,6 @@
 
 #define SENDER_CONTEXT_SIZE 8                   /*size of sender context in encapsulation header*/
 
-
 /* definition of known encapsulation commands */
 #define COMMAND_NOP                     0x0000
 #define COMMAND_LISTSERVICES            0x0004
@@ -43,7 +42,6 @@
 #define SUPPORT_CIP_TCP                 0x0020
 #define SUPPORT_CIP_UDP_CLASS_0_OR_1    0x0100
 
-
 /*identiy data from cipidentity.c*/
 extern EIP_UINT16 VendorID;
 extern EIP_UINT16 DeviceType;
@@ -77,48 +75,57 @@ struct S_Encapsulation_Interface_Information g_stInterfaceInformation;
 int anRegisteredSessions[OPENER_NUMBER_OF_SUPPORTED_SESSIONS];
 
 /*** private functions ***/
-int nop(void);
-int ListServices(struct S_Encapsulation_Data *pa_stReceiveData);
-int ListInterfaces(struct S_Encapsulation_Data *pa_stReceiveData);
-int ListIdentity(struct S_Encapsulation_Data *pa_stReceiveData);
-int RegisterSession(int pa_nSockfd,
-    struct S_Encapsulation_Data *pa_stReceiveData);
-int UnregisterSession(struct S_Encapsulation_Data *pa_stReceiveData);
-int SendUnitData(struct S_Encapsulation_Data *pa_stReceiveData);
-int SendRRData(struct S_Encapsulation_Data *pa_stReceiveData);
-
-int getFreeSessionIndex(void);
-EIP_INT16 createEncapsulationStructure(EIP_UINT8 * buf, int length,
-    struct S_Encapsulation_Data *pa_S_ReceiveData);
-EIP_STATUS checkRegisteredSessions(
+int
+nop(void);
+int
+ListServices(struct S_Encapsulation_Data *pa_stReceiveData);
+int
+ListInterfaces(struct S_Encapsulation_Data *pa_stReceiveData);
+int
+ListIdentity(struct S_Encapsulation_Data *pa_stReceiveData);
+int
+RegisterSession(int pa_nSockfd, struct S_Encapsulation_Data *pa_stReceiveData);
+int
+UnregisterSession(struct S_Encapsulation_Data *pa_stReceiveData);
+int
+SendUnitData(struct S_Encapsulation_Data *pa_stReceiveData);
+int
+SendRRData(struct S_Encapsulation_Data *pa_stReceiveData);
+
+int
+getFreeSessionIndex(void);
+EIP_INT16
+createEncapsulationStructure(EIP_UINT8 * buf, int length,
     struct S_Encapsulation_Data *pa_S_ReceiveData);
-int encapsulate_data(struct S_Encapsulation_Data *pa_S_SendData);
-
+EIP_STATUS
+checkRegisteredSessions(struct S_Encapsulation_Data *pa_S_ReceiveData);
+int
+encapsulate_data(struct S_Encapsulation_Data *pa_S_SendData);
 
 /*   void encapInit(void)
  *   initialize sessionlist and interfaceinformation.
  */
 
-void encapInit(void)
-  {
-    int i;
-
-    /* initialize Sessions to invalid == free session */
-    for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++)
-      {
-        anRegisteredSessions[i] = EIP_INVALID_SOCKET;
-      }
-
-    /*TODO make th interface inforamtion configureable*/
-    /* initialize interface information */
-    g_stInterfaceInformation.TypeCode = CIP_ITEM_ID_LISTSERVICE_RESPONSE;
-    g_stInterfaceInformation.Length
-        = sizeof(g_stInterfaceInformation);
-    g_stInterfaceInformation.EncapsulationProtocolVersion = 1;
-    g_stInterfaceInformation.CapabilityFlags = SUPPORT_CIP_TCP
-    | SUPPORT_CIP_UDP_CLASS_0_OR_1;
-    strcpy((char *) g_stInterfaceInformation.NameofService, "communications");
-  }
+void
+encapInit(void)
+{
+  int i;
+
+  /* initialize Sessions to invalid == free session */
+  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++)
+    {
+      anRegisteredSessions[i] = EIP_INVALID_SOCKET;
+    }
+
+  /*TODO make th interface inforamtion configureable*/
+  /* initialize interface information */
+  g_stInterfaceInformation.TypeCode = CIP_ITEM_ID_LISTSERVICE_RESPONSE;
+  g_stInterfaceInformation.Length = sizeof(g_stInterfaceInformation);
+  g_stInterfaceInformation.EncapsulationProtocolVersion = 1;
+  g_stInterfaceInformation.CapabilityFlags = SUPPORT_CIP_TCP
+      | SUPPORT_CIP_UDP_CLASS_0_OR_1;
+  strcpy((char *) g_stInterfaceInformation.NameofService, "communications");
+}
 
 /*   int handleReceivedExplictData(int pa_socket, EIP_UINT8* pa_buf, int pa_length. int *pa_nRemainingBytes)
  *   Read received bytes, copy to struct S_Encapsulation_data and handles the command.
@@ -127,132 +134,138 @@ void encapInit(void)
  *      pa_length	length of the data in pa_buf.
  *  return length of reply
  */
-int handleReceivedExplictData(int pa_socket, /* socket from which data was recevied*/
-    EIP_UINT8 * pa_buf, /* input buffer*/
-    int pa_length, /* length of input*/
-    int *pa_nRemainingBytes) /* return how many bytes of the input are left over after we're done here*/
-  {
-    int nRetVal = 0;
-    /* eat the encapsulation header*/
-    /* the structure contains a pointer to the encapsulated data*/
-    /* returns how many bytes are left after the encapsulated data*/
-    *pa_nRemainingBytes = createEncapsulationStructure(pa_buf, pa_length,
-        &g_sEncapData);
-
-    if (SUPPORTED_OPTIONS_MASK == g_sEncapData.nOptions) /*TODO generate aproriate error response*/
-      {        
-        if (*pa_nRemainingBytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
-          {
-            /* full package or more received */
-            g_sEncapData.nStatus = OPENER_ENCAP_STATUS_SUCCESS;
-            /* each of these can return one of:
-               reply size >0
-               0 (no reply shall be sent)
-               EIP_ERROR (i.e. -1) an error occurred, no reply shall be sent*/
-            switch (g_sEncapData.nCommand_code)
-              {
-            case (COMMAND_NOP):
-              nRetVal = nop();
-              break;
+int
+handleReceivedExplictData(int pa_socket, /* socket from which data was recevied*/
+EIP_UINT8 * pa_buf, /* input buffer*/
+int pa_length, /* length of input*/
+int *pa_nRemainingBytes) /* return how many bytes of the input are left over after we're done here*/
+{
+  int nRetVal = 0;
+  /* eat the encapsulation header*/
+  /* the structure contains a pointer to the encapsulated data*/
+  /* returns how many bytes are left after the encapsulated data*/
+  *pa_nRemainingBytes = createEncapsulationStructure(pa_buf, pa_length,
+      &g_sEncapData);
+
+  if (SUPPORTED_OPTIONS_MASK == g_sEncapData.nOptions) /*TODO generate aproriate error response*/
+    {
+      if (*pa_nRemainingBytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
+        {
+          /* full package or more received */
+          g_sEncapData.nStatus = OPENER_ENCAP_STATUS_SUCCESS;
+          /* each of these can return one of:
+           reply size >0
+           0 (no reply shall be sent)
+           EIP_ERROR (i.e. -1) an error occurred, no reply shall be sent*/
+          switch (g_sEncapData.nCommand_code)
+            {
+          case (COMMAND_NOP):
+            nRetVal = nop();
+            break;
 
-            case (COMMAND_LISTSERVICES):
-              nRetVal = ListServices(&g_sEncapData);
-              break;
+          case (COMMAND_LISTSERVICES):
+            nRetVal = ListServices(&g_sEncapData);
+            break;
 
-            case (COMMAND_LISTIDENTITY):
-              nRetVal = ListIdentity(&g_sEncapData);
-              break;
+          case (COMMAND_LISTIDENTITY):
+            nRetVal = ListIdentity(&g_sEncapData);
+            break;
 
-            case (COMMAND_LISTINTERFACES):
-              nRetVal = ListInterfaces(&g_sEncapData);
-              break;
+          case (COMMAND_LISTINTERFACES):
+            nRetVal = ListInterfaces(&g_sEncapData);
+            break;
 
-            case (COMMAND_REGISTERSESSION):
-              nRetVal = RegisterSession(pa_socket, &g_sEncapData);
-              break;
+          case (COMMAND_REGISTERSESSION):
+            nRetVal = RegisterSession(pa_socket, &g_sEncapData);
+            break;
 
-            case (COMMAND_UNREGISTERSESSION):
-              nRetVal = UnregisterSession(&g_sEncapData);
-              break;
+          case (COMMAND_UNREGISTERSESSION):
+            nRetVal = UnregisterSession(&g_sEncapData);
+            break;
 
-            case (COMMAND_SENDRRDATA):
-              nRetVal = SendRRData(&g_sEncapData);
-              break;
+          case (COMMAND_SENDRRDATA):
+            nRetVal = SendRRData(&g_sEncapData);
+            break;
 
-            case (COMMAND_SENDUNITDATA):
-              nRetVal = SendUnitData(&g_sEncapData); /* not currently supported, SendUnitData is a stub*/
-              break;
-            default:
-              g_sEncapData.nStatus = OPENER_ENCAP_STATUS_INVALID_COMMAND;
-              g_sEncapData.nData_length = 0;
-              nRetVal = encapsulate_data(&g_sEncapData);
-              break;
-              }
-          }
-      }
+          case (COMMAND_SENDUNITDATA):
+            nRetVal = SendUnitData(&g_sEncapData); /* not currently supported, SendUnitData is a stub*/
+            break;
+          default:
+            g_sEncapData.nStatus = OPENER_ENCAP_STATUS_INVALID_COMMAND;
+            g_sEncapData.nData_length = 0;
+            nRetVal = encapsulate_data(&g_sEncapData);
+            break;
+            }
+        }
+    }
 
-    return nRetVal;
-  }
+  return nRetVal;
+}
 
 /*   INT8 encapsulate_data(struct S_Encapsulation_Data *pa_stSendData)
  *   add encapsulation header and sender_context to data.
  *      pa_stSendData pointer to structure with header and datapointer.
  *  return size of reply
  */
-int encapsulate_data(struct S_Encapsulation_Data *pa_stSendData)
-  {
-    pa_stSendData->pEncapsulation_Data = &g_acCommBuf[2];
-    /*htols(pa_stSendData->nCommand_code, &pa_stSendData->pEncapsulation_Data);*/
-    htols(pa_stSendData->nData_length, &pa_stSendData->pEncapsulation_Data);
-    /*the g_acCommBuf should already contain the correct session handle*/
-    /*htoll(pa_stSendData->nSession_handle, &pa_stSendData->pEncapsulation_Data); */
-    pa_stSendData->pEncapsulation_Data += 4;
-    htoll(pa_stSendData->nStatus, &pa_stSendData->pEncapsulation_Data);
-    /*the g_acCommBuf should already contain the correct sender context*/
-    /*memcpy(pa_stSendData->pEncapsulation_Data, pa_stSendData->anSender_context, SENDER_CONTEXT_SIZE);*/
-    pa_stSendData->pEncapsulation_Data += SENDER_CONTEXT_SIZE + 2; /* the plus 2 is for the options value*/
-    /*the g_acCommBuf should already contain the correct  options value*/
-    /*htols((EIP_UINT16)pa_stSendData->nOptions, &pa_stSendData->pEncapsulation_Data);*/
-
-    return ENCAPSULATION_HEADER_LENGTH + pa_stSendData->nData_length;
-  }
+int
+encapsulate_data(struct S_Encapsulation_Data *pa_stSendData)
+{
+  pa_stSendData->pEncapsulation_Data = &g_acCommBuf[2];
+  /*htols(pa_stSendData->nCommand_code, &pa_stSendData->pEncapsulation_Data);*/
+  htols(pa_stSendData->nData_length, &pa_stSendData->pEncapsulation_Data);
+  /*the g_acCommBuf should already contain the correct session handle*/
+  /*htoll(pa_stSendData->nSession_handle, &pa_stSendData->pEncapsulation_Data); */
+  pa_stSendData->pEncapsulation_Data += 4;
+  htoll(pa_stSendData->nStatus, &pa_stSendData->pEncapsulation_Data);
+  /*the g_acCommBuf should already contain the correct sender context*/
+  /*memcpy(pa_stSendData->pEncapsulation_Data, pa_stSendData->anSender_context, SENDER_CONTEXT_SIZE);*/
+  pa_stSendData->pEncapsulation_Data += SENDER_CONTEXT_SIZE + 2; /* the plus 2 is for the options value*/
+  /*the g_acCommBuf should already contain the correct  options value*/
+  /*htols((EIP_UINT16)pa_stSendData->nOptions, &pa_stSendData->pEncapsulation_Data);*/
+
+  return ENCAPSULATION_HEADER_LENGTH + pa_stSendData->nData_length;
+}
 
 /*   INT8 nop()
  *   do nothing, only implemented for CIP conformity.
  */
-int nop(void)
-  {
-    return 0;
-  }
+int
+nop(void)
+{
+  return 0;
+}
 
 /*   INT8 ListServices(struct S_Encapsulation_Data *pa_S_ReceiveData)
  *   generate reply with "Communications Services" + compatibility Flags.
  *      pa_S_ReceiveData pointer to structur with received data
  */
-int ListServices(struct S_Encapsulation_Data *pa_stReceiveData)
-  {
-    pa_stReceiveData->nData_length = g_stInterfaceInformation.Length + 2;
-
-    EIP_UINT8 *pacCommBuf = pa_stReceiveData->pEncapsulation_Data;
-    /* copy Interface data to nmsg for sending */
-    htols(1, &pacCommBuf);
-    htols(g_stInterfaceInformation.TypeCode, &pacCommBuf);
-    htols((EIP_UINT16)(g_stInterfaceInformation.Length - 4), &pacCommBuf);
-    htols(g_stInterfaceInformation.EncapsulationProtocolVersion, &pacCommBuf);
-    htols(g_stInterfaceInformation.CapabilityFlags, &pacCommBuf);
-    memcpy(pacCommBuf, g_stInterfaceInformation.NameofService, sizeof(g_stInterfaceInformation.NameofService));
-
-    return encapsulate_data(pa_stReceiveData); /* encapsulate the data from structure and send to originator a reply */
-  }
-
-int ListInterfaces(struct S_Encapsulation_Data *pa_stReceiveData)
-  {
-    pa_stReceiveData->nData_length = 2;
-    EIP_UINT8 *pacCommBuf = pa_stReceiveData->pEncapsulation_Data;
-    htols(0x0000, &pacCommBuf); /* copy Interface data to nmsg for sending */
-
-    return encapsulate_data(pa_stReceiveData); /* encapsulate the data from structure and send to originator a reply */
-  }
+int
+ListServices(struct S_Encapsulation_Data *pa_stReceiveData)
+{
+  pa_stReceiveData->nData_length = g_stInterfaceInformation.Length + 2;
+
+  EIP_UINT8 *pacCommBuf = pa_stReceiveData->pEncapsulation_Data;
+  /* copy Interface data to nmsg for sending */
+  htols(1, &pacCommBuf);
+  htols(g_stInterfaceInformation.TypeCode, &pacCommBuf);
+  htols((EIP_UINT16) (g_stInterfaceInformation.Length - 4), &pacCommBuf);
+  htols(g_stInterfaceInformation.EncapsulationProtocolVersion, &pacCommBuf);
+  htols(g_stInterfaceInformation.CapabilityFlags, &pacCommBuf);
+  memcpy(pacCommBuf, g_stInterfaceInformation.NameofService,
+      sizeof(g_stInterfaceInformation.NameofService));
+
+  return encapsulate_data(pa_stReceiveData); /* encapsulate the data from structure and send to originator a reply */
+}
+
+int
+ListInterfaces(struct S_Encapsulation_Data *pa_stReceiveData)
+{
+  pa_stReceiveData->nData_length = 2;
+  EIP_UINT8 *pacCommBuf = pa_stReceiveData->pEncapsulation_Data;
+  htols(0x0000, &pacCommBuf); /* copy Interface data to nmsg for sending */
+
+  return encapsulate_data(pa_stReceiveData); /* encapsulate the data from structure and send to originator a reply */
+}
 
 /*   INT8 ListIdentity(struct S_Encapsulation_Data *pa_S_ReceiveData)
  *   send Get_Attribute_All to Identity Object and send data + sender_context back.
@@ -260,42 +273,43 @@ int ListInterfaces(struct S_Encapsulation_Data *pa_stReceiveData)
  *  return status
  * 			0 .. success
  */
-int ListIdentity(struct S_Encapsulation_Data * pa_stReceiveData)
-  {
-    /* List Identity reply according to EIP/CIP Specification */
-    EIP_UINT8 *pacCommBuf = pa_stReceiveData->pEncapsulation_Data;
-
-    htols(1, &pacCommBuf); /* one item */
-    htols(ITEM_ID_LISTIDENTITY, &pacCommBuf);
-
-    EIP_BYTE *acIdLenBuf = pacCommBuf;
-    pacCommBuf += 2; /*at this place the real length will be inserted below*/
-
-    htols(SUPPORTED_PROTOCOL_VERSION, &pacCommBuf);
-    htols(htons(AF_INET), &pacCommBuf); 
-    htols(htons(OPENER_ETHERNET_PORT), &pacCommBuf);
-    htoll(Interface_Configuration.IPAddress, &pacCommBuf);
-    memset(pacCommBuf, 0, 8);
-    pacCommBuf += 8;
-
-    htols(VendorID, &pacCommBuf);
-    htols(DeviceType, &pacCommBuf);
-    htols(ProductCode, &pacCommBuf);
-    *(pacCommBuf)++ = Revison.MajorRevision;
-    *(pacCommBuf)++ = Revison.MinorRevision;
-    htols(ID_Status, &pacCommBuf);
-    htoll(SerialNumber, &pacCommBuf);
-    *pacCommBuf++ = (unsigned char) ProductName.Length;
-    memcpy(pacCommBuf, ProductName.String, ProductName.Length);
-    pacCommBuf += ProductName.Length;
-    *pacCommBuf++ = 0x03;
-
-    pa_stReceiveData->nData_length = pacCommBuf
-        - &g_acCommBuf[ENCAPSULATION_HEADER_LENGTH];
-    htols(pacCommBuf - acIdLenBuf - 2, &acIdLenBuf); /* the -2 is for not counting the lenght field*/
-
-    return encapsulate_data(pa_stReceiveData);
-  }
+int
+ListIdentity(struct S_Encapsulation_Data * pa_stReceiveData)
+{
+  /* List Identity reply according to EIP/CIP Specification */
+  EIP_UINT8 *pacCommBuf = pa_stReceiveData->pEncapsulation_Data;
+
+  htols(1, &pacCommBuf); /* one item */
+  htols(ITEM_ID_LISTIDENTITY, &pacCommBuf);
+
+  EIP_BYTE *acIdLenBuf = pacCommBuf;
+  pacCommBuf += 2; /*at this place the real length will be inserted below*/
+
+  htols(SUPPORTED_PROTOCOL_VERSION, &pacCommBuf);
+  htols(htons(AF_INET), &pacCommBuf);
+  htols(htons(OPENER_ETHERNET_PORT), &pacCommBuf);
+  htoll(Interface_Configuration.IPAddress, &pacCommBuf);
+  memset(pacCommBuf, 0, 8);
+  pacCommBuf += 8;
+
+  htols(VendorID, &pacCommBuf);
+  htols(DeviceType, &pacCommBuf);
+  htols(ProductCode, &pacCommBuf);
+  *(pacCommBuf)++ = Revison.MajorRevision;
+  *(pacCommBuf)++ = Revison.MinorRevision;
+  htols(ID_Status, &pacCommBuf);
+  htoll(SerialNumber, &pacCommBuf);
+  *pacCommBuf++ = (unsigned char) ProductName.Length;
+  memcpy(pacCommBuf, ProductName.String, ProductName.Length);
+  pacCommBuf += ProductName.Length;
+  *pacCommBuf++ = 0x03;
+
+  pa_stReceiveData->nData_length = pacCommBuf
+      - &g_acCommBuf[ENCAPSULATION_HEADER_LENGTH];
+  htols(pacCommBuf - acIdLenBuf - 2, &acIdLenBuf); /* the -2 is for not counting the lenght field*/
+
+  return encapsulate_data(pa_stReceiveData);
+}
 
 /*   INT8 RegisterSession(struct S_Encapsulation_Data *pa_S_ReceiveData)
  *   Check supported protocol, generate session handle, send replay back to originator.
@@ -304,61 +318,61 @@ int ListIdentity(struct S_Encapsulation_Data * pa_stReceiveData)
  *  return status
  * 			0 .. success
  */
-int RegisterSession(int pa_nSockfd,
-    struct S_Encapsulation_Data * pa_stReceiveData)
-  {
-    int i;
-    int nSessionIndex = 0;
-    EIP_UINT8 *pacBuf;
-    EIP_UINT16 nProtocolVersion = ltohs(&pa_stReceiveData->pEncapsulation_Data);
-    EIP_UINT16 nOptionFlag = ltohs(&pa_stReceiveData->pEncapsulation_Data);
-    
-    /* check if requested protocol version is supported and the register session option flag is zero*/
-    if ((0 < nProtocolVersion) && (nProtocolVersion
-        <= SUPPORTED_PROTOCOL_VERSION) && (0 == nOptionFlag))
-      { /*Option field should be zero*/
-        /* check if the socket has already a session open */
-        for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i)
-          {
-            if (anRegisteredSessions[i] == pa_nSockfd)
-              {
-                /* the socket has already registered a session this is not allowed*/
-                pa_stReceiveData->nSession_handle = i + 1; /*return the already assigned session back, the cip spec is not clear about this needs to be tested*/
-                pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_UNSUPPORTED_PROTOCOL;
-                nSessionIndex = INVALID_SESSION;
-                pacBuf
-                    = &g_acCommBuf[ENCAPSULATION_HEADER_SESSION_HANDLE_POS];
-                htoll(pa_stReceiveData->nSession_handle, &pacBuf); /*encapsulate_data will not update the session handle so we have to do it here by hand*/
-                break;
-              }
-          }
-
-        if (INVALID_SESSION != nSessionIndex)
-          {
-            nSessionIndex = getFreeSessionIndex();
-            if (INVALID_SESSION == nSessionIndex) /* no more sessions available */
-              {
-                pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INSUFFICIENT_MEM;
-              }
-            else
-              { /* successful session registered */
-                anRegisteredSessions[nSessionIndex] = pa_nSockfd; /* store associated socket */
-                pa_stReceiveData->nSession_handle = nSessionIndex + 1;
-                pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_SUCCESS;
-                pacBuf = &g_acCommBuf[ENCAPSULATION_HEADER_SESSION_HANDLE_POS];
-                htoll(pa_stReceiveData->nSession_handle, &pacBuf); /*encapsulate_data will not update the session handle so we have to do it here by hand*/
-              }
-          }
-      }
-    else
-      { /* protocol not supported */
-        pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_UNSUPPORTED_PROTOCOL;
-      }
-
-    pa_stReceiveData->nData_length = 4;
-
-    return encapsulate_data(pa_stReceiveData);
-  }
+int
+RegisterSession(int pa_nSockfd, struct S_Encapsulation_Data * pa_stReceiveData)
+{
+  int i;
+  int nSessionIndex = 0;
+  EIP_UINT8 *pacBuf;
+  EIP_UINT16 nProtocolVersion = ltohs(&pa_stReceiveData->pEncapsulation_Data);
+  EIP_UINT16 nOptionFlag = ltohs(&pa_stReceiveData->pEncapsulation_Data);
+
+  /* check if requested protocol version is supported and the register session option flag is zero*/
+  if ((0 < nProtocolVersion)
+      && (nProtocolVersion <= SUPPORTED_PROTOCOL_VERSION) && (0 == nOptionFlag))
+    { /*Option field should be zero*/
+      /* check if the socket has already a session open */
+      for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i)
+        {
+          if (anRegisteredSessions[i] == pa_nSockfd)
+            {
+              /* the socket has already registered a session this is not allowed*/
+              pa_stReceiveData->nSession_handle = i + 1; /*return the already assigned session back, the cip spec is not clear about this needs to be tested*/
+              pa_stReceiveData->nStatus
+                  = OPENER_ENCAP_STATUS_UNSUPPORTED_PROTOCOL;
+              nSessionIndex = INVALID_SESSION;
+              pacBuf = &g_acCommBuf[ENCAPSULATION_HEADER_SESSION_HANDLE_POS];
+              htoll(pa_stReceiveData->nSession_handle, &pacBuf); /*encapsulate_data will not update the session handle so we have to do it here by hand*/
+              break;
+            }
+        }
+
+      if (INVALID_SESSION != nSessionIndex)
+        {
+          nSessionIndex = getFreeSessionIndex();
+          if (INVALID_SESSION == nSessionIndex) /* no more sessions available */
+            {
+              pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INSUFFICIENT_MEM;
+            }
+          else
+            { /* successful session registered */
+              anRegisteredSessions[nSessionIndex] = pa_nSockfd; /* store associated socket */
+              pa_stReceiveData->nSession_handle = nSessionIndex + 1;
+              pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_SUCCESS;
+              pacBuf = &g_acCommBuf[ENCAPSULATION_HEADER_SESSION_HANDLE_POS];
+              htoll(pa_stReceiveData->nSession_handle, &pacBuf); /*encapsulate_data will not update the session handle so we have to do it here by hand*/
+            }
+        }
+    }
+  else
+    { /* protocol not supported */
+      pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_UNSUPPORTED_PROTOCOL;
+    }
+
+  pa_stReceiveData->nData_length = 4;
+
+  return encapsulate_data(pa_stReceiveData);
+}
 
 /*   INT8 UnregisterSession(struct S_Encapsulation_Data *pa_S_ReceiveData)
  *   close all corresponding TCP connections and delete session handle.
@@ -366,27 +380,29 @@ int RegisterSession(int pa_nSockfd,
  *  return status
  * 			0.. success
  */
-int UnregisterSession(struct S_Encapsulation_Data * pa_stReceiveData)
-  {
-    int i;
-    
-    if((0 < pa_stReceiveData->nSession_handle) && 
-       (pa_stReceiveData->nSession_handle <= OPENER_NUMBER_OF_SUPPORTED_SESSIONS))
-      {
-        i = pa_stReceiveData->nSession_handle - 1;   
-        if(EIP_INVALID_SOCKET != anRegisteredSessions[i])
-          {
-            IApp_CloseSocket(anRegisteredSessions[i]);
-            anRegisteredSessions[i] = EIP_INVALID_SOCKET;
-            return EIP_OK;
-          }
-      }
-    
-    /* no such session registered */
-    pa_stReceiveData->nData_length = 0;
-    pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
-    return encapsulate_data(pa_stReceiveData);
-  }
+int
+UnregisterSession(struct S_Encapsulation_Data * pa_stReceiveData)
+{
+  int i;
+
+  if ((0 < pa_stReceiveData->nSession_handle)
+      && (pa_stReceiveData->nSession_handle
+          <= OPENER_NUMBER_OF_SUPPORTED_SESSIONS))
+    {
+      i = pa_stReceiveData->nSession_handle - 1;
+      if (EIP_INVALID_SOCKET != anRegisteredSessions[i])
+        {
+          IApp_CloseSocket(anRegisteredSessions[i]);
+          anRegisteredSessions[i] = EIP_INVALID_SOCKET;
+          return EIP_OK;
+        }
+    }
+
+  /* no such session registered */
+  pa_stReceiveData->nData_length = 0;
+  pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
+  return encapsulate_data(pa_stReceiveData);
+}
 
 /*   INT8 SendUnitData(struct S_Encapsulation_Data *pa_S_ReceiveData)
  *   Call Connection Manager.
@@ -394,34 +410,36 @@ int UnregisterSession(struct S_Encapsulation_Data * pa_stReceiveData)
  *  return status 	0 .. success.
  * 					-1 .. error
  */
-int SendUnitData(struct S_Encapsulation_Data * pa_stReceiveData)
-  {
-    EIP_INT16 nSendSize;
-    /* Commandspecific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
-    /* don't use the data yet */
-    ltohl(&pa_stReceiveData->pEncapsulation_Data); /* skip over null interface handle*/
-    ltohs(&pa_stReceiveData->pEncapsulation_Data); /* skip over unnused timeout value*/
-    pa_stReceiveData->nData_length -= 6; /* the rest is in CPF format*/
-
-    if (checkRegisteredSessions(pa_stReceiveData) == EIP_ERROR) /* see if the EIP session is registered*/
-      { /* received a package with non registerd session handle */
-        pa_stReceiveData->nData_length = 0;
-        pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
-        return encapsulate_data(pa_stReceiveData);
-      }
-
-    nSendSize = notifyConnectedCPF(pa_stReceiveData->pEncapsulation_Data,
-        pa_stReceiveData->nData_length,
-        &g_acCommBuf[ENCAPSULATION_HEADER_LENGTH]);
-
-    if (nSendSize > 0)
-      { /* need to send reply */
-        pa_stReceiveData->nData_length = nSendSize;
-        return encapsulate_data(pa_stReceiveData);
-      }
-
-    return nSendSize;
-  }
+int
+SendUnitData(struct S_Encapsulation_Data * pa_stReceiveData)
+{
+  EIP_INT16 nSendSize;
+  /* Commandspecific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
+  /* don't use the data yet */
+  ltohl(&pa_stReceiveData->pEncapsulation_Data); /* skip over null interface handle*/
+  ltohs(&pa_stReceiveData->pEncapsulation_Data); /* skip over unnused timeout value*/
+  pa_stReceiveData->nData_length -= 6; /* the rest is in CPF format*/
+
+  if (checkRegisteredSessions(pa_stReceiveData) == EIP_ERROR) /* see if the EIP session is registered*/
+    { /* received a package with non registerd session handle */
+      pa_stReceiveData->nData_length = 0;
+      pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
+      return encapsulate_data(pa_stReceiveData);
+    }
+
+  nSendSize
+      = notifyConnectedCPF(pa_stReceiveData->pEncapsulation_Data,
+          pa_stReceiveData->nData_length,
+          &g_acCommBuf[ENCAPSULATION_HEADER_LENGTH]);
+
+  if (nSendSize > 0)
+    { /* need to send reply */
+      pa_stReceiveData->nData_length = nSendSize;
+      return encapsulate_data(pa_stReceiveData);
+    }
+
+  return nSendSize;
+}
 
 /*   INT8 SendRRData(struct S_Encapsulation_Data *pa_stReceiveData)
  *   Call UCMM or Message Router if UCMM not implemented.
@@ -429,52 +447,55 @@ int SendUnitData(struct S_Encapsulation_Data * pa_stReceiveData)
  *  return status 	0 .. success.
  * 					-1 .. error
  */
-int SendRRData(struct S_Encapsulation_Data * pa_stReceiveData)
-  {
-    EIP_INT16 nSendSize;
-    /* Commandspecific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
-    /* don't use the data yet */
-    ltohl(&pa_stReceiveData->pEncapsulation_Data); /* skip over null interface handle*/
-    ltohs(&pa_stReceiveData->pEncapsulation_Data); /* skip over unnused timeout value*/
-    pa_stReceiveData->nData_length -= 6; /* the rest is in CPF format*/
-
-    if (checkRegisteredSessions(pa_stReceiveData) == EIP_ERROR) /* see if the EIP session is registered*/
-      { /* received a package with non registerd session handle */
-        pa_stReceiveData->nData_length = 0;
-        pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
-        return encapsulate_data(pa_stReceiveData);
-      }
-
-    nSendSize = notifyCPF(pa_stReceiveData->pEncapsulation_Data,
-        pa_stReceiveData->nData_length,
-        &g_acCommBuf[ENCAPSULATION_HEADER_LENGTH]);
-
-    if (nSendSize > 0)
-      { /* need to send reply */
-        pa_stReceiveData->nData_length = nSendSize;
-        return encapsulate_data(pa_stReceiveData);
-      }
-
-    return nSendSize;
-  }
+int
+SendRRData(struct S_Encapsulation_Data * pa_stReceiveData)
+{
+  EIP_INT16 nSendSize;
+  /* Commandspecific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
+  /* don't use the data yet */
+  ltohl(&pa_stReceiveData->pEncapsulation_Data); /* skip over null interface handle*/
+  ltohs(&pa_stReceiveData->pEncapsulation_Data); /* skip over unnused timeout value*/
+  pa_stReceiveData->nData_length -= 6; /* the rest is in CPF format*/
+
+  if (checkRegisteredSessions(pa_stReceiveData) == EIP_ERROR) /* see if the EIP session is registered*/
+    { /* received a package with non registerd session handle */
+      pa_stReceiveData->nData_length = 0;
+      pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
+      return encapsulate_data(pa_stReceiveData);
+    }
+
+  nSendSize
+      = notifyCPF(pa_stReceiveData->pEncapsulation_Data,
+          pa_stReceiveData->nData_length,
+          &g_acCommBuf[ENCAPSULATION_HEADER_LENGTH]);
+
+  if (nSendSize > 0)
+    { /* need to send reply */
+      pa_stReceiveData->nData_length = nSendSize;
+      return encapsulate_data(pa_stReceiveData);
+    }
+
+  return nSendSize;
+}
 
 /*   INT8 getFreeSessionIndex()
  *   search for available sessions an return index.
  *  return index of free session in anRegisteredSessions.
  * 			-1 .. no free session available
  */
-int getFreeSessionIndex(void)
-  {
-    int i;
-    for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++)
-      {
-        if (EIP_INVALID_SOCKET == anRegisteredSessions[i])
-          {
-            return i;
-          }
-      }
-    return -1;
-  }
+int
+getFreeSessionIndex(void)
+{
+  int i;
+  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++)
+    {
+      if (EIP_INVALID_SOCKET == anRegisteredSessions[i])
+        {
+          return i;
+        }
+    }
+  return -1;
+}
 
 /*   INT16 createEncapsulationStructure(INT16 pa_sockfd, INT8 *pa_buf, UINT16 pa_length, struct S_Encapsulation_Data *pa_S_Data)
  *   copy data from pa_buf in little endian to host in structure.
@@ -485,21 +506,22 @@ int getFreeSessionIndex(void)
  * 			>0 .. more than one packet received
  * 			<0 .. only fragment of data portion received
  */
-EIP_INT16 createEncapsulationStructure( EIP_UINT8 * pa_buf, /* receive buffer*/
-    int pa_length, /* size of stuff in  buffer (might be more than one message)*/
-    struct S_Encapsulation_Data * pa_stData) /* the struct to be created*/
-
-  {
-    pa_stData->nCommand_code = ltohs(&pa_buf);
-    pa_stData->nData_length = ltohs(&pa_buf);
-    pa_stData->nSession_handle = ltohl(&pa_buf);
-    pa_stData->nStatus = ltohl(&pa_buf);
-    /*memcpy(pa_stData->anSender_context, pa_buf, SENDER_CONTEXT_SIZE);*/
-    pa_buf += SENDER_CONTEXT_SIZE;
-    pa_stData->nOptions = ltohl(&pa_buf);
-    pa_stData->pEncapsulation_Data = pa_buf;
-    return (pa_length - ENCAPSULATION_HEADER_LENGTH - pa_stData->nData_length);
-  }
+EIP_INT16
+createEncapsulationStructure(EIP_UINT8 * pa_buf, /* receive buffer*/
+int pa_length, /* size of stuff in  buffer (might be more than one message)*/
+struct S_Encapsulation_Data * pa_stData) /* the struct to be created*/
+
+{
+  pa_stData->nCommand_code = ltohs(&pa_buf);
+  pa_stData->nData_length = ltohs(&pa_buf);
+  pa_stData->nSession_handle = ltohl(&pa_buf);
+  pa_stData->nStatus = ltohl(&pa_buf);
+  /*memcpy(pa_stData->anSender_context, pa_buf, SENDER_CONTEXT_SIZE);*/
+  pa_buf += SENDER_CONTEXT_SIZE;
+  pa_stData->nOptions = ltohl(&pa_buf);
+  pa_stData->pEncapsulation_Data = pa_buf;
+  return (pa_length - ENCAPSULATION_HEADER_LENGTH - pa_stData->nData_length);
+}
 
 /*   INT8 checkRegisteredSessions(struct S_Encapsulation_Data *pa_S_ReceiveData)
  *   check if received package belongs to registered session.
@@ -507,32 +529,35 @@ EIP_INT16 createEncapsulationStructure( EIP_UINT8 * pa_buf, /* receive buffer*/
  *  return 0 .. Session registered
  *  		-1 .. invalid session -> return unsupported command received
  */
-EIP_STATUS checkRegisteredSessions(
-    struct S_Encapsulation_Data * pa_stReceiveData)
-  {
-    
-    if((0 < pa_stReceiveData->nSession_handle) && 
-       (pa_stReceiveData->nSession_handle <= OPENER_NUMBER_OF_SUPPORTED_SESSIONS))
-      {
-        if(EIP_INVALID_SOCKET != anRegisteredSessions[pa_stReceiveData->nSession_handle - 1])
-          {
-            return EIP_OK;
-          }
-      }
-    
-    return EIP_ERROR;
-  }
-
-void closeSession(int pa_nSocket)
-  {
-    int i;
-    for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i)
-      {
-        if (anRegisteredSessions[i] == pa_nSocket)
-          {
-            IApp_CloseSocket(pa_nSocket);
-            anRegisteredSessions[i] = EIP_INVALID_SOCKET;
-            break;
-          }
-      }
-  }
+EIP_STATUS
+checkRegisteredSessions(struct S_Encapsulation_Data * pa_stReceiveData)
+{
+
+  if ((0 < pa_stReceiveData->nSession_handle)
+      && (pa_stReceiveData->nSession_handle
+          <= OPENER_NUMBER_OF_SUPPORTED_SESSIONS))
+    {
+      if (EIP_INVALID_SOCKET
+          != anRegisteredSessions[pa_stReceiveData->nSession_handle - 1])
+        {
+          return EIP_OK;
+        }
+    }
+
+  return EIP_ERROR;
+}
+
+void
+closeSession(int pa_nSocket)
+{
+  int i;
+  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i)
+    {
+      if (anRegisteredSessions[i] == pa_nSocket)
+        {
+          IApp_CloseSocket(pa_nSocket);
+          anRegisteredSessions[i] = EIP_INVALID_SOCKET;
+          break;
+        }
+    }
+}

+ 68 - 46
src/opener_api.h

@@ -28,7 +28,8 @@
  *  @param pa_acGateway     the gateway address 
  *  @return EIP_OK if the configuring worked otherwise EIP_ERROR
  */
-EIP_STATUS configureNetworkInterface(const char *pa_acIpAdress,
+EIP_STATUS
+configureNetworkInterface(const char *pa_acIpAdress,
     const char *pa_acSubNetMask, const char *pa_acGateway);
 
 /*! \ingroup CIP_API 
@@ -36,32 +37,37 @@ EIP_STATUS configureNetworkInterface(const char *pa_acIpAdress,
  * 
  *  @param pa_acMACAddress  the hardware MAC address of the network interface
  */
-void configureMACAddress(const EIP_UINT8 *pa_acMACAddress);
+void
+configureMACAddress(const EIP_UINT8 *pa_acMACAddress);
 
 /*! \ingroup CIP_API 
  * \brief Configure the domain name of the device
  *  @param pa_acDomainName the domain name to be used
  */
-void configureDomainName(const char *pa_acDomainName);
+void
+configureDomainName(const char *pa_acDomainName);
 
 /*! \ingroup CIP_API 
  * \brief Configure the host name of the device
  *  @param pa_acHostName the host name to be used
  */
-void configureHostName(const char *pa_acHostName);
+void
+configureHostName(const char *pa_acHostName);
 
 /*! \ingroup CIP_API
  * Set the serial number of the device's identy object.
  * 
  * @param pa_nSerialNumber unique 32 bit number identifying the device
- */ 
-void setDeviceSerialNumber(EIP_UINT32 pa_nSerialNumber);
+ */
+void
+setDeviceSerialNumber(EIP_UINT32 pa_nSerialNumber);
 
 /** \ingroup CIP_API 
  * \brief Initialize and setup the CIP-stack
  * 
  */
-void CIP_Init(void);
+void
+CIP_Init(void);
 
 /** \ingroup CIP_API 
  * \brief Get a pointer to a CIP object with given class code
@@ -70,7 +76,8 @@ void CIP_Init(void);
  * @return pointer to CIP Object
  *          0 if object is not present in the stack
  */
-S_CIP_Class *getCIPClass(EIP_UINT32 pa_nClassID);
+S_CIP_Class *
+getCIPClass(EIP_UINT32 pa_nClassID);
 
 /** \ingroup CIP_API 
  * \brief Get a pointer to an instance
@@ -80,8 +87,8 @@ S_CIP_Class *getCIPClass(EIP_UINT32 pa_nClassID);
  * @return pointer to CIP Instance
  *          0 if instance is not in the object
  */
-S_CIP_Instance *getCIPInstance(S_CIP_Class *pa_pstObject,
-    EIP_UINT16 pa_nInstanceNr);
+S_CIP_Instance *
+getCIPInstance(S_CIP_Class *pa_pstObject, EIP_UINT16 pa_nInstanceNr);
 
 /** \ingroup CIP_API 
  * \brief Get a pointer to an instance's attribute
@@ -93,8 +100,8 @@ S_CIP_Instance *getCIPInstance(S_CIP_Class *pa_pstObject,
  * @return pointer to attribute
  *          0 if instance is not in the object
  */
-S_CIP_attribute_struct *getAttribute(S_CIP_Instance * pa_pInstance,
-    EIP_UINT8 pa_nAttributeNr);
+S_CIP_attribute_struct *
+getAttribute(S_CIP_Instance * pa_pInstance, EIP_UINT8 pa_nAttributeNr);
 
 /*! \ingroup CIP_API 
  * \brief Allocate memory for new CIP Class and attributes
@@ -114,9 +121,12 @@ S_CIP_attribute_struct *getAttribute(S_CIP_Instance * pa_pInstance,
  *  @return pointer to new class object
  *      0 on error
  */
-S_CIP_Class *createCIPClass(EIP_UINT32 pa_nClassID, int pa_nNr_of_ClassAttributes, EIP_UINT32 pa_nClassGetAttrAllMask, int pa_nNr_of_ClassServices,
-    int pa_nNr_of_InstanceAttributes, EIP_UINT32 pa_nInstGetAttrAllMask, int pa_nNr_of_InstanceServices, 
-    int pa_nNr_of_Instances, char *pa_acName, EIP_UINT16 pa_nRevision);
+S_CIP_Class *
+createCIPClass(EIP_UINT32 pa_nClassID, int pa_nNr_of_ClassAttributes,
+    EIP_UINT32 pa_nClassGetAttrAllMask, int pa_nNr_of_ClassServices,
+    int pa_nNr_of_InstanceAttributes, EIP_UINT32 pa_nInstGetAttrAllMask,
+    int pa_nNr_of_InstanceServices, int pa_nNr_of_Instances, char *pa_acName,
+    EIP_UINT16 pa_nRevision);
 
 /** \ingroup CIP_API 
  * \brief Add a number of CIP instances to a given CIP class
@@ -133,8 +143,8 @@ S_CIP_Class *createCIPClass(EIP_UINT32 pa_nClassID, int pa_nNr_of_ClassAttribute
  * @return pointer to the first of the new instances
  *              0 on error
  */
-S_CIP_Instance *addCIPInstances(S_CIP_Class *pa_pstCIPObject,
-    int pa_nNr_of_Instances);
+S_CIP_Instance *
+addCIPInstances(S_CIP_Class *pa_pstCIPObject, int pa_nNr_of_Instances);
 
 /** \ingroup CIP_API 
  * \brief Create one instance of a given class with a certain instance number
@@ -146,8 +156,8 @@ S_CIP_Instance *addCIPInstances(S_CIP_Class *pa_pstCIPObject,
  *         already exists the existing is returned an no new instance is created
  * 
  */
-S_CIP_Instance *addCIPInstance(S_CIP_Class * pa_pstCIPClass,
-    EIP_UINT32 pa_nInstanceId);
+S_CIP_Instance *
+addCIPInstance(S_CIP_Class * pa_pstCIPClass, EIP_UINT32 pa_nInstanceId);
 
 /*! \ingroup CIP_API 
  * Insert an attribute in an instance of a CIP class
@@ -156,7 +166,8 @@ S_CIP_Instance *addCIPInstance(S_CIP_Class * pa_pstCIPClass,
  *  @param pa_nCIP_Type type of attribute to be inserted.
  *  @param pa_pt2data pointer to data of attribute.
  */
-void insertAttribute(S_CIP_Instance *pa_pInstance, EIP_UINT8 pa_nAttributeNr,
+void
+insertAttribute(S_CIP_Instance *pa_pInstance, EIP_UINT8 pa_nAttributeNr,
     EIP_UINT8 pa_nCIP_Type, void* pa_pt2data);
 
 /** \ingroup CIP_API 
@@ -170,7 +181,8 @@ void insertAttribute(S_CIP_Instance *pa_pInstance, EIP_UINT8 pa_nAttributeNr,
  * @param pa_ptfuncService pointer to function which represents the service.
  * @param name name of the service
  */
-void insertService(S_CIP_Class *pa_pClass, EIP_UINT8 pa_nServiceNr,
+void
+insertService(S_CIP_Class *pa_pClass, EIP_UINT8 pa_nServiceNr,
     TCIPServiceFunc pa_ptfuncService, char *name);
 
 /** \ingroup CIP_API 
@@ -187,9 +199,9 @@ void insertService(S_CIP_Class *pa_pClass, EIP_UINT8 pa_nServiceNr,
  * In order to support a configuration assembly object it has to be created with this function.
  * The notification on received configuration data is handled with the IApp_after_receive function.
  */
-S_CIP_Instance *createAssemblyObject(EIP_UINT8 pa_nInstanceID,
-    EIP_BYTE *pa_data, EIP_UINT16 pa_datalength);
-
+S_CIP_Instance *
+createAssemblyObject(EIP_UINT8 pa_nInstanceID, EIP_BYTE *pa_data,
+    EIP_UINT16 pa_datalength);
 
 /** \ingroup CIP_API 
  * Notify the encapsulation layer that an explicit message has been received via TCP or UDP.
@@ -200,7 +212,8 @@ S_CIP_Instance *createAssemblyObject(EIP_UINT8 pa_nInstanceID,
  * @param pa_nRemainingBytes return how many bytes of the input are left over after we're done here
  * @return length of reply that need to be sent back
  */
-int handleReceivedExplictData(int pa_socket, EIP_UINT8* pa_buf, int pa_length,
+int
+handleReceivedExplictData(int pa_socket, EIP_UINT8* pa_buf, int pa_length,
     int *pa_nRemainingBytes);
 
 /*! \ingroup CIP_API
@@ -209,8 +222,9 @@ int handleReceivedExplictData(int pa_socket, EIP_UINT8* pa_buf, int pa_length,
  *  @param pa_pnData pointer to the buffer of data that has been recieved 
  *  @param pa_nDataLength number of bytes in the data buffer
  *  @return EIP_OK on success
- */ 
-EIP_STATUS handleReceivedConnectedData(EIP_UINT8 *pa_pnData, int pa_nDataLength);
+ */
+EIP_STATUS
+handleReceivedConnectedData(EIP_UINT8 *pa_pnData, int pa_nDataLength);
 
 /*! \ingroup CIP_API
  * Check if any of the connection timers (TransmissionTrigger or WarchdogTimeout) has timed out.
@@ -219,15 +233,16 @@ EIP_STATUS handleReceivedConnectedData(EIP_UINT8 *pa_pnData, int pa_nDataLength)
  * 
  * @return EIP_OK on success
  */
-EIP_STATUS manageConnections(void); 
+EIP_STATUS
+manageConnections(void);
 
 /*! \ingroup CIP_API
  * Inform the encapsulation layer that the remote host has closed the connection.
  * According to the specs that will clean up and close the session in the encapsulation layer.
  * @param pa_nSocket the handler to the socket of the closed connection
  */
-void closeSession(int pa_nSocket);
-
+void
+closeSession(int pa_nSocket);
 
 /**  \defgroup CIP_CALLBACK_API Callback Functions Demanded by OpENer
  * \ingroup CIP_API
@@ -247,7 +262,8 @@ void closeSession(int pa_nSocket);
  *  return status EIP_ERROR .. error
  *                EIP_OK ... successful finish
  */
-EIP_STATUS IApp_Init(void);
+EIP_STATUS
+IApp_Init(void);
 
 /** \ingroup CIP_CALLBACK_API 
  * \brief Call back function to inform application on received data for an assembly object.
@@ -263,8 +279,8 @@ EIP_STATUS IApp_Init(void);
  * The CIP-stack uses this function to inform on received configuration data. The length of the data
  * is already checked within the stack. Therefore the user only has to check if the data is valid.
  */
-EIP_STATUS IApp_AfterAssemblyDataReceived(S_CIP_Instance *pa_pstInstance);
-
+EIP_STATUS
+IApp_AfterAssemblyDataReceived(S_CIP_Instance *pa_pstInstance);
 /** \ingroup CIP_CALLBACK_API 
  * \brief Inform the application that the data of an assembly
  * object will be sent.
@@ -276,7 +292,8 @@ EIP_STATUS IApp_AfterAssemblyDataReceived(S_CIP_Instance *pa_pstInstance);
  *          - true assembly data has changed
  *          - false assembly data has not changed
  */
-EIP_BOOL8 IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance);
+EIP_BOOL8
+IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance);
 
 /** \ingroup CIP_CALLBACK_API 
  * \brief Emulate as close a possible a power cycle of the device
@@ -284,7 +301,8 @@ EIP_BOOL8 IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance);
  * @return if the service is supported the function will not return.
  *     EIP_ERROR if this service is not supported
  */
-EIP_STATUS IApp_ResetDevice(void);
+EIP_STATUS
+IApp_ResetDevice(void);
 
 /**\ingroup CIP_CALLBACK_API 
  * \brief Reset the device to the initial configuration and emulate as close as possible a power cycle of the device
@@ -292,7 +310,8 @@ EIP_STATUS IApp_ResetDevice(void);
  * return if the service is supported the function will not return.
  *     EIP_ERROR if this service is not supported
  */
-EIP_STATUS IApp_ResetDeviceToInitialConfiguration(void);
+EIP_STATUS
+IApp_ResetDeviceToInitialConfiguration(void);
 
 /**\ingroup CIP_CALLBACK_API 
  * \brief Allocate memory for the cip stack
@@ -304,7 +323,8 @@ EIP_STATUS IApp_ResetDeviceToInitialConfiguration(void);
  * @param pa_nSizeOfElement size in bytes of one element
  * return pointer to the allocated memory, 0 on error
  */
-void *IApp_CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement);
+void *
+IApp_CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement);
 
 /**\ingroup CIP_CALLBACK_API 
  * \brief Inform the application that the Run/Idle State has been changed
@@ -313,7 +333,8 @@ void *IApp_CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement);
  * 
  * @param pa_nRunIdleValue  the current value of the run/idle flag according to CIP spec Vol 1 3-6.5
  */
-void IApp_RunIdleChanged(EIP_UINT32 pa_nRunIdleValue);
+void
+IApp_RunIdleChanged(EIP_UINT32 pa_nRunIdleValue);
 
 /**\ingroup CIP_CALLBACK_API 
  * \brief create a producing or consuming UDP socket
@@ -323,7 +344,8 @@ void IApp_RunIdleChanged(EIP_UINT32 pa_nRunIdleValue);
  * @return socket identifier on success
  *         -1 on error 
  */
-int IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr); 
+int
+IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr);
 
 /**\ingroup CIP_CALLBACK_API 
  * \brief create a producing or consuming UDP socket
@@ -334,7 +356,8 @@ int IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr);
  * @param pa_nDataLength length of the data to send
  * @return  EIP_SUCCESS on success
  */
-EIP_STATUS IApp_SendUDPData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
+EIP_STATUS
+IApp_SendUDPData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
     EIP_UINT8 *pa_acData, EIP_UINT16 pa_nDataLength);
 
 /**\ingroup CIP_CALLBACK_API 
@@ -342,8 +365,8 @@ EIP_STATUS IApp_SendUDPData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
  * 
  * @param pa_nSockFd socket descriptor to close
  */
-void IApp_CloseSocket(int pa_nSockFd);
-
+void
+IApp_CloseSocket(int pa_nSockFd);
 
 /*! \mainpage OpENer - Open Source EtherNet/IP(TM) Communication Stack Documentation
  *
@@ -403,7 +426,7 @@ void IApp_CloseSocket(int pa_nSockFd);
  * 
  * \copydoc opener_user_conf.h
  * 
-* \section startup_sec Startup Sequence
+ * \section startup_sec Startup Sequence
  * During startup of your EtherNet/IP(TM) device the following steps have to be 
  * performed:
  *   -# Configure the network properties:\n
@@ -443,7 +466,7 @@ void IApp_CloseSocket(int pa_nSockFd);
  *      received and can be hand over to the Ethernet encapsulation layer.
  * 
  * \section normal_op_sec Normal Operation
-* During normal operation the following tasks have to be done by the platform
+ * During normal operation the following tasks have to be done by the platform
  * specific code:
  *   - Establish connections requested on TCP port AF12hex
  *   - Receive explicit message data on connected TCP sockets and the UPD socket
@@ -493,8 +516,7 @@ void IApp_CloseSocket(int pa_nSockFd);
  * 
  * \include "license.txt"  
  * 
- */  
-
+ */
 
 #endif /*CIP_API_H_*/
 

+ 2 - 1
src/ports/platform-pc/main.c

@@ -13,7 +13,8 @@
 
 #include "networkhandler.h"
 #include "opener_api.h"
-#include "cipcommon.h" 
+#include "cipcommon.h"
+#include "trace.h"
 
 /* global variables for demo application (3 assembly data fields) */
 EIP_UINT8 g_assemblydata[32]; /* Input */

+ 43 - 67
src/ports/platform-pc/networkhandler.c

@@ -18,12 +18,10 @@
 #include <encap.h>
 #include <cipconnectionmanager.h>
 #include <endianconv.h> 
+#include <trace.h>
 
 EIP_UINT8 g_acCommBuf[OPENER_ETHERNET_BUFFER_SIZE];
 
-extern void
-dump(unsigned char *p, int size);
-
 #define MAX_NO_OF_TCP_SOCKETS 10
 
 typedef long MILLISECONDS;
@@ -104,14 +102,14 @@ Start_NetworkHandler()
   /* create a new TCP socket */
   if ((listener = socket(PF_INET, SOCK_STREAM, 0)) == -1)
     {
-      printf("error allocating socket stream listener, %d\n", errno);
+      OPENER_TRACE_ERR("error allocating socket stream listener, %d\n", errno);
       return EIP_ERROR;
     }
 
   /* create a new UDP socket */
   if ((nUDPListener = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
     {
-      printf("error allocating udp listener socket, %d\n", errno);
+      OPENER_TRACE_ERR("error allocating udp listener socket, %d\n", errno);
       return EIP_ERROR;
     }
 
@@ -124,7 +122,7 @@ Start_NetworkHandler()
   if ((bind(listener, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)))
       == -1)
     {
-      perror("error with bind");
+      OPENER_TRACE_ERR("error with bind: %s", strerror(errno));
       return EIP_ERROR;
     }
 
@@ -132,21 +130,21 @@ Start_NetworkHandler()
   int y = 1;
   if (0 > setsockopt(nUDPListener, SOL_SOCKET, SO_BROADCAST, &y, sizeof(int)))
     {
-      perror("error with setting broadcast receive for udp socket");
+      OPENER_TRACE_ERR("error with setting broadcast receive for udp socket: %s", strerror(errno));
       return EIP_ERROR;
     }
 
   if ((bind(nUDPListener, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)))
       == -1)
     {
-      perror("error with udp bind");
+      OPENER_TRACE_ERR("error with udp bind: %s", strerror(errno));
       return EIP_ERROR;
     }
 
   /* switch socket in listen mode */
   if ((listen(listener, MAX_NO_OF_TCP_SOCKETS)) == -1)
     {
-      perror("networkhandler: error with listen");
+      OPENER_TRACE_ERR("networkhandler: error with listen: %s", strerror(errno));
       return EIP_ERROR;
     }
 
@@ -180,7 +178,7 @@ Start_NetworkHandler()
             }
           else
             {
-              perror("networkhandler: error with select");
+              OPENER_TRACE_ERR("networkhandler: error with select: %s", strerror(errno));
               return EIP_ERROR;
             }
         }
@@ -192,21 +190,20 @@ Start_NetworkHandler()
               {
                 if (!FD_ISSET(fd, &master))
                   {
-                    printf("socket fd %d closed with pending message\n", fd);
+                    OPENER_TRACE_INFO("socket fd %d closed with pending message\n", fd);
                     continue;
                   }
 
                 /* see if this is a connection request to the TCP listener*/
                 if (fd == listener) /* handle new TCP connection */
                   {
-                    if (EIP_DEBUG >= EIP_VERBOSE)
-                      printf("networkhandler: new TCP connection\n");
+                    OPENER_TRACE_INFO("networkhandler: new TCP connection\n");
                     addrlen = sizeof(remote_addr);
                     newfd = accept(listener, (struct sockaddr *) &remote_addr,
                         &addrlen); /* remote_addr does not seem to be used*/
                     if (newfd == -1)
                       {
-                        perror("networkhandler: error on accept");
+                        OPENER_TRACE_ERR("networkhandler: error on accept: %s", strerror(errno));
                         continue;
                       }
 
@@ -214,20 +211,18 @@ Start_NetworkHandler()
                     /* add newfd to master set */
                     if (newfd > fdmax)
                       fdmax = newfd;
-                    if (EIP_DEBUG >= EIP_VERBOSE)
-                      printf(
-                          "networkhandler: opened new TCP connection on fd %d\n",
-                          newfd);
+                    OPENER_TRACE_STATE(
+                        "networkhandler: opened new TCP connection on fd %d\n",
+                        newfd);
                     continue;
                   }
 
                 /* see if this is an unsolicited inbound UDP message */
                 if (fd == nUDPListener)
                   {
-                    if (EIP_DEBUG >= EIP_VERBOSE)
-                      printf(
-                          "networkhandler: unsolicited UDP message on fd %d\n",
-                          fd);
+                    OPENER_TRACE_STATE(
+                        "networkhandler: unsolicited UDP message on fd %d\n",
+                        fd);
 
                     /*Handle udp broadcast messages */
                     nReceived_size = recvfrom(fd, g_acCommBuf,
@@ -236,16 +231,13 @@ Start_NetworkHandler()
 
                     if (nReceived_size <= 0)
                       { /* got error */
-                        perror(
-                            "networkhandler: error on recvfrom udp broadcast port");
+                        OPENER_TRACE_ERR(
+                            "networkhandler: error on recvfrom udp broadcast port: %s",
+                            strerror(errno));
                         continue;
                       }
 
-                    if (EIP_DEBUG >= EIP_VVERBOSE)
-                      {
-                        printf("Data received on udp:\n");
-                        dump(g_acCommBuf, nReceived_size);
-                      }
+                    OPENER_TRACE_INFO("Data received on udp:\n");
 
                     rxp = &g_acCommBuf[0];
                     do
@@ -258,18 +250,14 @@ Start_NetworkHandler()
 
                         if (replylen > 0)
                           {
-                            if (EIP_DEBUG >= EIP_VVERBOSE)
-                              {
-                                printf("reply sent:\n");
-                                dump(g_acCommBuf, replylen);
-                              }
+                            OPENER_TRACE_INFO("reply sent:\n");
 
                             /* if the active fd matches a registered UDP callback, handle a UDP packet */
                             res = sendto(fd, (char *) g_acCommBuf, replylen, 0,
                                 (struct sockaddr *) &from, sizeof(from));
                             if (res != replylen)
                               {
-                                printf(
+                                OPENER_TRACE_INFO(
                                     "networkhandler: UDP response was not fully sent\n");
                               }
                           }
@@ -287,7 +275,7 @@ Start_NetworkHandler()
                         (struct sockaddr *) &from, &fromlen);
                     if (nReceived_size == 0)
                       {
-                        printf("connection closed by client\n");
+                        OPENER_TRACE_STATE("connection closed by client\n");
                         FD_CLR(fd, &master);
                         /* remove from master set */
                         close(fd); /* close socket */
@@ -295,7 +283,7 @@ Start_NetworkHandler()
                       }
                     if (nReceived_size <= 0)
                       {
-                        perror("networkhandler: error on recv");
+                        OPENER_TRACE_ERR("networkhandler: error on recv: %s", strerror(errno));
                         FD_CLR(fd, &master);
                         /* remove from master set */
                         close(fd); /* close socket */
@@ -343,12 +331,12 @@ IApp_SendUDPData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
 
   if (sentlength < 0)
     {
-      perror("networkhandler: error with sendto in sendUDPData");
+      OPENER_TRACE_ERR("networkhandler: error with sendto in sendUDPData: %s", strerror(errno));
       return EIP_ERROR;
     }
   else if (sentlength != pa_nDataLength)
     {
-      printf("not all data was sent in sendUDPData, sent %d of %d\n",
+      OPENER_TRACE_WARN("not all data was sent in sendUDPData, sent %d of %d\n",
           sentlength, pa_nDataLength);
       return EIP_ERROR;
     }
@@ -375,12 +363,12 @@ handleDataOnTCPSocket(int pa_nSocket)
 
   if (nDataSize == 0)
     {
-      perror("networkhandler: connection closed by client");
+      OPENER_TRACE_ERR("networkhandler: connection closed by client: %s", strerror(errno));
       return EIP_ERROR;
     }
   if (nDataSize < 0)
     {
-      perror("networkhandler: error on recv");
+      OPENER_TRACE_ERR("networkhandler: error on recv: %s", strerror(errno));
       return EIP_ERROR;
     }
 
@@ -389,7 +377,7 @@ handleDataOnTCPSocket(int pa_nSocket)
   /* (NOTE this advances the buffer pointer) */
   if (OPENER_ETHERNET_BUFFER_SIZE < nDataSize)
     { /*TODO can this be handled in a better way?*/
-      printf("too large packet recieved will be ignored\n"); /* this may corrupt the connection ???*/
+      OPENER_TRACE_ERR("too large packet recieved will be ignored\n"); /* this may corrupt the connection ???*/
       return EIP_OK;
     }
 
@@ -397,47 +385,35 @@ handleDataOnTCPSocket(int pa_nSocket)
 
   if (nDataSize == 0) /* got error or connection closed by client */
     {
-      perror("networkhandler: connection closed by client");
+      OPENER_TRACE_ERR("networkhandler: connection closed by client: %s", strerror(errno));
       return EIP_ERROR;
     }
   if (nDataSize < 0)
     {
-      perror("networkhandler: error on recv");
+      OPENER_TRACE_ERR("networkhandler: error on recv: %s", strerror(errno));
       return EIP_ERROR;
     }
 
   nDataSize += 4;
   /*TODO handle partial packets*/
-  if (EIP_DEBUG > EIP_VVERBOSE)
-    {
-      printf("Data received on tcp:\n");
-      dump(g_acCommBuf, nDataSize);
-    }
+  OPENER_TRACE_INFO("Data received on tcp:\n");
 
   nDataSize = handleReceivedExplictData(pa_nSocket, g_acCommBuf, nDataSize,
       &nRemainingBytes);
   if (nRemainingBytes != 0)
     {
-      if (EIP_DEBUG >= EIP_TERSE)
-        printf("Warning: received packet was to long: %d Bytes left!\n",
-            nRemainingBytes);
+      OPENER_TRACE_WARN("Warning: received packet was to long: %d Bytes left!\n",
+          nRemainingBytes);
     }
 
   if (nDataSize > 0)
     {
-      if (EIP_DEBUG >= EIP_VVERBOSE)
-        {
-          printf("reply sent:\n");
-          dump(g_acCommBuf, nDataSize);
-        }
+      OPENER_TRACE_INFO("reply sent:\n");
 
       nDataSent = send(pa_nSocket, (char *) g_acCommBuf, nDataSize, 0);
       if (nDataSent != nDataSize)
         {
-          if (EIP_DEBUG >= EIP_TERSE)
-            {
-              printf("TCP response was not fully sent\n");
-            }
+          OPENER_TRACE_WARN("TCP response was not fully sent\n");
         }
     }
 
@@ -452,11 +428,11 @@ IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr)
   /* create a new UDP socket */
   if ((newfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
     {
-      printf("networkhandler: cannot create UDP socket\n");
+      OPENER_TRACE_ERR("networkhandler: cannot create UDP socket: %s\n", strerror(errno));
       return EIP_ERROR;
     }
-  if (EIP_DEBUG >= EIP_VERBOSE)
-    printf("networkhandler: UDP socket %d\n", newfd);
+
+  OPENER_TRACE_INFO("networkhandler: UDP socket %d\n", newfd);
 
   /* check if it is sending or receiving */
   if (pa_nDirection == CONSUMING)
@@ -464,11 +440,11 @@ IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr)
       if ((bind(newfd, (struct sockaddr *) pa_pstAddr, sizeof(struct sockaddr)))
           == -1)
         {
-          printf("error on bind udp\n");
+          OPENER_TRACE_ERR("error on bind udp: %s\n", strerror(errno));
           return EIP_ERROR;
         }
-      if (EIP_DEBUG >= EIP_VERBOSE)
-        printf("networkhandler: bind UDP socket %d\n", newfd);
+
+      OPENER_TRACE_INFO("networkhandler: bind UDP socket %d\n", newfd);
     }
 
   /* add new fd to the master list */

+ 19 - 9
src/ports/platform-pc/opener_user_conf.h

@@ -11,10 +11,10 @@
 /*! \file
  * \brief OpENer configuration setup
  * 
- * This file containes the general application specific configuration for OpENer.
+ * This file contains the general application specific configuration for OpENer.
  * 
- * Furthermore you have to specifiy platform specific ntework include files.
- * OpENer needs defintions for the follwing data-types 
+ * Furthermore you have to specific platform specific network include files.
+ * OpENer needs definitions for the following data-types
  * and functions:
  *    - struct sockaddr_in
  *    - AF_INET
@@ -28,7 +28,7 @@
 #include <arpa/inet.h>
 
 
-/*! Identiy configuration of the device */
+/*! Identity configuration of the device */
 #define OPENER_DEVICE_VENDOR_ID           1
 #define OPENER_DEVICE_TYPE               12
 #define OPENER_DEVICE_PRODUCT_CODE      200
@@ -37,7 +37,7 @@
 #define OPENER_DEVICE_NAME      "ENetIP EC"
 
 
-/*! The port address to be used for udp multi-cast connections
+/*! The port address to be used for UDP multi-cast connections
  */ 
 #define OPENER_UDP_MULTICAST_PORT   2222
 
@@ -47,9 +47,9 @@
 #define OPENER_NUMBER_OF_SUPPORTED_CONNECTIONS 10
 
 
-/*! The number of bytes used for the ethernet message buffer.
- *  This buffer size will be used for any recieved message.
- *  The same buffer is used for the replied eplicit message.
+/*! The number of bytes used for the Ethernet message buffer.
+ *  This buffer size will be used for any received message.
+ *  The same buffer is used for the replied explicit message.
  */ 
 #define OPENER_ETHERNET_BUFFER_SIZE 512
 
@@ -65,7 +65,7 @@
  */ 
 #define OPENER_NUMBER_OF_SUPPORTED_SESSIONS 4
 
-/*! The time in ms of the timmer used in this implementations
+/*! The time in ms of the timer used in this implementations
  */ 
 #define OPENER_TIMER_TICK 10 
 
@@ -74,4 +74,14 @@
  */ 
 #define OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER 1
 
+#ifdef OPENER_WITH_TRACES
+/* If we have tracing enabled provide print tracing macro */
+#include <stdio.h>
+
+#define LOG_TRACE(args...)  fprintf(stderr,args)
+
+/*#define PRINT_TRACE(args...)  fprintf(stderr,args);*/
+
+#endif
+
 #endif /*OPENER_USER_CONF_H_*/

+ 0 - 46
src/ports/platform-pc/stubs.c

@@ -1,46 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009, Rockwell Automation, Inc.
- * All rights reserved. 
- *
- * Contributors:
- *     <date>: <author>, <author email> - changes
- ******************************************************************************/
-#include <string.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <assert.h>
-
-static char dumpbuf[256];
-
-void dump(unsigned char *p, int size)
-  {
-    int i;
-    char *b;
-
-    while (size > 0)
-      {
-        b = dumpbuf;
-        /* b += sprintf(b,"%08x: ",(int)p);*/
-        for (i = 0; i < 16; i++)
-          {
-            if (i < size)
-              b += sprintf(b, "%02x ", p[i]);
-            else
-              b += sprintf(b, "   ");
-          }
-        b += sprintf(b, " |");
-        for (i = 0; i < 16; i++)
-          {
-            if (i < size)
-              {
-                if (' ' <= p[i] && p[i] < 0x7f)
-                  b += sprintf(b, "%c", p[i]);
-                else
-                  b += sprintf(b, ".");
-              }
-          }
-        p += 16;
-        size -= 16;
-        printf("%s\n", dumpbuf);
-      }
-  }

+ 100 - 0
src/trace.h

@@ -0,0 +1,100 @@
+/*******************************************************************************
+ * Copyright (c) 2009, Rockwell Automation, Inc.
+ * All rights reserved.
+ *
+ * Contributors:
+ *     <date>: <author>, <author email> - changes
+ ******************************************************************************/
+#ifndef TRACE_H_
+#define TRACE_H_
+
+#include <opener_user_conf.h>
+
+/*!\file
+ * \brief Tracing infrastructure for OpENer
+ */
+
+#ifdef OPENER_WITH_TRACES
+
+/*! Enable tracing of error messages. This is the default if no trace level is given*/
+#define OPENER_TRACE_LEVEL_ERROR    0x01
+
+/*! Enable tracing of warning messages*/
+#define OPENER_TRACE_LEVEL_WARNING  0x02
+
+/*! Enable tracing of state messages*/
+#define OPENER_TRACE_LEVEL_STATE    0x04
+
+/*! Enable tracing of info messages*/
+#define OPENER_TRACE_LEVEL_INFO     0x08
+
+#ifndef OPENER_TRACE_LEVEL
+#warning OPENER_TRACE_LEVEL was not defined setting it to OPENER_TRACE_LEVEL_ERROR
+#define OPENER_TRACE_LEVEL OPENER_TRACE_LEVEL_ERROR
+#endif
+
+#define OPENER_TRACE_ENABLED      /* can be used for conditional code compilation */
+
+/*#ifdef OPENER_EIP_TRACE_TIME
+ //
+ //#define OPENER_TRACE_TIME_ENABLED // can be used for conditional code compilation
+ //
+ //extern struct timeval trace_now;
+ //
+ //#define TRACE_ERR(args...)   do { if ((0x01 & trace_level) && trace_stream) \
+//        { gettimeofday(&trace_now, NULL); fprintf(stderr,"[%09lu:%06lu]: ", trace_now.tv_sec, trace_now.tv_usec);  \
+//          fprintf(stderr,args); }} while(0)
+ //#define TRACE_WARN(args...)  do { if ((0x02 & trace_level) && trace_stream) \
+//        { gettimeofday(&trace_now, NULL); fprintf(trace_stream,"[%09lu:%06lu]: ", trace_now.tv_sec, trace_now.tv_usec);  \
+//          fprintf(trace_stream,args); }} while(0)
+ //#define TRACE_STATE(args...) do { if ((0x04 & trace_level) && trace_stream) \
+//        { gettimeofday(&trace_now, NULL); fprintf(trace_stream,"[%09lu:%06lu]: ", trace_now.tv_sec, trace_now.tv_usec);  \
+//          fprintf(trace_stream,args); }} while(0)
+ //#define TRACE_PROTO(args...) do { if ((0x08 & trace_level) && trace_stream) \
+//        { gettimeofday(&trace_now, NULL); fprintf(trace_stream,"[%09lu:%06lu]: ", trace_now.tv_sec, trace_now.tv_usec);  \
+//          fprintf(trace_stream,args); }} while(0)
+ //#define TRACE_INFO(args...)  do { if ((0x10 & trace_level) && trace_stream) \
+//        { gettimeofday(&trace_now, NULL); fprintf(trace_stream,"[%09lu:%06lu]: ", trace_now.tv_sec, trace_now.tv_usec);  \
+//          fprintf(trace_stream,args); }} while(0)
+ //#else
+ */
+
+/*! Trace error messages.
+ *  In order to activate this trace level set the OPENER_TRACE_LEVEL_ERROR flag
+ *  in OPENER_TRACE_LEVEL.
+ */
+#define OPENER_TRACE_ERR(args...)   do { if (OPENER_TRACE_LEVEL_ERROR & OPENER_TRACE_LEVEL) \
+      LOG_TRACE(args); } while(0)
+
+/*! Trace warning messages.
+ *  In order to activate this trace level set the OPENER_TRACE_LEVEL_WARNING flag
+ *  in OPENER_TRACE_LEVEL.
+ */
+#define OPENER_TRACE_WARN(args...)  do { if (OPENER_TRACE_LEVEL_WARNING & OPENER_TRACE_LEVEL) \
+      LOG_TRACE(args); } while(0)
+
+/*! Trace state messages.
+ *  In order to activate this trace level set the OPENER_TRACE_LEVEL_STATE flag
+ *  in OPENER_TRACE_LEVEL.
+ */
+#define OPENER_TRACE_STATE(args...) do { if (OPENER_TRACE_LEVEL_STATE & OPENER_TRACE_LEVEL) \
+      LOG_TRACE(args); } while(0)
+
+/*! Trace information messages.
+ *  In order to activate this trace level set the OPENER_TRACE_LEVEL_INFO flag
+ *  in OPENER_TRACE_LEVEL.
+ */
+#define OPENER_TRACE_INFO(args...)  do { if (OPENER_TRACE_LEVEL_INFO & OPENER_TRACE_LEVEL) \
+      LOG_TRACE(args); } while(0)
+
+#else
+/* define the tracing macros empty in order to save space */
+
+#define OPENER_TRACE_ERR(args...)
+#define OPENER_TRACE_WARN(args...)
+#define OPENER_TRACE_STATE(args...)
+#define OPENER_TRACE_INFO(args...)
+#endif
+/* TRACING *******************************************************************/
+
+#endif /*TRACE_H_*/

+ 10 - 18
src/typedefs.h

@@ -33,7 +33,7 @@
 #define EIP_BOOL8	bool
 
 /*! Constant idenfying if a socket desciptor is invalid
- */ 
+ */
 #define EIP_INVALID_SOCKET      -1
 
 /*
@@ -56,20 +56,16 @@
  */
 
 typedef enum
-  {
-    EIP_OK = 0,
-    EIP_OK_SEND = 1,
-    EIP_ERROR = -1
-  } EIP_STATUS;
-
+{
+  EIP_OK = 0, EIP_OK_SEND = 1, EIP_ERROR = -1
+} EIP_STATUS;
 
 #ifndef __cplusplus
 /*! If we don't have C++ define a C++ -like "bool"*/
 typedef enum
-  {
-    false=0,
-    true=1
-  }bool;
+{
+  false = 0, true = 1
+} bool;
 
 #endif
 
@@ -80,9 +76,9 @@ typedef enum
  example:
 
  typedef enum { A, B, C, FOO_PACKED_SIZE=ENUM_UINT16} PACKED FOO;		 this forces the field to be 16 bits long, even though the defined values could be contained in 8 bits
-										 the definition FOO_PACKED_SIZE is a dummy, but it forces the minimum size
-*/
-  
+ the definition FOO_PACKED_SIZE is a dummy, but it forces the minimum size
+ */
+
 /* TODO -- find some portable way of dealing with packed structs and typed enums */
 #ifdef __GNUC__
 #define PACKED __attribute__((packed))
@@ -93,8 +89,4 @@ typedef enum
 
 #endif
 
-#define EIP_SILENT	0	/* print nothing */
-#define EIP_TERSE	1	/* print signifcant events and error messages */
-#define EIP_VERBOSE	2	/* print a running commentary on many events */
-#define EIP_VVERBOSE	3	/* print a running commentary plus dumps of messages */
 #endif /*TYPEDEFS_H_*/

Деякі файли не було показано, через те що забагато файлів було змінено