瀏覽代碼

Closes #39 Changes to Google code style, updates coding rules

capxilinx 10 年之前
父節點
當前提交
f02383883f
共有 58 個文件被更改,包括 6880 次插入7295 次删除
  1. 57 0
      .clang-format
  2. 二進制
      source/doc/coding_rules/opener_coding_rules.pdf
  3. 151 79
      source/doc/coding_rules/src/opener_coding_rules.tex
  4. 2 2
      source/opener.doxyfile
  5. 304 357
      source/src/cip/appcontype.c
  6. 27 32
      source/src/cip/appcontype.h
  7. 145 173
      source/src/cip/cipassembly.c
  8. 19 15
      source/src/cip/cipassembly.h
  9. 41 45
      source/src/cip/cipclass3connection.c
  10. 12 8
      source/src/cip/cipclass3connection.h
  11. 592 640
      source/src/cip/cipcommon.c
  12. 27 22
      source/src/cip/cipcommon.h
  13. 477 491
      source/src/cip/cipconnectionmanager.c
  14. 211 191
      source/src/cip/cipconnectionmanager.h
  15. 48 70
      source/src/cip/ciperror.h
  16. 39 44
      source/src/cip/cipethernetlink.c
  17. 5 6
      source/src/cip/cipethernetlink.h
  18. 101 109
      source/src/cip/cipidentity.c
  19. 37 25
      source/src/cip/cipidentity.h
  20. 660 720
      source/src/cip/cipioconnection.c
  21. 17 20
      source/src/cip/cipioconnection.h
  22. 187 206
      source/src/cip/cipmessagerouter.c
  23. 20 22
      source/src/cip/cipmessagerouter.h
  24. 230 247
      source/src/cip/ciptcpipinterface.c
  25. 23 17
      source/src/cip/ciptcpipinterface.h
  26. 352 348
      source/src/cip/ciptypes.h
  27. 269 280
      source/src/enet_encap/cpf.c
  28. 59 59
      source/src/enet_encap/cpf.h
  29. 475 560
      source/src/enet_encap/encap.c
  30. 44 44
      source/src/enet_encap/encap.h
  31. 118 150
      source/src/enet_encap/endianconv.c
  32. 47 42
      source/src/enet_encap/endianconv.h
  33. 565 475
      source/src/opener_api.h
  34. 51 62
      source/src/ports/LM3S8962/basiccip.c
  35. 63 68
      source/src/ports/LM3S8962/flashmgr.c
  36. 177 215
      source/src/ports/LM3S8962/networkhandler.c
  37. 1 2
      source/src/ports/LM3S8962/networkhandler.h
  38. 66 87
      source/src/ports/LM3S8962/sample_application/main.c
  39. 6 18
      source/src/ports/LM3S8962/sample_application/opener_user_conf.h
  40. 46 56
      source/src/ports/LM3S8962/stubs.c
  41. 43 55
      source/src/ports/POSIX/main.c
  42. 359 426
      source/src/ports/POSIX/networkhandler.c
  43. 3 4
      source/src/ports/POSIX/networkhandler.h
  44. 9 20
      source/src/ports/POSIX/sample_application/opener_user_conf.h
  45. 71 89
      source/src/ports/POSIX/sample_application/sampleapplication.c
  46. 43 55
      source/src/ports/WIN32/main.c
  47. 347 419
      source/src/ports/WIN32/networkhandler.c
  48. 3 4
      source/src/ports/WIN32/networkhandler.h
  49. 6 17
      source/src/ports/WIN32/sample_application/opener_user_conf.h
  50. 64 82
      source/src/ports/WIN32/sample_application/sampleapplication.c
  51. 44 31
      source/src/trace.h
  52. 69 33
      source/src/typedefs.h
  53. 4 5
      source/src/utils/random.c
  54. 10 11
      source/src/utils/random.h
  55. 11 14
      source/src/utils/xorshiftrandom.c
  56. 13 13
      source/src/utils/xorshiftrandom.h
  57. 3 3
      source/tests/utils/randomTests.cpp
  58. 7 7
      source/tests/utils/xorshiftrandomtests.cpp

+ 57 - 0
.clang-format

@@ -0,0 +1,57 @@
+---
+Language:        Cpp
+# BasedOnStyle:  Google
+AccessModifierOffset: -1
+ConstructorInitializerIndentWidth: 4
+AlignEscapedNewlinesLeft: true
+AlignTrailingComments: true
+AllowAllParametersOfDeclarationOnNextLine: true
+AllowShortBlocksOnASingleLine: false
+AllowShortIfStatementsOnASingleLine: true
+AllowShortLoopsOnASingleLine: true
+AllowShortFunctionsOnASingleLine: All
+AlwaysBreakTemplateDeclarations: true
+AlwaysBreakBeforeMultilineStrings: true
+BreakBeforeBinaryOperators: false
+BreakBeforeTernaryOperators: true
+BreakConstructorInitializersBeforeComma: false
+BinPackParameters: true
+ColumnLimit:     80
+ConstructorInitializerAllOnOneLineOrOnePerLine: true
+DerivePointerAlignment: true
+ExperimentalAutoDetectBinPacking: false
+IndentCaseLabels: true
+IndentWrappedFunctionNames: false
+IndentFunctionDeclarationAfterType: false
+MaxEmptyLinesToKeep: 1
+KeepEmptyLinesAtTheStartOfBlocks: false
+NamespaceIndentation: None
+ObjCSpaceAfterProperty: false
+ObjCSpaceBeforeProtocolList: false
+PenaltyBreakBeforeFirstCallParameter: 1
+PenaltyBreakComment: 300
+PenaltyBreakString: 1000
+PenaltyBreakFirstLessLess: 120
+PenaltyExcessCharacter: 1000000
+PenaltyReturnTypeOnItsOwnLine: 200
+PointerAlignment: Left
+SpacesBeforeTrailingComments: 2
+Cpp11BracedListStyle: true
+Standard:        Auto
+IndentWidth:     2
+TabWidth:        8
+UseTab:          Never
+BreakBeforeBraces: Attach
+SpacesInParentheses: false
+SpacesInAngles:  false
+SpaceInEmptyParentheses: false
+SpacesInCStyleCastParentheses: false
+SpacesInContainerLiterals: true
+SpaceBeforeAssignmentOperators: true
+ContinuationIndentWidth: 4
+CommentPragmas:  '^ IWYU pragma:'
+ForEachMacros:   [ foreach, Q_FOREACH, BOOST_FOREACH ]
+SpaceBeforeParens: ControlStatements
+DisableFormat:   false
+...
+

二進制
source/doc/coding_rules/opener_coding_rules.pdf


+ 151 - 79
source/doc/coding_rules/src/opener_coding_rules.tex

@@ -1,5 +1,6 @@
 \documentclass[final,a4paper,10pt, oneside]{article}
 \documentclass[final,a4paper,10pt, oneside]{article}
-\usepackage[latin1]{inputenc}
+\usepackage[latin1]{inputenc}
+\usepackage[T1]{fontenc}
 
 
 \usepackage{a4wide} 
 \usepackage{a4wide} 
 
 
@@ -8,9 +9,9 @@
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
 
 
 
-\title{Coding Rules for\\ \emph{OpENer} --- Open Source EtherNet/IP$^{TM}$ Adapter Stack\\\large Version 1.0}
-\author{Alois Zoitl\thanks{zoitl\@@acin.tuwien.ac.at}}
-\date{2009-10-29}
+\title{Coding Rules for\\ \emph{OpENer} --- Open Source EtherNet/IP$^{TM}$ Adapter Stack\\\large Version 2.0}
+\author{Martin Melik Merkumians\thanks{melik-merkumians\@@acin.tuwien.ac.at}}
+\date{2015-11-15}
 
 
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -40,7 +41,10 @@
 \lstset{language=C++}
 \lstset{language=C++}
 \lstset{commentstyle=\textit}
 \lstset{commentstyle=\textit}
 \lstset{linewidth=\textwidth}
 \lstset{linewidth=\textwidth}
-\lstset{basicstyle=\scriptsize}
+\lstset{basicstyle=\scriptsize}
+
+\usepackage{fancyref}
+\usepackage{hyperref}
 
 
 
 
 
 
@@ -48,15 +52,32 @@
 
 
 \maketitle
 \maketitle
 
 
-\tableofcontents
+\tableofcontents
+
+\section{Introduction}
+This document describes the coding rules, which has to be used in the OpENer project. These rules are mainly the Google C++ style rules, with some extensions specific to C and the OpENer project. If something is not covered by the rules given in this document, please check the official Google C++ style guide, available at \url{http://google.github.io/styleguide/cppguide.html}. Additional code style examples can be found at \url{https://gist.github.com/davidzchen/9187878}.
+
+As the OpENer code style aims to be as close as possible to the established Google C++ code style, please file an issue if anything in this guide contradicts the Google C++ code style.
 
 
 \section{Comments}
 \section{Comments}
-A sufficient amount of comments has to be written. There are never too many comments, whereas invalid comments are worse than none --- thus
-invalid comments have to be removed from the source code. Comments have to be written in English. 
-
-\begin{quote}
-Comments for function, structure, \ldots~ definitions have to follow the conventions of \emph{Doxygen} to allow the automated generation of documentation for the sourcecode. 
-\end{quote}
+A sufficient amount of comments has to be written. There are never too many comments, whereas invalid comments are worse than none --- thus invalid comments have to be removed from the source code. Comments have to be written in English. 
+
+
+Comments for function, structure, \ldots~ definitions have to follow the conventions of \emph{Doxygen} to allow the automated generation of documentation for the source code. Hereby Java-style Doxygen comments shall be used. Doxygen comments shall therefore start with slash and two starts, and use the @ symbol to indicate Doxygen keywords. For enums, variables, and strucutres inline documentation with \emph{/**<} shall be used. Autobrief behavior shall not be assumed for Doxygen comments. See the example below.
+\begin{lstlisting}[frame=trbl]{}
+/** @brief function, structure, enum, etc. to comment
+ *
+ *  Detailed explanation, spanning multiple lines if needed.
+ *  @param parameter1 Parameter1 description
+ *  @return Return value description
+ */
+int foo(char bar) {
+    ...
+}
+
+const int g_kFooBar = 1; /**< Global constant which needs documentation */
+
+\end{lstlisting}
 
 
 Comments have to be meaningful, to describe to program and to be up to date.
 Comments have to be meaningful, to describe to program and to be up to date.
 
 
@@ -74,7 +95,7 @@ Every source-file must contain a fileheader as follows:
 \end{lstlisting}
 \end{lstlisting}
 Each author needs to explain his changes in the code. 
 Each author needs to explain his changes in the code. 
 \subsection{Revision History}
 \subsection{Revision History}
-%To track changes in the source files every new file version must contain it's version information in the followoing form:
+%To track changes in the source files every new file version must contain it's version information in the following form:
 %\begin{center}
 %\begin{center}
 %  @version: $<$date$>$/$<$author$>$: $<$description$>$
 %  @version: $<$date$>$/$<$author$>$: $<$description$>$
 %\end{center}
 %\end{center}
@@ -89,89 +110,140 @@ The following Keywords should be used in the source code to mark special comment
 \end{itemize}
 \end{itemize}
 
 
 \section{Datatypes}
 \section{Datatypes}
-The following table contains the definitions of important standard datatypes. This is done to ensure a machine independant defintion of the bit-width of the standard data types. For \emph{OpENer}-development these definitions are in the file: \verb|src/typedefs.h|
+\Fref{tab:datatypes} contains the definitions of important standard datatypes. This is done to ensure a machine independant defintion of the bit-width of the standard data types. For \emph{OpENer}-development these definitions are in the file: \verb|src/typedefs.h|
 
 
-\begin{table}[h]
-	\centering
+\begin{table}[h] 
+\caption{Data types used in OpENer} \label{tab:datatypes}
+	\centering 
 		\begin{tabular}{lll}
 		\begin{tabular}{lll}
 			defined data type	& bit-width / description & used C-datatype \\
 			defined data type	& bit-width / description & used C-datatype \\
 			\hline
 			\hline
-			EIP\_BYTE	&	8 bit unsigned	&   char\\
-			EIP\_INT8	&	8 bit signed	&	signed char	 \\
-			EIP\_INT16	&	16 bit signed	&	short	 \\
-			EIP\_INT32	&	32 bit signed	&	long	 \\
-			EIP\_UINT8	&	8 bit unsigned	&	char	 \\
-			EIP\_UINT16	&	16 bit unsigned	&	unsigned short	 \\
-			EIP\_UINT32	&	32 bit unsigned	&	unsigned long	 \\
-			EIP\_FLOAT	&	single precission IEEE float (32 bit)&	float	 \\
-			EIP\_DFLOAT	&	double precission IEEE float (64 bit) &	double	\\
-			EIP\_BOOL8	&	byte variable as boolean value	&	bool	 \\
+			EipByte	&	8 bit unsigned	&   uint8\_t\\
+			EipInt8	&	8 bit signed	&	int8\_t	 \\
+			EipInt16	&	16 bit signed	&	int16\_t	 \\
+			EipInt32	&	32 bit signed	&	int32\_t	 \\
+			EipInt64 & 64 bit signed & int64\_t \\
+			EipUint8	&	8 bit unsigned	&	uint8\_t	 \\
+			EipUint16	&	16 bit unsigned	&	uint16\_t	 \\
+			EipUint32	&	32 bit unsigned	&	uint32\_t	 \\
+			EipUint64 & 64 bit unsigned & uint64\_t \\
+			EipFloat	&	single precission IEEE float (32 bit) &	float	 \\
+			EipDfloat	&	double precission IEEE float (64 bit) &	double	\\
+			EipBool8	&	byte variable as boolean value	&	unit8\_t	 \\
+			
+			CipOctet & unspecified type & uint8\_t \\
+			CipBool & byte variable as boolean value & uint8\_t \\
+			CipByte & 8 bit unsigned & uint8\_t \\
+			CipWord & 16 bit unsigned & uint16\_t \\
+			CipDword & 32 bit unsigned & uint32\_t \\
+			CipUsint & 8 bit unsigned & uint8\_t \\
+			CipUint & 16 bit unsigned & uint16\_t \\
+			CipUdint & 32 bit unsigned & uint32\_t \\
+			CipSint & 8 bit signed & int8\_t \\
+			CipInt & 16 bit signed & int16\_t \\
+			CipDint & 32 bit signed & int32\_t \\
+			CipReal & single precission IEEE float (32 bit) & float \\
+			CipLreal & double precission IEEE float (64 bit) & double \\
+
+			CipLint & 64 bit signed & int64\_t \\
+			CipUlint & 64 bit unsigned & uint64\_t \\
+			CipLword & 64 bit unsigned & uint64\_t
 		\end{tabular}
 		\end{tabular}
-\end{table}
+\end{table} 
 
 
-These data types shall only be used when the bit size is important for the correct operation of the code. If not we advice to use the type \verb|int| or \verb|unsigned int| for most variables, as this is the most efficent data type and can lead on some platforms (e.g., ARM) even to smaller code size.
+These data types shall only be used when the bit size is important for the correct operation of the code, whereby Eip-prefixed data types shall be used for communication functions, and Cip-prefixed data types shall be used for CIP related functions and objects. If not we advice to use the type \verb|int| or \verb|unsigned int| for most variables, as this is the most efficient data type and can lead on some platforms (e.g., ARM) even to smaller code size.
 
 
 \section{Naming of Identifiers}
 \section{Naming of Identifiers}
 Every identifier has to be named in English. The first character of an identifier must not contain underscores (there are some compiler directives which start with underscores and this could lead to conflicts). Mixed case letters has to be used and the appropriate prefixes have to be inserted where necessary.
 Every identifier has to be named in English. The first character of an identifier must not contain underscores (there are some compiler directives which start with underscores and this could lead to conflicts). Mixed case letters has to be used and the appropriate prefixes have to be inserted where necessary.
 
 
-
+\subsection{Pre- \& Postfixes}
+The following prefixes have to be applied to identifiers:\\
+\begin{itemize}
+	\item \emph{"g\_"} shall be prefixed for global variables.
+	\item \emph{"\_"} shall be postfixed for member variables. These are usually CIP object variables with file-global scope.
+\end{itemize}
+
 \subsection{Variables}
 \subsection{Variables}
-Variables have to be named self explanatory. The names have to be provided with the appropriate prefixes and they have to start with an uppercase letter. In case of combining prefixes, the use of ranges, arrays, pointer, enumerations, or structures is at first, followed by basic data types or object prefixes. The only exception are loop variables (thereby the use of i, j, k is allowed). Only one variable declaration per line is allowed. Pointer operators at the declaration have to be located in front of the variable (not after the type identifier). If possible initializations have to be done directly at the declaration.
-
-\subsection{Prefixes}
-The following prefixes have to be applied to identifiers:\\
-\begin{tabular}{ll}
-&\\
-\textbf{Type Definitions} & \textbf{Ranges} \\
-\begin{tabular}{ll}
-S& for structures \\
-E& for enum\\
-T\_& for types (e.g. typedef in C++)\\ 
-\end{tabular} &
-
-\begin{tabular}{ll}
-m\_ & for member variables of classes\\	
-g\_ & for global variables\\
-s\_ & for static variables\\
-pa\_ & for function parameters\\
-\end{tabular}	\vspace{1mm}\\
-\textbf{Variable Types} & \textbf{Basic Data Types} \\
-\begin{tabular}{ll}
-a & for arrays\\
-p & for pointers\\ 	
-e & for enumerations\\
-st & for structures\\
-\end{tabular}	&
-
-\begin{tabular}{ll}
-c & for characters \\
-b & for booleans\\
-n & for integers\\	
-f & for all floating point numbers
-\end{tabular} \vspace{1mm}\\
-\end{tabular}
-
-\paragraph{Examples}
+Variables have to be named self explanatory. The names have to be provided with the appropriate pre- or postfix and shall be all lowercase letters, and if a name consists of more than one word underscores shall be used for separating these words. The only exception are loop variables (thereby the use of i, j, k is allowed). Only one variable declaration per line is allowed. Pointer operators at the declaration have to be located in front of the variable (not after the type identifier). If possible initializations have to be done directly at the declaration.
+
+\paragraph{Examples}
 \begin{quote}
 \begin{quote}
-\verb|struct SCIPObject;|\\
-\verb|int nNumber;|\\
-\verb|int *pnNumber = &nNumber;|\\
-\verb|char cKey;|\\
-\verb|bool g_bIsInitialized;|\\
-\verb|float m_fPi = 3.1415;|\\
-\verb|int anNumbers[10];|\\
+\begin{lstlisting}
+int i;
+int local_variable;
+CipBool boolean_flag_in_cip_object_;
+\end{lstlisting}
 \end{quote}
 \end{quote}
-
-
-\subsection{Constants}
-Constants have to be named with block letters (only upper case letters). If a name consists of more words, underscores for separation are
-allowed.  Avoid the using ``magic numbers'' 
-(e.g. \verb|if (x == 3){...}|). Instead use constants.
+
+\subsection{Constants}
+The preferred way to declare constants is to define them as\emph{const} data types, if this is not possible constants shall be defined as pre-processor statements, via \emph{\#define}.
+If constants are defined as C constants the name of the constant shall start with \emph{k}, followed by the constant name in Pascal case.
+If a constant is defined as a pre-processor statement the constant name shall be all upper case, separating multiple words with underscored.
+Avoid the using ``magic numbers'' (e.g. \verb|if (x == 3){...}|). Instead use constants.
+
+\paragraph{Examples}
+\begin{quote}
+\begin{lstlisting}
+static int g_global_variable;
+static const int g_kAGlobalConstant = 73:
+const int kAnImportantConstant = 42;
+#define DO_NOT_DO_THIS_IF_IT_IS_NOT_NECESSARY bad
+\end{lstlisting}
+\end{quote}
+
+\subsection{Functions}
+Functions names shall be Pascal cased, function parameters shall be named like variables. The parameter list shall adhere to the following rules:
+\begin{itemize}
+	\item Input parameters shall come first
+	\item Input parameters shall be const
+	\item Output parameters shall be last
+\end{itemize}
+
+\paragraph{Examples}
+\begin{quote}
+\begin{lstlisting}
+int FooBar(const int foo, const char* const bar, double* additional_return_value)
+\end{lstlisting}
+\end{quote}
+
+\subsection{Structs}
+The default case for structs shall be, that they are defined as anonymous structs, giving them a type name via the \emph{typedef} keyword.  Struct names shall be pascal cased. If a struct type is needed, before a typedef alias can be created (usually inside the same struct), the struct name shall be repeated in the struct type name, following the conventions for variable names, with all lowercase and words separated with underscores.
+
+The element names inside the struct are following the normal conventions for their types.
+
+\paragraph{Examples}
+\begin{quote}
+\begin{lstlisting}
+typedef struct {
+    int foo;
+    char bar;
+} TheDefaultCase;
+
+typedef the_excpetion {
+    struct the_exection *needed_the_struct_definition_already_here;
+    char other_elements;
+} TheException;
+\end{lstlisting}
+\end{quote}
+
+\subsection{Enums}
+Enums shall be defined anonymous and typedef'ed to a type name. As the values inside an enum are constant, the naming scheme of constants apply for enum members. As Enums do not define their own namespace, the enum type name shall be added between the initial \emph{k} and the constant name.
+
+\paragraph{Examples}
+\begin{quote}
+\begin{lstlisting}
+typedef enum {
+    kImportantEnumConstant1 = 0,
+    kImportantEnumConstant2 = 1
+} ImportantEnum;
+\end{lstlisting}
+\end{quote}
+
 
 
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Code Formatting}
 \section{Code Formatting}
-In order to have consitent code formating the rules of GNU shall apply. When using Eclipse as development environment this format is alread set as preset. By pressing \verb|<ctrl><shift>f| the formater will format the code according to these rules.
+In order to have consistent code formating the Google C++ coding style rules shall apply. When using Eclipse as development environment the coding format xml file is available at \url{https://github.com/google/styleguide}. By pressing \verb|<ctrl><shift>f| the formatter will format the code according to these rules.
 
 
 
 
 \end{document}
 \end{document}

+ 2 - 2
source/opener.doxyfile

@@ -68,7 +68,7 @@ OUTPUT_DIRECTORY       = doc/api_doc
 # performance problems for the file system.
 # performance problems for the file system.
 # The default value is: NO.
 # The default value is: NO.
 
 
-CREATE_SUBDIRS         = NO
+CREATE_SUBDIRS         = YES
 
 
 # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
 # If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
 # characters to appear in the names of generated files. If set to NO, non-ASCII
 # characters to appear in the names of generated files. If set to NO, non-ASCII
@@ -1012,7 +1012,7 @@ CLANG_OPTIONS          =
 # classes, structs, unions or interfaces.
 # classes, structs, unions or interfaces.
 # The default value is: YES.
 # The default value is: YES.
 
 
-ALPHABETICAL_INDEX     = NO
+ALPHABETICAL_INDEX     = YES
 
 
 # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
 # The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
 # which the alphabetical index list will be split.
 # which the alphabetical index list will be split.

+ 304 - 357
source/src/cip/appcontype.c

@@ -8,406 +8,353 @@
 #include "opener_api.h"
 #include "opener_api.h"
 #include <string.h>
 #include <string.h>
 
 
-/* external globals needed from connectionmanager.c */
-extern S_CIP_ConnectionObject *g_pstActiveConnectionList;
-
-typedef struct
-{
-  unsigned int m_unOutputAssembly; /*< the O-to-T point for the connection */
-  unsigned int m_unInputAssembly; /*< the T-to-O point for the connection */
-  unsigned int m_unConfigAssembly; /*< the config point for the connection */
-  S_CIP_ConnectionObject m_stConnectionData; /*< the connection data, only one connection is allowed per O-to-T point*/
-} S_ExclusiveOwnerConnection;
-
-typedef struct
-{
-  unsigned int m_unOutputAssembly; /*< the O-to-T point for the connection */
-  unsigned int m_unInputAssembly; /*< the T-to-O point for the connection */
-  unsigned int m_unConfigAssembly; /*< the config point for the connection */
-  S_CIP_ConnectionObject m_astConnectionData[OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH]; /*< the connection data */
-} S_InputOnlyConnection;
-
-typedef struct
-{
-  unsigned int m_unOutputAssembly; /*< the O-to-T point for the connection */
-  unsigned int m_unInputAssembly; /*< the T-to-O point for the connection */
-  unsigned int m_unConfigAssembly; /*< the config point for the connection */
-  S_CIP_ConnectionObject m_astConnectionData[OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH]; /*< the connection data */
-} S_ListenOnlyConnection;
-
-S_ExclusiveOwnerConnection g_astExlusiveOwnerConnections[OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS];
-
-S_InputOnlyConnection g_astInputOnlyConnections[OPENER_CIP_NUM_INPUT_ONLY_CONNS];
-
-S_ListenOnlyConnection g_astListenOnlyConnections[OPENER_CIP_NUM_LISTEN_ONLY_CONNS];
-
-S_CIP_ConnectionObject *
-getExclusiveOwnerConnection(S_CIP_ConnectionObject * pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError);
-S_CIP_ConnectionObject *
-getInputOnlyConnection(S_CIP_ConnectionObject * pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError);
-S_CIP_ConnectionObject *
-getListenOnlyConnection(S_CIP_ConnectionObject * pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError);
-
-void
-configureExclusiveOwnerConnectionPoint(unsigned int pa_unConnNum,
-    unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly,
-    unsigned int pa_unConfigAssembly)
-{
-  if (OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS > pa_unConnNum)
-    {
-      g_astExlusiveOwnerConnections[pa_unConnNum].m_unOutputAssembly =
-          pa_unOutputAssembly;
-      g_astExlusiveOwnerConnections[pa_unConnNum].m_unInputAssembly =
-          pa_unInputAssembly;
-      g_astExlusiveOwnerConnections[pa_unConnNum].m_unConfigAssembly =
-          pa_unConfigAssembly;
-    }
+/** @brief External globals needed from connectionmanager.c */
+extern ConnectionObject *g_active_connection_list;
+
+typedef struct {
+  unsigned int output_assembly; /**< the O-to-T point for the connection */
+  unsigned int input_assembly; /**< the T-to-O point for the connection */
+  unsigned int config_assembly; /**< the config point for the connection */
+  ConnectionObject connection_data; /**< the connection data, only one connection is allowed per O-to-T point*/
+} ExclusiveOwnerConnection;
+
+typedef struct {
+  unsigned int output_assembly; /**< the O-to-T point for the connection */
+  unsigned int input_assembly; /**< the T-to-O point for the connection */
+  unsigned int config_assembly; /**< the config point for the connection */
+  ConnectionObject connection_data[OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH]; /*< the connection data */
+} InputOnlyConnection;
+
+typedef struct {
+  unsigned int output_assembly; /**< the O-to-T point for the connection */
+  unsigned int input_assembly; /**< the T-to-O point for the connection */
+  unsigned int config_assembly; /**< the config point for the connection */
+  ConnectionObject connection_data[OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH]; /**< the connection data */
+} ListenOnlyConnection;
+
+ExclusiveOwnerConnection g_exlusive_owner_connections[OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS];
+
+InputOnlyConnection g_input_only_connections[OPENER_CIP_NUM_INPUT_ONLY_CONNS];
+
+ListenOnlyConnection g_listen_only_connections[OPENER_CIP_NUM_LISTEN_ONLY_CONNS];
+
+ConnectionObject *GetExclusiveOwnerConnection(
+    ConnectionObject *connection_object, EipUint16 *extended_error);
+
+ConnectionObject *GetInputOnlyConnection(ConnectionObject *connection_object,
+                                         EipUint16 *extended_error);
+
+ConnectionObject *GetListenOnlyConnection(ConnectionObject *connection_object,
+                                          EipUint16 *extended_error);
+
+void ConfigureExclusiveOwnerConnectionPoint(unsigned int connection_number,
+                                            unsigned int output_assembly,
+                                            unsigned int input_assembly,
+                                            unsigned int config_assembly) {
+  if (OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS > connection_number) {
+    g_exlusive_owner_connections[connection_number].output_assembly =
+        output_assembly;
+    g_exlusive_owner_connections[connection_number].input_assembly =
+        input_assembly;
+    g_exlusive_owner_connections[connection_number].config_assembly =
+        config_assembly;
+  }
 }
 }
 
 
-void
-configureInputOnlyConnectionPoint(unsigned int pa_unConnNum,
-    unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly,
-    unsigned int pa_unConfigAssembly)
-{
-  if (OPENER_CIP_NUM_INPUT_ONLY_CONNS > pa_unConnNum)
-    {
-      g_astInputOnlyConnections[pa_unConnNum].m_unOutputAssembly =
-          pa_unOutputAssembly;
-      g_astInputOnlyConnections[pa_unConnNum].m_unInputAssembly =
-          pa_unInputAssembly;
-      g_astInputOnlyConnections[pa_unConnNum].m_unConfigAssembly =
-          pa_unConfigAssembly;
-    }
+void ConfigureInputOnlyConnectionPoint(unsigned int connection_number,
+                                       unsigned int output_assembly,
+                                       unsigned int input_assembly,
+                                       unsigned int config_assembly) {
+  if (OPENER_CIP_NUM_INPUT_ONLY_CONNS > connection_number) {
+    g_input_only_connections[connection_number].output_assembly =
+        output_assembly;
+    g_input_only_connections[connection_number].input_assembly = input_assembly;
+    g_input_only_connections[connection_number].config_assembly =
+        config_assembly;
+  }
 }
 }
 
 
-void
-configureListenOnlyConnectionPoint(unsigned int pa_unConnNum,
-    unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly,
-    unsigned int pa_unConfigAssembly)
-{
-  if (OPENER_CIP_NUM_LISTEN_ONLY_CONNS > pa_unConnNum)
-    {
-      g_astListenOnlyConnections[pa_unConnNum].m_unOutputAssembly =
-          pa_unOutputAssembly;
-      g_astListenOnlyConnections[pa_unConnNum].m_unInputAssembly =
-          pa_unInputAssembly;
-      g_astListenOnlyConnections[pa_unConnNum].m_unConfigAssembly =
-          pa_unConfigAssembly;
-    }
+void ConfigureListenOnlyConnectionPoint(unsigned int connection_number,
+                                        unsigned int output_assembly,
+                                        unsigned int input_assembly,
+                                        unsigned int config_assembly) {
+  if (OPENER_CIP_NUM_LISTEN_ONLY_CONNS > connection_number) {
+    g_listen_only_connections[connection_number].output_assembly =
+        output_assembly;
+    g_listen_only_connections[connection_number].input_assembly =
+        input_assembly;
+    g_listen_only_connections[connection_number].config_assembly =
+        config_assembly;
+  }
 }
 }
 
 
-S_CIP_ConnectionObject *
-getIOConnectionForConnectionData(S_CIP_ConnectionObject *pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError)
-{
-  S_CIP_ConnectionObject *pstRetVal = NULL;
-  *pa_pnExtendedError = 0;
-
-  pstRetVal = getExclusiveOwnerConnection(pa_pstConnData, pa_pnExtendedError);
-  if (NULL == pstRetVal)
-    {
-      if (0 == *pa_pnExtendedError)
-        {
-          /* we found no connection and don't have an error so try input only next */
-          pstRetVal = getInputOnlyConnection(pa_pstConnData,
-              pa_pnExtendedError);
-          if (NULL == pstRetVal)
-            {
-              if (0 == *pa_pnExtendedError)
-                {
-                  /* we found no connection and don't have an error so try listen only next */
-                  pstRetVal = getListenOnlyConnection(pa_pstConnData,
-                      pa_pnExtendedError);
-                  if ((NULL == pstRetVal) && (0 == *pa_pnExtendedError))
-                    {
-                      /* no application connection type was found that suits the given data */
-                      /* TODO check error code VS */
-                      *pa_pnExtendedError =
-                          CIP_CON_MGR_INCONSISTENT_APPLICATION_PATH_COMBO;
-                    }
-                  else
-                    {
-                      pa_pstConnData->m_eInstanceType = enConnTypeIOListenOnly;
-                    }
-                }
-            }
-          else
-            {
-              pa_pstConnData->m_eInstanceType = enConnTypeIOInputOnly;
-            }
+ConnectionObject *GetIoConnectionForConnectionData(
+    ConnectionObject *connection_object, EipUint16 *extended_error) {
+  ConnectionObject *io_connection = NULL;
+  *extended_error = 0;
+
+  io_connection = GetExclusiveOwnerConnection(connection_object,
+                                              extended_error);
+  if (NULL == io_connection) {
+    if (0 == *extended_error) {
+      /* we found no connection and don't have an error so try input only next */
+      io_connection = GetInputOnlyConnection(connection_object, extended_error);
+      if (NULL == io_connection) {
+        if (0 == *extended_error) {
+          /* we found no connection and don't have an error so try listen only next */
+          io_connection = GetListenOnlyConnection(connection_object,
+                                                  extended_error);
+          if ((NULL == io_connection) && (0 == *extended_error)) {
+            /* no application connection type was found that suits the given data */
+            /* TODO check error code VS */
+            *extended_error =
+                kConnectionManagerStatusCodeInconsistentApplicationPathCombo;
+          } else {
+            connection_object->instance_type = kConnectionTypeIoListenOnly;
+          }
         }
         }
+      } else {
+        connection_object->instance_type = kConnectionTypeIoInputOnly;
+      }
     }
     }
-  else
-    {
-      pa_pstConnData->m_eInstanceType = enConnTypeIOExclusiveOwner;
-    }
+  } else {
+    connection_object->instance_type = kConnectionTypeIoExclusiveOwner;
+  }
 
 
-  if (NULL != pstRetVal)
-    {
-      copyConnectionData(pstRetVal, pa_pstConnData);
-    }
+  if (NULL != io_connection) {
+    CopyConnectionData(io_connection, connection_object);
+  }
 
 
-  return pstRetVal;
+  return io_connection;
 }
 }
 
 
-S_CIP_ConnectionObject *
-getExclusiveOwnerConnection(S_CIP_ConnectionObject * pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError)
-{
-  S_CIP_ConnectionObject *pstRetVal = NULL;
+ConnectionObject *GetExclusiveOwnerConnection(
+    ConnectionObject *connection_object, EipUint16 *extended_error) {
+  ConnectionObject *exclusive_owner_connection = NULL;
   int i;
   int i;
 
 
-  for (i = 0; i < OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS; i++)
-    {
-      if ((g_astExlusiveOwnerConnections[i].m_unOutputAssembly
-          == pa_pstConnData->ConnectionPath.ConnectionPoint[0])
-          && (g_astExlusiveOwnerConnections[i].m_unInputAssembly
-              == pa_pstConnData->ConnectionPath.ConnectionPoint[1])
-          && (g_astExlusiveOwnerConnections[i].m_unConfigAssembly
-              == pa_pstConnData->ConnectionPath.ConnectionPoint[2]))
-        {
-
-          /* check if on other connection point with the same output assembly is currently connected */
-          if (NULL
-              != getConnectedOutputAssembly(
-                  pa_pstConnData->ConnectionPath.ConnectionPoint[0]))
-            {
-              *pa_pnExtendedError = CIP_CON_MGR_ERROR_OWNERSHIP_CONFLICT;
-              break;
-            }
-          pstRetVal = &(g_astExlusiveOwnerConnections[i].m_stConnectionData);
-          break;
-        }
+  for (i = 0; i < OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS; i++) {
+    if ((g_exlusive_owner_connections[i].output_assembly
+        == connection_object->connection_path.connection_point[0])
+        && (g_exlusive_owner_connections[i].input_assembly
+            == connection_object->connection_path.connection_point[1])
+        && (g_exlusive_owner_connections[i].config_assembly
+            == connection_object->connection_path.connection_point[2])) {
+
+      /* check if on other connection point with the same output assembly is currently connected */
+      if (NULL
+          != GetConnectedOutputAssembly(
+              connection_object->connection_path.connection_point[0])) {
+        *extended_error = kConnectionManagerStatusCodeErrorOwnershipConflict;
+        break;
+      }
+      exclusive_owner_connection = &(g_exlusive_owner_connections[i]
+          .connection_data);
+      break;
     }
     }
-  return pstRetVal;
+  }
+  return exclusive_owner_connection;
 }
 }
 
 
-S_CIP_ConnectionObject *
-getInputOnlyConnection(S_CIP_ConnectionObject * pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError)
-{
-  S_CIP_ConnectionObject *pstRetVal = NULL;
+ConnectionObject *GetInputOnlyConnection(ConnectionObject *connection_object,
+                                         EipUint16 *extended_error) {
+  ConnectionObject *input_only_connection = NULL;
   int i, j;
   int i, j;
 
 
-  for (i = 0; i < OPENER_CIP_NUM_INPUT_ONLY_CONNS; i++)
-    {
-      if (g_astInputOnlyConnections[i].m_unOutputAssembly
-          == pa_pstConnData->ConnectionPath.ConnectionPoint[0])
-        { /* we have the same output assembly */
-          if (g_astInputOnlyConnections[i].m_unInputAssembly
-              != pa_pstConnData->ConnectionPath.ConnectionPoint[1])
-            {
-              *pa_pnExtendedError =
-                  CIP_CON_MGR_INVALID_PRODUCING_APPLICATION_PATH;
-              break;
-            }
-          if (g_astInputOnlyConnections[i].m_unConfigAssembly
-              != pa_pstConnData->ConnectionPath.ConnectionPoint[2])
-            {
-              *pa_pnExtendedError =
-                  CIP_CON_MGR_INCONSISTENT_APPLICATION_PATH_COMBO;
-              break;
-            }
-
-          for (j = 0; j < OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH; j++)
-            {
-              if (CONN_STATE_NONEXISTENT
-                  == g_astInputOnlyConnections[i].m_astConnectionData[j].State)
-                {
-                  return &(g_astInputOnlyConnections[i].m_astConnectionData[j]);
-                }
-            }
-          *pa_pnExtendedError = CIP_CON_MGR_TARGET_OBJECT_OUT_OF_CONNECTIONS;
-          break;
+  for (i = 0; i < OPENER_CIP_NUM_INPUT_ONLY_CONNS; i++) {
+    if (g_input_only_connections[i].output_assembly
+        == connection_object->connection_path.connection_point[0]) { /* we have the same output assembly */
+      if (g_input_only_connections[i].input_assembly
+          != connection_object->connection_path.connection_point[1]) {
+        *extended_error =
+            kConnectionManagerStatusCodeInvalidProducingApplicationPath;
+        break;
+      }
+      if (g_input_only_connections[i].config_assembly
+          != connection_object->connection_path.connection_point[2]) {
+        *extended_error =
+            kConnectionManagerStatusCodeInconsistentApplicationPathCombo;
+        break;
+      }
+
+      for (j = 0; j < OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH; j++) {
+        if (kConnectionStateNonExistent
+            == g_input_only_connections[i].connection_data[j].state) {
+          return &(g_input_only_connections[i].connection_data[j]);
         }
         }
+      }
+      *extended_error =
+          kConnectionManagerStatusCodeTargetObjectOutOfConnections;
+      break;
     }
     }
-  return pstRetVal;
+  }
+  return input_only_connection;
 }
 }
 
 
-S_CIP_ConnectionObject *
-getListenOnlyConnection(S_CIP_ConnectionObject * pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError)
-{
-  S_CIP_ConnectionObject *pstRetVal = NULL;
+ConnectionObject *GetListenOnlyConnection(ConnectionObject *connection_object,
+                                          EipUint16 *extended_error) {
+  ConnectionObject *listen_only_connection = NULL;
   int i, j;
   int i, j;
 
 
-  if (CIP_MULTICAST_CONNECTION
-      != (pa_pstConnData->T_to_O_NetworkConnectionParameter
-          & CIP_MULTICAST_CONNECTION))
-    {
-      /* a listen only connection has to be a multicast connection. */
-      *pa_pnExtendedError = CIP_CON_MGR_NON_LISTEN_ONLY_CONNECTION_NOT_OPENED; /* maybe not the best error message however there is no suitable definition in the cip spec */
-      return NULL;
-    }
-
-  for (i = 0; i < OPENER_CIP_NUM_LISTEN_ONLY_CONNS; i++)
-    {
-      if (g_astListenOnlyConnections[i].m_unOutputAssembly
-          == pa_pstConnData->ConnectionPath.ConnectionPoint[0])
-        { /* we have the same output assembly */
-          if (g_astListenOnlyConnections[i].m_unInputAssembly
-              != pa_pstConnData->ConnectionPath.ConnectionPoint[1])
-            {
-              *pa_pnExtendedError =
-                  CIP_CON_MGR_INVALID_PRODUCING_APPLICATION_PATH;
-              break;
-            }
-          if (g_astListenOnlyConnections[i].m_unConfigAssembly
-              != pa_pstConnData->ConnectionPath.ConnectionPoint[2])
-            {
-              *pa_pnExtendedError =
-                  CIP_CON_MGR_INCONSISTENT_APPLICATION_PATH_COMBO;
-              break;
-            }
-
-          if (NULL
-              == getExistingProdMulticastConnection(
-                  pa_pstConnData->ConnectionPath.ConnectionPoint[1]))
-            {
-              *pa_pnExtendedError =
-                  CIP_CON_MGR_NON_LISTEN_ONLY_CONNECTION_NOT_OPENED;
-              break;
-            }
-
-          for (j = 0; j < OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH; j++)
-            {
-              if (CONN_STATE_NONEXISTENT
-                  == g_astListenOnlyConnections[i].m_astConnectionData[j].State)
-                {
-                  return &(g_astListenOnlyConnections[i].m_astConnectionData[j]);
-                }
-            }
-          *pa_pnExtendedError = CIP_CON_MGR_TARGET_OBJECT_OUT_OF_CONNECTIONS;
-          break;
+  if (kRoutingTypeMulticastConnection
+      != (connection_object->t_to_o_network_connection_parameter
+          & kRoutingTypeMulticastConnection)) {
+    /* a listen only connection has to be a multicast connection. */
+    *extended_error =
+        kConnectionManagerStatusCodeNonListenOnlyConnectionNotOpened; /* maybe not the best error message however there is no suitable definition in the cip spec */
+    return NULL;
+  }
+
+  for (i = 0; i < OPENER_CIP_NUM_LISTEN_ONLY_CONNS; i++) {
+    if (g_listen_only_connections[i].output_assembly
+        == connection_object->connection_path.connection_point[0]) { /* we have the same output assembly */
+      if (g_listen_only_connections[i].input_assembly
+          != connection_object->connection_path.connection_point[1]) {
+        *extended_error =
+            kConnectionManagerStatusCodeInvalidProducingApplicationPath;
+        break;
+      }
+      if (g_listen_only_connections[i].config_assembly
+          != connection_object->connection_path.connection_point[2]) {
+        *extended_error =
+            kConnectionManagerStatusCodeInconsistentApplicationPathCombo;
+        break;
+      }
+
+      if (NULL
+          == GetExistingProducerMulticastConnection(
+              connection_object->connection_path.connection_point[1])) {
+        *extended_error =
+            kConnectionManagerStatusCodeNonListenOnlyConnectionNotOpened;
+        break;
+      }
+
+      for (j = 0; j < OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH; j++) {
+        if (kConnectionStateNonExistent
+            == g_listen_only_connections[i].connection_data[j].state) {
+          return &(g_listen_only_connections[i].connection_data[j]);
         }
         }
+      }
+      *extended_error =
+          kConnectionManagerStatusCodeTargetObjectOutOfConnections;
+      break;
     }
     }
-  return pstRetVal;
+  }
+  return listen_only_connection;
 }
 }
 
 
-S_CIP_ConnectionObject *
-getExistingProdMulticastConnection(EIP_UINT32 pa_unInputPoint)
-{
-  S_CIP_ConnectionObject *pstRunner = g_pstActiveConnectionList;
-
-  while (NULL != pstRunner)
-    {
-      if ((enConnTypeIOExclusiveOwner == pstRunner->m_eInstanceType)
-          || (enConnTypeIOInputOnly == pstRunner->m_eInstanceType))
-        {
-          if ((pa_unInputPoint == pstRunner->ConnectionPath.ConnectionPoint[1])
-              && (CIP_MULTICAST_CONNECTION
-                  == (pstRunner->T_to_O_NetworkConnectionParameter
-                      & CIP_MULTICAST_CONNECTION))
-              && (EIP_INVALID_SOCKET != pstRunner->sockfd[PRODUCING]))
-            {
-              /* we have a connection that produces the same input assembly,
-               * is a multicast producer and manages the connection.
-               */
-              break;
-            }
-        }
-      pstRunner = pstRunner->m_pstNext;
+ConnectionObject *GetExistingProducerMulticastConnection(EipUint32 input_point) {
+  ConnectionObject *producer_multicast_connection = g_active_connection_list;
+
+  while (NULL != producer_multicast_connection) {
+    if ((kConnectionTypeIoExclusiveOwner
+        == producer_multicast_connection->instance_type)
+        || (kConnectionTypeIoInputOnly
+            == producer_multicast_connection->instance_type)) {
+      if ((input_point
+          == producer_multicast_connection->connection_path.connection_point[1])
+          && (kRoutingTypeMulticastConnection
+              == (producer_multicast_connection
+                  ->t_to_o_network_connection_parameter
+                  & kRoutingTypeMulticastConnection))
+          && (kEipInvalidSocket
+              != producer_multicast_connection->socket[kUdpCommuncationDirectionProducing])) {
+        /* we have a connection that produces the same input assembly,
+         * is a multicast producer and manages the connection.
+         */
+        break;
+      }
     }
     }
-  return pstRunner;
+    producer_multicast_connection = producer_multicast_connection
+        ->next_connection_object;
+  }
+  return producer_multicast_connection;
 }
 }
 
 
-S_CIP_ConnectionObject *
-getNextNonCtrlMasterCon(EIP_UINT32 pa_unInputPoint)
-{
-  S_CIP_ConnectionObject *pstRunner = g_pstActiveConnectionList;
-
-  while (NULL != pstRunner)
-    {
-      if ((enConnTypeIOExclusiveOwner == pstRunner->m_eInstanceType)
-          || (enConnTypeIOInputOnly == pstRunner->m_eInstanceType))
-        {
-          if ((pa_unInputPoint == pstRunner->ConnectionPath.ConnectionPoint[1])
-              && (CIP_MULTICAST_CONNECTION
-                  == (pstRunner->T_to_O_NetworkConnectionParameter
-                      & CIP_MULTICAST_CONNECTION))
-              && (EIP_INVALID_SOCKET == pstRunner->sockfd[PRODUCING]))
-            {
-              /* we have a connection that produces the same input assembly,
-               * is a multicast producer and does not manages the connection.
-               */
-              break;
-            }
-        }
-      pstRunner = pstRunner->m_pstNext;
+ConnectionObject *GetNextNonControlMasterConnection(EipUint32 input_point) {
+  ConnectionObject *next_non_control_master_connection =
+      g_active_connection_list;
+
+  while (NULL != next_non_control_master_connection) {
+    if ((kConnectionTypeIoExclusiveOwner
+        == next_non_control_master_connection->instance_type)
+        || (kConnectionTypeIoInputOnly
+            == next_non_control_master_connection->instance_type)) {
+      if ((input_point
+          == next_non_control_master_connection->connection_path
+              .connection_point[1])
+          && (kRoutingTypeMulticastConnection
+              == (next_non_control_master_connection
+                  ->t_to_o_network_connection_parameter
+                  & kRoutingTypeMulticastConnection))
+          && (kEipInvalidSocket
+              == next_non_control_master_connection->socket[kUdpCommuncationDirectionProducing])) {
+        /* we have a connection that produces the same input assembly,
+         * is a multicast producer and does not manages the connection.
+         */
+        break;
+      }
     }
     }
-  return pstRunner;
+    next_non_control_master_connection = next_non_control_master_connection
+        ->next_connection_object;
+  }
+  return next_non_control_master_connection;
 }
 }
 
 
-void
-closeAllConnsForInputWithSameType(EIP_UINT32 pa_unInputPoint,
-    EConnType pa_eInstanceType)
-{
-  S_CIP_ConnectionObject *pstRunner = g_pstActiveConnectionList;
-  S_CIP_ConnectionObject *pstToDelete;
-
-  while (NULL != pstRunner)
-    {
-      if ((pa_eInstanceType == pstRunner->m_eInstanceType)
-          && (pa_unInputPoint == pstRunner->ConnectionPath.ConnectionPoint[1]))
-        {
-          pstToDelete = pstRunner;
-          pstRunner = pstRunner->m_pstNext;
-          IApp_IOConnectionEvent(pstToDelete->ConnectionPath.ConnectionPoint[0],
-              pstToDelete->ConnectionPath.ConnectionPoint[1], enClosed);
-
-          //FIXME check if this is ok
-          pstToDelete->m_pfCloseFunc(pstToDelete);
-          //closeConnection(pstToDelete); /* will remove the connection from the active connection list */
-        }
-      else
-        {
-          pstRunner = pstRunner->m_pstNext;
-        }
+void CloseAllConnectionsForInputWithSameType(EipUint32 input_point,
+                                             ConnectionType instance_type) {
+  ConnectionObject *connection = g_active_connection_list;
+  ConnectionObject *connection_to_delete;
+
+  while (NULL != connection) {
+    if ((instance_type == connection->instance_type)
+        && (input_point == connection->connection_path.connection_point[1])) {
+      connection_to_delete = connection;
+      connection = connection->next_connection_object;
+      IoConnectionEvent(
+          connection_to_delete->connection_path.connection_point[0],
+          connection_to_delete->connection_path.connection_point[1],
+          kClosedEvent);
+
+      /* FIXME check if this is ok */
+      connection_to_delete->connection_close_function(connection_to_delete);
+      /*closeConnection(pstToDelete); will remove the connection from the active connection list */
+    } else {
+      connection = connection->next_connection_object;
     }
     }
+  }
 }
 }
 
 
-void
-closeAllConnections(void)
-{
-  S_CIP_ConnectionObject *pstRunner = g_pstActiveConnectionList;
-  while (NULL != pstRunner)
-    {
-      //FIXME check if m_pfCloseFunc would be suitable
-      closeConnection(pstRunner);
-      /* Close connection will remove the connection from the list therefore we
-       * need to get again the start until there is no connection left
-       */
-      pstRunner = g_pstActiveConnectionList;
-    }
+void CloseAllConnections(void) {
+  ConnectionObject *connection = g_active_connection_list;
+  while (NULL != connection) {
+    /*FIXME check if m_pfCloseFunc would be suitable*/
+    CloseConnection(connection);
+    /* Close connection will remove the connection from the list therefore we
+     * need to get again the start until there is no connection left
+     */
+    connection = g_active_connection_list;
+  }
 
 
 }
 }
 
 
-EIP_BOOL8
-connectionWithSameConfigPointExists(EIP_UINT32 pa_unConfigPoint)
-{
-  S_CIP_ConnectionObject *pstRunner = g_pstActiveConnectionList;
+EipBool8 ConnectionWithSameConfigPointExists(EipUint32 config_point) {
+  ConnectionObject *connection = g_active_connection_list;
 
 
-  while (NULL != pstRunner)
-    {
-      if (pa_unConfigPoint == pstRunner->ConnectionPath.ConnectionPoint[2])
-        {
-          break;
-        }
-      pstRunner = pstRunner->m_pstNext;
+  while (NULL != connection) {
+    if (config_point == connection->connection_path.connection_point[2]) {
+      break;
     }
     }
-  return (NULL != pstRunner);
+    connection = connection->next_connection_object;
+  }
+  return (NULL != connection);
 }
 }
 
 
-void
-initializeIOConnectionData()
-{
-  memset(g_astExlusiveOwnerConnections, 0,
-      OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS * sizeof(S_ExclusiveOwnerConnection));
-  memset(g_astInputOnlyConnections, 0,
-      OPENER_CIP_NUM_INPUT_ONLY_CONNS * sizeof(S_InputOnlyConnection));
-  memset(g_astListenOnlyConnections, 0,
-      OPENER_CIP_NUM_LISTEN_ONLY_CONNS * sizeof(S_ListenOnlyConnection));
+void InitializeIoConnectionData(void) {
+  memset(g_exlusive_owner_connections, 0,
+  OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS * sizeof(ExclusiveOwnerConnection));
+  memset(g_input_only_connections, 0,
+  OPENER_CIP_NUM_INPUT_ONLY_CONNS * sizeof(InputOnlyConnection));
+  memset(g_listen_only_connections, 0,
+  OPENER_CIP_NUM_LISTEN_ONLY_CONNS * sizeof(ListenOnlyConnection));
 }
 }

+ 27 - 32
source/src/cip/appcontype.h

@@ -3,74 +3,69 @@
  * All rights reserved.
  * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef APPCONTYPE_H_
-#define APPCONTYPE_H_
+#ifndef OPENER_APPCONTYPE_H_
+#define OPENER_APPCONTYPE_H_
 
 
 #include "cipconnectionmanager.h"
 #include "cipconnectionmanager.h"
 
 
+void InitializeIoConnectionData(void);
 
 
-void initializeIOConnectionData();
-
-/*! \brief check if for the given connection data received in a forward_open request
+/** @brief check if for the given connection data received in a forward_open request
  *  a suitable connection is available.
  *  a suitable connection is available.
  *
  *
  *  If a suitable connection is found the connection data is transfered the
  *  If a suitable connection is found the connection data is transfered the
  *  application connection type is set (i.e., EConnType).
  *  application connection type is set (i.e., EConnType).
- *  @param pa_pstConnData connection data to be used
- *  @param pa_pnExtendedError if an error occurred this value has the according
+ *  @param connection_object connection data to be used
+ *  @param extended_error if an error occurred this value has the according
  *     error code for the response
  *     error code for the response
  *  @return
  *  @return
  *        - on success: A pointer to the connection object already containing the connection
  *        - on success: A pointer to the connection object already containing the connection
  *          data given in pa_pstConnData.
  *          data given in pa_pstConnData.
  *        - on error: NULL
  *        - on error: NULL
  */
  */
-S_CIP_ConnectionObject *
-getIOConnectionForConnectionData(S_CIP_ConnectionObject *pa_pstConnData,
-    EIP_UINT16 *pa_pnExtendedError);
+ConnectionObject *GetIoConnectionForConnectionData(
+    ConnectionObject *connection_object, EipUint16 *extended_error);
 
 
-/*! \brief Check if there exists already an exclusive owner or listen only connection
+/** @brief Check if there exists already an exclusive owner or listen only connection
  *         which produces the input assembly.
  *         which produces the input assembly.
  *
  *
- *  @param pa_unInputPoint the Input point to be produced
+ *  @param input_point the Input point to be produced
  *  @return if a connection could be found a pointer to this connection if not NULL
  *  @return if a connection could be found a pointer to this connection if not NULL
  */
  */
-S_CIP_ConnectionObject *
-getExistingProdMulticastConnection(EIP_UINT32 pa_unInputPoint);
+ConnectionObject *GetExistingProducerMulticastConnection(EipUint32 input_point);
 
 
-/*! \brief check if there exists an producing multicast exclusive owner or
+/** @brief check if there exists an producing multicast exclusive owner or
  * listen only connection that should produce the same input but is not in charge
  * listen only connection that should produce the same input but is not in charge
  * of the connection.
  * of the connection.
  *
  *
- * @param pa_unInputPoint the produced input
+ * @param input_point the produced input
  * @return if a connection could be found the pointer to this connection
  * @return if a connection could be found the pointer to this connection
  *      otherwise NULL.
  *      otherwise NULL.
  */
  */
-S_CIP_ConnectionObject *
-getNextNonCtrlMasterCon(EIP_UINT32 pa_unInputPoint);
+ConnectionObject *GetNextNonControlMasterConnection(EipUint32 input_point);
 
 
-/*! \brief Close all connection producing the same input and have the same type
+/** @brief Close all connection producing the same input and have the same type
  * (i.e., listen only or input only).
  * (i.e., listen only or input only).
  *
  *
- * @param pa_unInputPoint  the input point
- * @param pa_eInstanceType the connection application type
+ * @param input_point  the input point
+ * @param instance_type the connection application type
  */
  */
-void
-closeAllConnsForInputWithSameType(EIP_UINT32 pa_unInputPoint,
-    EConnType pa_eInstanceType);
-
+void CloseAllConnectionsForInputWithSameType(EipUint32 input_point,
+                                             ConnectionType instance_type);
 
 
-/*!\brief close all open connections.
+/**@ brief close all open connections.
  *
  *
  * For I/O connections the sockets will be freed. The sockets for explicit
  * For I/O connections the sockets will be freed. The sockets for explicit
  * connections are handled by the encapsulation layer, and freed there.
  * connections are handled by the encapsulation layer, and freed there.
  */
  */
-void closeAllConnections(void);
+void CloseAllConnections(void);
 
 
-
-/*! \brief Check if there is an established connection that uses the same
+/** @brief Check if there is an established connection that uses the same
  * config point.
  * config point.
+ *
+ * @param config_point The configuration point
+ * @return true if connection was found, otherwise false
  */
  */
-EIP_BOOL8
-connectionWithSameConfigPointExists(EIP_UINT32 pa_unConfigPoint);
+EipBool8 ConnectionWithSameConfigPointExists(EipUint32 config_point);
 
 
-#endif /* APPCONTYPE_H_ */
+#endif /* OPENER_APPCONTYPE_H_ */

+ 145 - 173
source/src/cip/cipassembly.c

@@ -3,212 +3,184 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
+
 #include <string.h>    /*needed for memcpy */
 #include <string.h>    /*needed for memcpy */
+
 #include "cipassembly.h"
 #include "cipassembly.h"
+
 #include "cipcommon.h"
 #include "cipcommon.h"
 #include "opener_api.h"
 #include "opener_api.h"
 #include "trace.h"
 #include "trace.h"
 #include "cipconnectionmanager.h"
 #include "cipconnectionmanager.h"
 
 
-/*! \brief Implementation of the SetAttributeSingle CIP service for Assembly
+/** @brief Implementation of the SetAttributeSingle CIP service for Assembly
  *          Objects.
  *          Objects.
  *  Currently only supports Attribute 3 (CIP_BYTE_ARRAY) of an Assembly
  *  Currently only supports Attribute 3 (CIP_BYTE_ARRAY) of an Assembly
  */
  */
-EIP_STATUS
-setAssemblyAttributeSingle(S_CIP_Instance *pa_pstInstance,
-    S_CIP_MR_Request *pa_pstMRRequest, S_CIP_MR_Response *pa_pstMRResponse);
-
-S_CIP_Class *
-createAssemblyClass()
-{
-  S_CIP_Class *pstAssemblyClass;
-  /* create the CIP Assembly object with zero instances */
-  pstAssemblyClass = createCIPClass(CIP_ASSEMBLY_CLASS_CODE, 0, /* # class attributes*/
-  0, /* 0 as the assembly object should not have a get_attribute_all service*/
-  0, /* # class services*/
-  2, /* # instance attributes*/
-  0, /* 0 as the assembly object should not have a get_attribute_all service*/
-  1, /* # instance services*/
-  0, /* # instances*/
-  "assembly", 2 /* Revision, according to the CIP spec currently this has to be 2 */
-  );
-  if (NULL != pstAssemblyClass)
-    {
-      insertService(pstAssemblyClass, CIP_SET_ATTRIBUTE_SINGLE,
-          &setAssemblyAttributeSingle, "SetAssemblyAttributeSingle");
-    }
+EipStatus SetAssemblyAttributeSingle(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response);
 
 
-  return pstAssemblyClass;
+CipClass *CreateAssemblyClass(void) {
+  CipClass *assembly_class;
+  /* create the CIP Assembly object with zero instances */
+  assembly_class = CreateCipClass(kCipAssemblyClassCode, 0, /* # class attributes*/
+                                  0, /* 0 as the assembly object should not have a get_attribute_all service*/
+                                  0, /* # class services*/
+                                  2, /* # instance attributes*/
+                                  0, /* 0 as the assembly object should not have a get_attribute_all service*/
+                                  1, /* # instance services*/
+                                  0, /* # instances*/
+                                  "assembly", /* name */
+                                  2 /* Revision, according to the CIP spec currently this has to be 2 */
+                                  );
+  if (NULL != assembly_class) {
+    InsertService(assembly_class, kSetAttributeSingle,
+                  &SetAssemblyAttributeSingle, "SetAssemblyAttributeSingle");
+  }
+
+  return assembly_class;
 }
 }
 
 
-EIP_STATUS
-CIP_Assembly_Init()
-{ /* create the CIP Assembly object with zero instances */
-  return createAssemblyClass() ? EIP_OK : EIP_ERROR;
+EipStatus CipAssemblyInitialize(void) { /* create the CIP Assembly object with zero instances */
+  return (NULL != CreateAssemblyClass()) ? kEipStatusOk : kEipStatusError;
 }
 }
 
 
-void
-shutdownAssemblies(void)
-{
-  S_CIP_Class *pstAssemblyClass = getCIPClass(CIP_ASSEMBLY_CLASS_CODE);
-  S_CIP_attribute_struct *pstAttribute;
-  S_CIP_Instance *pstRunner;
-
-  if (NULL != pstAssemblyClass)
-    {
-      pstRunner = pstAssemblyClass->pstInstances;
-      while (NULL != pstRunner)
-        {
-          pstAttribute = getAttribute(pstRunner, 3);
-          if (NULL != pstAttribute)
-            {
-              IApp_CipFree(pstAttribute->pt2data);
-            }
-          pstRunner = pstRunner->pstNext;
-        }
+void ShutdownAssemblies(void) {
+  CipClass *assembly_class = GetCipClass(kCipAssemblyClassCode);
+  CipAttributeStruct *attribute;
+  CipInstance *instance;
+
+  if (NULL != assembly_class) {
+    instance = assembly_class->instances;
+    while (NULL != instance) {
+      attribute = GetCipAttribute(instance, 3);
+      if (NULL != attribute) {
+        CipFree(attribute->data);
+      }
+      instance = instance->next;
     }
     }
+  }
 }
 }
 
 
-S_CIP_Instance *
-createAssemblyObject(EIP_UINT32 pa_nInstanceID, EIP_BYTE * pa_data,
-    EIP_UINT16 pa_datalength)
-{
-  S_CIP_Class *pstAssemblyClass;
-  S_CIP_Instance *pstAssemblyInstance;
-  S_CIP_Byte_Array *stAssemblyByteArray;
-
-  if (NULL == (pstAssemblyClass = getCIPClass(CIP_ASSEMBLY_CLASS_CODE)))
-    {
-      if (NULL == (pstAssemblyClass = createAssemblyClass()))
-        {
-          return NULL;
-        }
+CipInstance *CreateAssemblyObject(EipUint32 instance_id, EipByte *data,
+                                  EipUint16 data_length) {
+  CipClass *assembly_class;
+  CipInstance *instance;
+  CipByteArray *assembly_byte_array;
+
+  if (NULL == (assembly_class = GetCipClass(kCipAssemblyClassCode))) {
+    if (NULL == (assembly_class = CreateAssemblyClass())) {
+      return NULL;
     }
     }
+  }
 
 
-  pstAssemblyInstance = addCIPInstance(pstAssemblyClass, pa_nInstanceID); /* add instances (always succeeds (or asserts))*/
+  instance = AddCIPInstance(assembly_class, instance_id); /* add instances (always succeeds (or asserts))*/
 
 
-  if ((stAssemblyByteArray = (S_CIP_Byte_Array *) IApp_CipCalloc(1,
-      sizeof(S_CIP_Byte_Array))) == NULL)
-    {
-      return NULL; /*TODO remove assembly instance in case of error*/
-    }
+  if ((assembly_byte_array = (CipByteArray *) CipCalloc(1, sizeof(CipByteArray)))
+      == NULL) {
+    return NULL; /*TODO remove assembly instance in case of error*/
+  }
 
 
-  stAssemblyByteArray->len = pa_datalength;
-  stAssemblyByteArray->Data = pa_data;
-  insertAttribute(pstAssemblyInstance, 3, CIP_BYTE_ARRAY, stAssemblyByteArray, CIP_ATTRIB_SETGETABLE);
-    //Attribut 4 Number of bytes in Attribut 3 
-  insertAttribute(pstAssemblyInstance, 4, CIP_UINT, &(stAssemblyByteArray->len), CIP_ATTRIB_GETABLESINGLE);
+  assembly_byte_array->length = data_length;
+  assembly_byte_array->data = data;
+  InsertAttribute(instance, 3, kCipByteArray, assembly_byte_array,
+                  kSetAndGetAble);
+  /* Attribute 4 Number of bytes in Attribute 3 */
+  InsertAttribute(instance, 4, kCipUint, &(assembly_byte_array->length),
+                  kGetableSingle);
 
 
-  return pstAssemblyInstance;
+  return instance;
 }
 }
 
 
-EIP_STATUS
-notifyAssemblyConnectedDataReceived(S_CIP_Instance * pa_pstInstance,
-    EIP_UINT8 * pa_pnData, EIP_UINT16 pa_nDataLength)
-{
-  S_CIP_Byte_Array *p;
+EipStatus NotifyAssemblyConnectedDataReceived(CipInstance *instance,
+                                              EipUint8 *data,
+                                              EipUint16 data_length) {
+  CipByteArray *assembly_byte_array;
 
 
   /* empty path (path size = 0) need to be checked and taken care of in future */
   /* empty path (path size = 0) need to be checked and taken care of in future */
   /* copy received data to Attribute 3 */
   /* copy received data to Attribute 3 */
-  p = (S_CIP_Byte_Array *) pa_pstInstance->pstAttributes->pt2data;
-  if (p->len != pa_nDataLength)
-    {
-      OPENER_TRACE_ERR("wrong amount of data arrived for assembly object\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);
+  assembly_byte_array = (CipByteArray *) instance->attributes->data;
+  if (assembly_byte_array->length != data_length) {
+    OPENER_TRACE_ERR("wrong amount of data arrived for assembly object\n");
+    return kEipStatusError; /*TODO question should we notify the application that wrong data has been recieved???*/
+  } else {
+    memcpy(assembly_byte_array->data, data, data_length);
+    /* call the application that new data arrived */
+  }
+
+  return AfterAssemblyDataReceived(instance);
 }
 }
 
 
-EIP_STATUS
-setAssemblyAttributeSingle(S_CIP_Instance *pa_pstInstance,
-    S_CIP_MR_Request *pa_pstMRRequest, S_CIP_MR_Response *pa_pstMRResponse)
-{
-
-  
-  EIP_UINT8 *acReqData;
-  S_CIP_attribute_struct *p; 
-  OPENER_TRACE_INFO(" setAttribute %d\n", pa_pstMRRequest->RequestPath.AttributNr);
-  
-  acReqData = pa_pstMRRequest->Data;
-
-  pa_pstMRResponse->DataLength = 0;
-  pa_pstMRResponse->ReplyService = (0x80 | pa_pstMRRequest->Service);
-  pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SUPPORTED;
-  pa_pstMRResponse->SizeofAdditionalStatus = 0;
-
-
-  p = getAttribute(pa_pstInstance,
-      pa_pstMRRequest->RequestPath.AttributNr);
-
-  if ((p != 0) && (3 == pa_pstMRRequest->RequestPath.AttributNr))
-    {
-      if (p->pt2data != 0)
-        {
-          S_CIP_Byte_Array * pacData = (S_CIP_Byte_Array *) p->pt2data;
-
-          //TODO: check for ATTRIBUTE_SET/GETABLE MASK
-          if (true == isConnectedOutputAssembly(pa_pstInstance->nInstanceNr))
-            {
-              OPENER_TRACE_WARN("Assembly AssemblyAttributeSingle: received data for connected output assembly\n\r");
-              pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SETTABLE;
-            }
-          else
-            {
-              if (pa_pstMRRequest->DataLength < pacData->len)
-                {
-                  OPENER_TRACE_INFO("Assembly setAssemblyAttributeSingle: not enough data received.\r\n");
-                  pa_pstMRResponse->GeneralStatus = CIP_ERROR_NOT_ENOUGH_DATA;
-                }
-              else
-                {
-                  if (pa_pstMRRequest->DataLength > pacData->len)
-                    {
-                      OPENER_TRACE_INFO("Assembly setAssemblyAttributeSingle: too much data received.\r\n");
-                      pa_pstMRResponse->GeneralStatus = CIP_ERROR_TOO_MUCH_DATA;
-                    }
-                  else
-                    {
-                      memcpy(pacData->Data, acReqData, pacData->len);
-
-                      if (IApp_AfterAssemblyDataReceived(pa_pstInstance)
-                          != EIP_OK)
-                        {
-                          /* punt early without updating the status... though I don't know
-                           * how much this helps us here, as the attribute's data has already
-                           * been overwritten.
-                           *
-                           * however this is the task of the application side which will
-                           * take the data. In addition we have to inform the sender that the
-                           * data was not ok.
-                           */
-                          pa_pstMRResponse->GeneralStatus
-                              = CIP_ERROR_INVALID_ATTRIBUTE_VALUE;
-                        }
-                      else
-                        {
-                          pa_pstMRResponse->GeneralStatus = CIP_ERROR_SUCCESS;
-                        }
-                    }
-                }
+EipStatus SetAssemblyAttributeSingle(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response) {
+  EipUint8 *router_request_data;
+  CipAttributeStruct *attribute;
+  OPENER_TRACE_INFO(" setAttribute %d\n",
+                    message_router_request->request_path.attribute_number);
+
+  router_request_data = message_router_request->data;
+
+  message_router_response->data_length = 0;
+  message_router_response->reply_service = (0x80
+      | message_router_request->service);
+  message_router_response->general_status = kCipErrorAttributeNotSupported;
+  message_router_response->size_of_additional_status = 0;
+
+  attribute = GetCipAttribute(
+      instance, message_router_request->request_path.attribute_number);
+
+  if ((attribute != NULL)
+      && (3 == message_router_request->request_path.attribute_number)) {
+    if (attribute->data != NULL) {
+      CipByteArray *data = (CipByteArray*) attribute->data;
+
+      /* TODO: check for ATTRIBUTE_SET/GETABLE MASK */
+      if (true == IsConnectedOutputAssembly(instance->instance_number)) {
+        OPENER_TRACE_WARN(
+            "Assembly AssemblyAttributeSingle: received data for connected output assembly\n\r");
+        message_router_response->general_status = kCipErrorAttributeNotSetable;
+      } else {
+        if (message_router_request->data_length < data->length) {
+          OPENER_TRACE_INFO(
+              "Assembly setAssemblyAttributeSingle: not enough data received.\r\n");
+          message_router_response->general_status = kCipErrorNotEnoughData;
+        } else {
+          if (message_router_request->data_length > data->length) {
+            OPENER_TRACE_INFO(
+                "Assembly setAssemblyAttributeSingle: too much data received.\r\n");
+            message_router_response->general_status = kCipErrorTooMuchData;
+          } else {
+            memcpy(data->data, router_request_data, data->length);
+
+            if (AfterAssemblyDataReceived(instance) != kEipStatusOk) {
+              /* punt early without updating the status... though I don't know
+               * how much this helps us here, as the attribute's data has already
+               * been overwritten.
+               *
+               * however this is the task of the application side which will
+               * take the data. In addition we have to inform the sender that the
+               * data was not ok.
+               */
+              message_router_response->general_status =
+                  kCipErrorInvalidAttributeValue;
+            } else {
+              message_router_response->general_status = kCipErrorSuccess;
             }
             }
+          }
         }
         }
-      else
-        {
-          /* the attribute was zero we are a heartbeat assembly */
-          pa_pstMRResponse->GeneralStatus = CIP_ERROR_TOO_MUCH_DATA;
-        }
+      }
+    } else {
+      /* the attribute was zero we are a heartbeat assembly */
+      message_router_response->general_status = kCipErrorTooMuchData;
     }
     }
+  }
 
 
-  if ((p != 0) && (4 == pa_pstMRRequest->RequestPath.AttributNr))
-    {
-      pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SETTABLE;
-    }
+  if ((attribute != NULL)
+      && (4 == message_router_request->request_path.attribute_number)) {
+    message_router_response->general_status = kCipErrorAttributeNotSetable;
+  }
 
 
-  return EIP_OK_SEND;
+  return kEipStatusOkSend;
 }
 }

+ 19 - 15
source/src/cip/cipassembly.h

@@ -3,44 +3,48 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPASSEMBLY_H_
-#define CIPASSEMBLY_H_
+#ifndef OPENER_CIPASSEMBLY_H_
+#define OPENER_CIPASSEMBLY_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
 
 
-#define CIP_ASSEMBLY_CLASS_CODE 0x04
+/** @brief Assembly Class Code */
+static const int kCipAssemblyClassCode = 0x04;
 
 
 /* public functions */
 /* public functions */
 
 
-/*! Setup the Assembly object
+/** @brief Setup the Assembly object
  * 
  * 
  * Creates the Assembly Class with zero instances and sets up all services.
  * Creates the Assembly Class with zero instances and sets up all services.
+ *
+ * @return Returns kEipStatusOk if assembly object was successfully created, otherwise kEipStatusError
  */
  */
-EIP_STATUS CIP_Assembly_Init(void);
+EipStatus CipAssemblyInitialize(void);
 
 
-/*! \brief clean up the data allocated in the assembly object instances
+/** @brief clean up the data allocated in the assembly object instances
  *
  *
  * Assembly object instances allocate per instance data to store attribute 3.
  * Assembly object instances allocate per instance data to store attribute 3.
  * This will be freed here. The assembly object data given by the application
  * This will be freed here. The assembly object data given by the application
  * is not freed neither the assembly object instances. These are handled in the
  * is not freed neither the assembly object instances. These are handled in the
  * main shutdown function.
  * main shutdown function.
  */
  */
-void shutdownAssemblies(void);
+void ShutdownAssemblies(void);
 
 
-/*! notify an Assembly object that data has been received for it.
+/** @brief notify an Assembly object that data has been received for it.
  * 
  * 
  *  The data will be copied into the assembly objects attribute 3 and
  *  The data will be copied into the assembly objects attribute 3 and
  *  the application will be informed with the IApp_after_assembly_data_received function.
  *  the application will be informed with the IApp_after_assembly_data_received function.
  *  
  *  
- *  @param pa_pstInstance the assembly object instance for which the data was received
- *  @param pa_pnData pointer to the data received
- *  @param pa_nDatalength number of bytes received
+ *  @param instance the assembly object instance for which the data was received
+ *  @param data pointer to the data received
+ *  @param data_length number of bytes received
  *  @return 
  *  @return 
  *     - EIP_OK the received data was okay
  *     - EIP_OK the received data was okay
  *     - EIP_ERROR the received data was wrong
  *     - EIP_ERROR the received data was wrong
- */ 
-EIP_STATUS notifyAssemblyConnectedDataReceived(S_CIP_Instance *pa_pstInstance,
-    EIP_UINT8 *pa_pnData, EIP_UINT16 pa_nDatalength);
+ */
+EipStatus NotifyAssemblyConnectedDataReceived(CipInstance *instance,
+                                              EipUint8 *data,
+                                              EipUint16 data_length);
 
 
-#endif /*CIPASSEMBLY_H_*/
+#endif /* OPENER_CIPASSEMBLY_H_ */

+ 41 - 45
source/src/cip/cipclass3connection.c

@@ -4,67 +4,63 @@
  *
  *
  ******************************************************************************/
  ******************************************************************************/
 
 
-#include "cipclass3connection.h"
-#include "cipconnectionmanager.h"
 #include <string.h>
 #include <string.h>
 
 
-S_CIP_ConnectionObject *
-getFreeExplicitConnection(void);
+#include "cipclass3connection.h"
+
+ConnectionObject *GetFreeExplicitConnection(void);
 
 
 /**** Global variables ****/
 /**** Global variables ****/
 
 
-/*! Array of the available explicit connections */
-S_CIP_ConnectionObject g_astExplicitConnections[OPENER_CIP_NUM_EXPLICIT_CONNS];
+/** @brief Array of the available explicit connections */
+ConnectionObject g_explicit_connections[OPENER_CIP_NUM_EXPLICIT_CONNS];
 
 
 /**** Implementation ****/
 /**** Implementation ****/
-int
-establishClass3Connection(struct CIP_ConnectionObject *pa_pstConnObj,
-    EIP_UINT16 *pa_pnExtendedError)
-{
-  int nRetVal = EIP_OK;
-  EIP_UINT32 nTmp;
+int EstablishClass3Connection(ConnectionObject *connection_object,
+                              EipUint16 *extended_error) {
+  int eip_status = kEipStatusOk;
+  EipUint32 produced_connection_id_buffer;
 
 
-  //TODO add check for transport type trigger
-  //if (0x03 == (g_stDummyConnectionObject.TransportTypeClassTrigger & 0x03))
+  /*TODO add check for transport type trigger */
+  /* if (0x03 == (g_stDummyConnectionObject.TransportTypeClassTrigger & 0x03)) */
 
 
-  S_CIP_ConnectionObject *pstExplConn = getFreeExplicitConnection();
+  ConnectionObject *explicit_connection = GetFreeExplicitConnection();
 
 
-  if (NULL == pstExplConn)
-    {
-      nRetVal = CIP_ERROR_CONNECTION_FAILURE;
-      *pa_pnExtendedError = CIP_CON_MGR_ERROR_NO_MORE_CONNECTIONS_AVAILABLE;
-    }
-  else
-    {
-      copyConnectionData(pstExplConn, pa_pstConnObj);
+  if (NULL == explicit_connection) {
+    eip_status = kCipErrorConnectionFailure;
+    *extended_error =
+        kConnectionManagerStatusCodeErrorNoMoreConnectionsAvailable;
+  } else {
+    CopyConnectionData(explicit_connection, connection_object);
 
 
-      nTmp = pstExplConn->CIPProducedConnectionID;
-      generalConnectionConfiguration(pstExplConn);
-      pstExplConn->CIPProducedConnectionID = nTmp;
-      pstExplConn->m_eInstanceType = enConnTypeExplicit;
-      pstExplConn->sockfd[0] = pstExplConn->sockfd[1] = EIP_INVALID_SOCKET;
-      /* set the connection call backs */
-      pstExplConn->m_pfCloseFunc = removeFromActiveConnections;
-      /* explicit connection have to be closed on time out*/
-      pstExplConn->m_pfTimeOutFunc = removeFromActiveConnections;
+    produced_connection_id_buffer = explicit_connection->produced_connection_id;
+    GeneralConnectionConfiguration(explicit_connection);
+    explicit_connection->produced_connection_id = produced_connection_id_buffer;
+    explicit_connection->instance_type = kConnectionTypeExplicit;
+    explicit_connection->socket[0] = explicit_connection->socket[1] =
+        kEipInvalidSocket;
+    /* set the connection call backs */
+    explicit_connection->connection_close_function =
+        RemoveFromActiveConnections;
+    /* explicit connection have to be closed on time out*/
+    explicit_connection->connection_timeout_function =
+        RemoveFromActiveConnections;
 
 
-      addNewActiveConnection(pstExplConn);
-    }
-  return nRetVal;
+    AddNewActiveConnection(explicit_connection);
+  }
+  return eip_status;
 }
 }
 
 
-S_CIP_ConnectionObject *
-getFreeExplicitConnection(void)
-{
+ConnectionObject *GetFreeExplicitConnection(void) {
   int i;
   int i;
-  for (i = 0; i < OPENER_CIP_NUM_EXPLICIT_CONNS; i++)
-    {
-      if (g_astExplicitConnections[i].State == CONN_STATE_NONEXISTENT)
-        return &(g_astExplicitConnections[i]);
-    }
+  for (i = 0; i < OPENER_CIP_NUM_EXPLICIT_CONNS; i++) {
+    if (g_explicit_connections[i].state == kConnectionStateNonExistent)
+      return &(g_explicit_connections[i]);
+  }
   return NULL;
   return NULL;
 }
 }
 
 
-void initializeClass3ConnectionData(){
-  memset(g_astExplicitConnections, 0, OPENER_CIP_NUM_EXPLICIT_CONNS * sizeof(S_CIP_ConnectionObject));
+void InitializeClass3ConnectionData(void) {
+  memset(g_explicit_connections, 0,
+  OPENER_CIP_NUM_EXPLICIT_CONNS * sizeof(ConnectionObject));
 }
 }

+ 12 - 8
source/src/cip/cipclass3connection.h

@@ -4,13 +4,17 @@
  *
  *
  ******************************************************************************/
  ******************************************************************************/
 
 
-#ifndef CIPCLASS3CONNECTION_H_
-#define CIPCLASS3CONNECTION_H_
+#ifndef OPENER_CIPCLASS3CONNECTION_H_
+#define OPENER_CIPCLASS3CONNECTION_H_
 
 
+/** @file cipclass3connection.h
+ *  @brief CIP Class 3 connection
+ */
 
 
-#include <opener_api.h>
+#include "opener_api.h"
+#include "cipconnectionmanager.h"
 
 
-/** \brief Check if Class3 connection is available and if yes setup all data.
+/** @brief Check if Class3 connection is available and if yes setup all data.
  *
  *
  * This function can be called after all data has been parsed from the forward open request
  * This function can be called after all data has been parsed from the forward open request
  * @param pa_pstConnObj pointer to the connection object structure holding the parsed data from the forward open request
  * @param pa_pstConnObj pointer to the connection object structure holding the parsed data from the forward open request
@@ -19,9 +23,9 @@
  *    - EIP_OK ... on success
  *    - EIP_OK ... on success
  *    - On an error the general status code to be put into the response
  *    - On an error the general status code to be put into the response
  */
  */
-int
-establishClass3Connection(struct CIP_ConnectionObject *pa_pstConnObj, EIP_UINT16 *pa_pnExtendedError);
+int EstablishClass3Connection(ConnectionObject *connection_object,
+                              EipUint16 *extended_error);
 
 
-void initializeClass3ConnectionData();
+void InitializeClass3ConnectionData(void);
 
 
-#endif /* CIPCLASS3CONNECTION_H_ */
+#endif /* OPENER_CIPCLASS3CONNECTION_H_ */

+ 592 - 640
source/src/cip/cipcommon.c

@@ -5,9 +5,10 @@
  ******************************************************************************/
  ******************************************************************************/
 #include <string.h>
 #include <string.h>
 
 
+#include "cipcommon.h"
+
 #include "opener_user_conf.h"
 #include "opener_user_conf.h"
 #include "opener_api.h"
 #include "opener_api.h"
-#include "cipcommon.h"
 #include "cipidentity.h"
 #include "cipidentity.h"
 #include "ciptcpipinterface.h"
 #include "ciptcpipinterface.h"
 #include "cipethernetlink.h"
 #include "cipethernetlink.h"
@@ -21,180 +22,169 @@
 #include "trace.h"
 #include "trace.h"
 #include "appcontype.h"
 #include "appcontype.h"
 
 
-/* global public variables */EIP_UINT8 g_acMessageDataReplyBuffer[OPENER_MESSAGE_DATA_REPLY_BUFFER];
+/* global public variables */
+EipUint8 g_message_data_reply_buffer[OPENER_MESSAGE_DATA_REPLY_BUFFER];
 
 
-const EIP_UINT16 cg_unCIPUINTZERO = 0;
+const EipUint16 kCipUintZero = 0;
 
 
 /* private functions*/
 /* private functions*/
-int
-encodeEPath(S_CIP_EPATH *pa_pstEPath, EIP_UINT8 **pa_pnMsg);
-
-void
-CIP_Init(EIP_UINT16 pa_nUniqueConnID)
-{
-  EIP_STATUS nRetVal;
-  encapInit();
+int EncodeEPath(CipEpath *epath, EipUint8 **message);
+
+void CipStackInit(EipUint16 unique_connection_id) {
+  EipStatus eip_status;
+  EncapsulationInit();
   /* The message router is the first CIP object that has to be initialized first!!! */
   /* The message router is the first CIP object that has to be initialized first!!! */
-  nRetVal = CIP_MessageRouter_Init();
-  OPENER_ASSERT(EIP_OK == nRetVal);
-  nRetVal = CIP_Identity_Init();
-  OPENER_ASSERT(EIP_OK == nRetVal);
-  nRetVal = CIP_TCPIP_Interface_Init();
-  OPENER_ASSERT(EIP_OK == nRetVal);
-  nRetVal = CIP_Ethernet_Link_Init();
-  OPENER_ASSERT(EIP_OK == nRetVal);
-  nRetVal = Connection_Manager_Init(pa_nUniqueConnID);
-  OPENER_ASSERT(EIP_OK == nRetVal);
-  nRetVal = CIP_Assembly_Init();
-  OPENER_ASSERT(EIP_OK == nRetVal);
+  eip_status = CipMessageRouterInit();
+  OPENER_ASSERT(kEipStatusOk == eip_status);
+  eip_status = CipIdentityInit();
+  OPENER_ASSERT(kEipStatusOk == eip_status);
+  eip_status = CipTcpIpInterfaceInit();
+  OPENER_ASSERT(kEipStatusOk == eip_status);
+  eip_status = CipEthernetLinkInit();
+  OPENER_ASSERT(kEipStatusOk == eip_status);
+  eip_status = ConnectionManagerInit(unique_connection_id);
+  OPENER_ASSERT(kEipStatusOk == eip_status);
+  eip_status = CipAssemblyInitialize();
+  OPENER_ASSERT(kEipStatusOk == eip_status);
   /* the application has to be initialized at last */
   /* the application has to be initialized at last */
-  nRetVal = IApp_Init();
-  OPENER_ASSERT(EIP_OK == nRetVal);
+  eip_status = ApplicationInitialization();
+  OPENER_ASSERT(kEipStatusOk == eip_status);
 }
 }
 
 
-void
-shutdownCIP(void)
-{
+void ShutdownCipStack(void) {
   /* First close all connections */
   /* First close all connections */
-  closeAllConnections();
+  CloseAllConnections();
   /* Than free the sockets of currently active encapsulation sessions */
   /* Than free the sockets of currently active encapsulation sessions */
-  encapShutDown();
+  EncapsulationShutDown();
   /*clean the data needed for the assembly object's attribute 3*/
   /*clean the data needed for the assembly object's attribute 3*/
-  shutdownAssemblies();
+  ShutdownAssemblies();
 
 
-  shutdownTCPIP_Interface();
+  ShutdownTcpIpInterface();
 
 
   /*no clear all the instances and classes */
   /*no clear all the instances and classes */
-  deleteAllClasses();
+  DeleteAllClasses();
 }
 }
 
 
-EIP_STATUS
-notifyClass(S_CIP_Class * pt2Class, S_CIP_MR_Request * pa_MRRequest,
-    S_CIP_MR_Response * pa_MRResponse)
-{
+EipStatus NotifyClass(CipClass *cip_class,
+                      CipMessageRouterRequest *message_router_request,
+                      CipMessageRouterResponse *message_router_response) {
   int i;
   int i;
-  S_CIP_Instance *pstInstance;
-  S_CIP_service_struct *p;
-  unsigned instNr; /* my instance number */
+  CipInstance *instance;
+  CipServiceStruct *service;
+  unsigned instance_number; /* my instance number */
 
 
   /* find the instance: if instNr==0, the class is addressed, else find the instance */
   /* find the instance: if instNr==0, the class is addressed, else find the instance */
-  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 */
+  instance_number = message_router_request->request_path.instance_number; /* get the instance number */
+  instance = GetCipInstance(cip_class, instance_number); /* look up the instance (note that if inst==0 this will be the class itself) */
+  if (instance) /* if instance is found */
+  {
+    OPENER_TRACE_INFO("notify: found instance %d%s\n", instance_number,
+                      instance_number == 0 ? " (class object)" : "");
+
+    service = instance->cip_class->services; /* get pointer to array of services */
+    if (service) /* if services are defined */
     {
     {
-      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 < instance->cip_class->number_of_services; i++) /* seach the services list */
+      {
+        if (message_router_request->service == service->service_number) /* if match is found */
         {
         {
-          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 */
-                {
-                  /* call the service, and return what it returns */
-                  OPENER_TRACE_INFO("notify: calling %s service\n", p->name);
-                  OPENER_ASSERT(NULL != p->m_ptfuncService);
-                  return p->m_ptfuncService(pstInstance, pa_MRRequest,
-                      pa_MRResponse);
-                }
-              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;*/
+          /* call the service, and return what it returns */
+          OPENER_TRACE_INFO("notify: calling %s service\n", service->name);
+          OPENER_ASSERT(NULL != service->service_function);
+          return service->service_function(instance, message_router_request,
+                                           message_router_response);
+        } else {
+          service++;
+        }
+      }
     }
     }
+    OPENER_TRACE_WARN("notify: service 0x%x not supported\n",
+                      message_router_request->service);
+    message_router_response->general_status = kCipErrorServiceNotSupported; /* if no services or service not found, return an error reply*/
+  } else {
+    OPENER_TRACE_WARN("notify: instance number %d unknown\n", instance_number);
+    /* if instance not found, return an error reply*/
+    message_router_response->general_status = kCipErrorPathDestinationUnknown; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
+  }
 
 
   /* handle error replies*/
   /* 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 */
+  message_router_response->size_of_additional_status = 0; /* fill in the rest of the reply with not much of anything*/
+  message_router_response->data_length = 0;
+  message_router_response->reply_service = (0x80
+      | message_router_request->service); /* except the reply code is an echo of the command + the reply flag */
 
 
-  return EIP_OK_SEND;
+  return kEipStatusOkSend;
 }
 }
 
 
-S_CIP_Instance *
-addCIPInstances(S_CIP_Class * pa_pstCIPClass, int pa_nNr_of_Instances)
-{
-  S_CIP_Instance *first, *p, **pp;
+CipInstance *AddCipInstances(CipClass *cip_class, int number_of_instances) {
+  CipInstance *first_instance, *current_instance, **next_instance;
   int i;
   int i;
-  int inst = 1; /* the first instance is number 1 */
+  int instance_number = 1; /* the first instance is number 1 */
 
 
-  OPENER_TRACE_INFO("adding %d instances to class %s\n", pa_nNr_of_Instances,
-      pa_pstCIPClass->acName);
+  OPENER_TRACE_INFO("adding %d instances to class %s\n", number_of_instances,
+                    cip_class->class_name);
 
 
-  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 */
-    }
+  next_instance = &cip_class->instances; /* get address of pointer to head of chain */
+  while (*next_instance) /* as long as what pp points to is not zero */
+  {
+    next_instance = &(*next_instance)->next; /*    follow the chain until pp points to pointer that contains a zero */
+    instance_number++; /*    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*/
-  OPENER_ASSERT(NULL != p);
+  first_instance = current_instance = (CipInstance *) CipCalloc(
+      number_of_instances, sizeof(CipInstance)); /* allocate a block of memory for all created instances*/
+  OPENER_ASSERT(NULL != current_instance);
   /* fail if run out of memory */
   /* 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 */
+  cip_class->number_of_instances += number_of_instances; /* add the number of instances just created to the total recorded by the class */
 
 
-      p->nInstanceNr = inst; /* assign the next sequential instance number */
-      p->pstClass = pa_pstCIPClass; /* point each instance to its class */
+  for (i = 0; i < number_of_instances; i++) /* initialize all the new instances */
+  {
+    *next_instance = current_instance; /* link the previous pointer to this new node */
 
 
-      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));
-        }
+    current_instance->instance_number = instance_number; /* assign the next sequential instance number */
+    current_instance->cip_class = cip_class; /* point each instance to its class */
 
 
-      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*/
+    if (cip_class->number_of_attributes) /* if the class calls for instance attributes */
+    { /* then allocate storage for the attribute array */
+      current_instance->attributes = (CipAttributeStruct*) CipCalloc(
+          cip_class->number_of_attributes, sizeof(CipAttributeStruct));
     }
     }
 
 
-  return first;
-}
-
-S_CIP_Instance *
-addCIPInstance(S_CIP_Class * pa_pstCIPClass, EIP_UINT32 pa_nInstanceId)
-{
-  S_CIP_Instance *pstInstance = getCIPInstance(pa_pstCIPClass, pa_nInstanceId);
+    next_instance = &current_instance->next; /* update pp to point to the next link of the current node */
+    instance_number++; /* update to the number of the next node*/
+    current_instance++; /* point to the next node in the calloc'ed array*/
+  }
 
 
-  if (0 == pstInstance)
-    { /*we have no instance with given id*/
-      pstInstance = addCIPInstances(pa_pstCIPClass, 1);
-      pstInstance->nInstanceNr = pa_nInstanceId;
-    }
-  return pstInstance;
+  return first_instance;
 }
 }
 
 
-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 */
+CipInstance *AddCIPInstance(CipClass *class, EipUint32 instance_id) {
+  CipInstance *instance = GetCipInstance(class, instance_id);
 
 
-  OPENER_TRACE_INFO("creating class '%s' with id: 0x%"PRIX32"\n", pa_acName, pa_nClassID);
+  if (0 == instance) { /*we have no instance with given id*/
+    instance = AddCipInstances(class, 1);
+    instance->instance_number = instance_id;
+  }
+  return instance;
+}
 
 
-  pt2Class = getCIPClass(pa_nClassID); /* check if an class with the ClassID already exists */
-  OPENER_ASSERT(NULL == pt2Class);
+CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
+                         EipUint32 get_all_class_attributes_mask,
+                         int number_of_class_services,
+                         int number_of_instance_attributes,
+                         EipUint32 get_all_instance_attributes_mask,
+                         int number_of_instance_services,
+                         int number_of_instances, char *name,
+                         EipUint16 revision) {
+  CipClass *class; /* pointer to the class struct */
+  CipClass *meta_class; /* pointer to the metaclass struct */
+
+  OPENER_TRACE_INFO("creating class '%s' with id: 0x%"PRIX32"\n", name,
+                    class_id);
+
+  class = GetCipClass(class_id); /* check if an class with the ClassID already exists */
+  OPENER_ASSERT(NULL == class);
   /* should never try to redefine a class*/
   /* should never try to redefine a class*/
 
 
   /* a metaClass is a class that holds the class attributes and services
   /* a metaClass is a class that holds the class attributes and services
@@ -203,670 +193,632 @@ createCIPClass(EIP_UINT32 pa_nClassID, int pa_nNr_of_ClassAttributes,
    and contains a pointer to a metaclass
    and contains a pointer to a metaclass
    CIP never explicitly addresses a metaclass*/
    CIP never explicitly addresses a metaclass*/
 
 
-  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*/
+  class = (CipClass*) CipCalloc(1, sizeof(CipClass)); /* create the class object*/
+  meta_class = (CipClass*) CipCalloc(1, sizeof(CipClass)); /* create the metaclass object*/
 
 
   /* initialize the class-specific fields of the Class struct*/
   /* initialize the class-specific fields of the Class struct*/
-  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
-      + ((0 == pa_nInstGetAttrAllMask) ? 1 : 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 + 7; /* 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
-      + ((0 == pa_nClassGetAttrAllMask) ? 1 : 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);
+  class->class_id = class_id; /* the class remembers the class ID */
+  class->revision = revision; /* the class remembers the class ID */
+  class->number_of_instances = 0; /* the number of instances initially zero (more created below) */
+  class->instances = 0;
+  class->number_of_attributes = number_of_instance_attributes; /* the class remembers the number of instances of that class */
+  class->get_attribute_all_mask = get_all_instance_attributes_mask; /* indicate which attributes are included in instance getAttributeAll */
+  class->number_of_services = number_of_instance_services
+      + ((0 == get_all_instance_attributes_mask) ? 1 : 2); /* the class manages the behavior of the instances */
+  class->services = 0;
+  class->class_name = name; /* initialize the class-specific fields of the metaClass struct */
+  meta_class->class_id = 0xffffffff; /* set metaclass ID (this should never be referenced) */
+  meta_class->number_of_instances = 1; /* the class object is the only instance of the metaclass */
+  meta_class->instances = (CipInstance *) class;
+  meta_class->number_of_attributes = number_of_class_attributes + 7; /* the metaclass remembers how many class attributes exist*/
+  meta_class->get_attribute_all_mask = get_all_class_attributes_mask; /* indicate which attributes are included in class getAttributeAll*/
+  meta_class->number_of_services = number_of_class_services
+      + ((0 == get_all_class_attributes_mask) ? 1 : 2); /* the metaclass manages the behavior of the class itself */
+  class->services = 0;
+  meta_class->class_name = (char *) CipCalloc(1, strlen(name) + 6); /* fabricate the name "meta<classname>"*/
+  strcpy(meta_class->class_name, "meta-");
+  strcat(meta_class->class_name, name);
 
 
   /* initialize the instance-specific fields of the Class struct*/
   /* initialize the instance-specific fields of the Class struct*/
-  pt2Class->m_stSuper.nInstanceNr = 0; /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
-  pt2Class->m_stSuper.pstAttributes = 0; /* this will later point to the class attibutes*/
-  pt2Class->m_stSuper.pstClass = pt2MetaClass; /* the class's class is the metaclass (like SmallTalk)*/
-  pt2Class->m_stSuper.pstNext = 0; /* the next link will always be zero, sinc there is only one instance of any particular class object */
+  class->m_stSuper.instance_number = 0; /* the class object is instance zero of the class it describes (weird, but that's the spec)*/
+  class->m_stSuper.attributes = 0; /* this will later point to the class attibutes*/
+  class->m_stSuper.cip_class = meta_class; /* the class's class is the metaclass (like SmallTalk)*/
+  class->m_stSuper.next = 0; /* the next link will always be zero, sinc there is only one instance of any particular class object */
 
 
-  pt2MetaClass->m_stSuper.nInstanceNr = 0xffffffff; /*the metaclass object does not really have a valid instance number*/
-  pt2MetaClass->m_stSuper.pstAttributes = 0; /* the metaclass has no attributes*/
-  pt2MetaClass->m_stSuper.pstClass = 0; /* the metaclass has no class*/
-  pt2MetaClass->m_stSuper.pstNext = 0; /* the next link will always be zero, since there is only one instance of any particular metaclass object*/
+  meta_class->m_stSuper.instance_number = 0xffffffff; /*the metaclass object does not really have a valid instance number*/
+  meta_class->m_stSuper.attributes = 0; /* the metaclass has no attributes*/
+  meta_class->m_stSuper.cip_class = 0; /* the metaclass has no class*/
+  meta_class->m_stSuper.next = 0; /* the next link will always be zero, since there is only one instance of any particular metaclass object*/
 
 
   /* further initialization of the class object*/
   /* further initialization of the class object*/
 
 
-  pt2Class->m_stSuper.pstAttributes = (S_CIP_attribute_struct *) IApp_CipCalloc(
-      pt2MetaClass->nNr_of_Attributes, sizeof(S_CIP_attribute_struct));
+  class->m_stSuper.attributes = (CipAttributeStruct *) CipCalloc(
+      meta_class->number_of_attributes, sizeof(CipAttributeStruct));
   /* TODO -- check that we didn't run out of memory?*/
   /* TODO -- check that we didn't run out of memory?*/
 
 
-  pt2MetaClass->pstServices = (S_CIP_service_struct *) IApp_CipCalloc(
-      pt2MetaClass->nNr_of_Services, sizeof(S_CIP_service_struct));
+  meta_class->services = (CipServiceStruct *) CipCalloc(
+      meta_class->number_of_services, sizeof(CipServiceStruct));
 
 
-  pt2Class->pstServices = (S_CIP_service_struct *) IApp_CipCalloc(
-      pt2Class->nNr_of_Services, sizeof(S_CIP_service_struct));
+  class->services = (CipServiceStruct *) CipCalloc(class->number_of_services,
+                                                   sizeof(CipServiceStruct));
 
 
-  if (pa_nNr_of_Instances > 0)
-    {
-      addCIPInstances(pt2Class, pa_nNr_of_Instances); /*TODO handle return value and clean up if necessary*/
-    }
+  if (number_of_instances > 0) {
+    AddCipInstances(class, number_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*/
-    }
+  if ((RegisterClass(class)) == kEipStatusError) { /* no memory to register class in Message Router */
+    return 0; /*TODO handle return value and clean up if necessary*/
+  }
 
 
   /* create the standard class attributes*/
   /* create the standard class attributes*/
-  insertAttribute((S_CIP_Instance *) pt2Class, 1, CIP_UINT,
-      (void *) &pt2Class->nRevision, CIP_ATTRIB_GETABLE); /* revision */
-  insertAttribute((S_CIP_Instance *) pt2Class, 2, CIP_UINT,
-      (void *) &pt2Class->nNr_of_Instances, CIP_ATTRIB_GETABLE); /*  largest instance number */
-  insertAttribute((S_CIP_Instance *) pt2Class, 3, CIP_UINT,
-      (void *) &pt2Class->nNr_of_Instances, CIP_ATTRIB_GETABLE); /* number of instances currently existing*/
-  insertAttribute((S_CIP_Instance *) pt2Class, 4, CIP_UINT,
-      (void *) &cg_unCIPUINTZERO, CIP_ATTRIB_GETABLEALL); /* optional attribute list - default = 0 */
-  insertAttribute((S_CIP_Instance *) pt2Class, 5, CIP_UINT,
-      (void *) &cg_unCIPUINTZERO, CIP_ATTRIB_GETABLEALL); /* optional service list - default = 0 */
-  insertAttribute((S_CIP_Instance *) pt2Class, 6, CIP_UINT,
-      (void *) &pt2MetaClass->nMaxAttribute, CIP_ATTRIB_GETABLE); /* max class attribute number*/
-  insertAttribute((S_CIP_Instance *) pt2Class, 7, CIP_UINT,
-      (void *) &pt2Class->nMaxAttribute, CIP_ATTRIB_GETABLE); /* max instance attribute number*/
+  InsertAttribute((CipInstance *) class, 1, kCipUint, (void *) &class->revision,
+                  kGetableSingleAndAll); /* revision */
+  InsertAttribute((CipInstance *) class, 2, kCipUint,
+                  (void *) &class->number_of_instances, kGetableSingleAndAll); /*  largest instance number */
+  InsertAttribute((CipInstance *) class, 3, kCipUint,
+                  (void *) &class->number_of_instances, kGetableSingleAndAll); /* number of instances currently existing*/
+  InsertAttribute((CipInstance *) class, 4, kCipUint, (void *) &kCipUintZero,
+                  kGetableAll); /* optional attribute list - default = 0 */
+  InsertAttribute((CipInstance *) class, 5, kCipUint, (void *) &kCipUintZero,
+                  kGetableAll); /* optional service list - default = 0 */
+  InsertAttribute((CipInstance *) class, 6, kCipUint,
+                  (void *) &meta_class->highest_attribute_number,
+                  kGetableSingleAndAll); /* max class attribute number*/
+  InsertAttribute((CipInstance *) class, 7, kCipUint,
+                  (void *) &class->highest_attribute_number,
+                  kGetableSingleAndAll); /* max instance attribute number*/
 
 
   /* create the standard class services*/
   /* create the standard class services*/
-  if (0 != pa_nClassGetAttrAllMask)
-    { /*only if the mask has values add the get_attribute_all service */
-      insertService(pt2MetaClass, CIP_GET_ATTRIBUTE_ALL, &getAttributeAll,
-          "GetAttributeAll"); /* bind instance services to the metaclass*/
-    }
-  insertService(pt2MetaClass, CIP_GET_ATTRIBUTE_SINGLE, &getAttributeSingle,
-      "GetAttributeSingle");
+  if (0 != get_all_class_attributes_mask) { /*only if the mask has values add the get_attribute_all service */
+    InsertService(meta_class, kGetAttributeAll, &GetAttributeAll,
+                  "GetAttributeAll"); /* bind instance services to the metaclass*/
+  }
+  InsertService(meta_class, kGetAttributeSingle, &GetAttributeSingle,
+                "GetAttributeSingle");
 
 
   /* create the standard instance services*/
   /* create the standard instance services*/
-  if (0 != pa_nInstGetAttrAllMask)
-    { /*only if the mask has values add the get_attribute_all service */
-      insertService(pt2Class, CIP_GET_ATTRIBUTE_ALL, &getAttributeAll,
-          "GetAttributeAll"); /* bind instance services to the class*/
-    }
-  insertService(pt2Class, CIP_GET_ATTRIBUTE_SINGLE, &getAttributeSingle,
-      "GetAttributeSingle");
+  if (0 != get_all_instance_attributes_mask) { /*only if the mask has values add the get_attribute_all service */
+    InsertService(class, kGetAttributeAll, &GetAttributeAll, "GetAttributeAll"); /* bind instance services to the class*/
+  }
+  InsertService(class, kGetAttributeSingle, &GetAttributeSingle,
+                "GetAttributeSingle");
 
 
-  return pt2Class;
+  return class;
 }
 }
 
 
-void
-insertAttribute(S_CIP_Instance * pa_pInstance, EIP_UINT16 pa_nAttributeNr,
-    EIP_UINT8 pa_nCIP_Type, void *pa_pt2data, EIP_BYTE pa_bCIP_Flags)
-{
+void InsertAttribute(CipInstance *instance, EipUint16 attribute_number,
+                     EipUint8 cip_type, void *data, EipByte cip_flags) {
   int i;
   int i;
-  S_CIP_attribute_struct *p;
+  CipAttributeStruct *attribute;
 
 
-  p = pa_pInstance->pstAttributes;
-  OPENER_ASSERT(NULL != p);
+  attribute = instance->attributes;
+  OPENER_ASSERT(NULL != attribute);
   /* adding a attribute to a class that was not declared to have any attributes is not allowed */
   /* adding a attribute to a class that was not declared to have any attributes is not allowed */
-  for (i = 0; i < 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->CIP_AttributeFlags = pa_bCIP_Flags;
-          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++;
+  for (i = 0; i < instance->cip_class->number_of_attributes; i++) {
+    if (attribute->data == 0) { /* found non set attribute */
+      attribute->attribute_number = attribute_number;
+      attribute->type = cip_type;
+      attribute->attribute_flags = cip_flags;
+      attribute->data = data;
+
+      if (attribute_number > instance->cip_class->highest_attribute_number) /* remember the max attribute number that was defined*/
+      {
+        instance->cip_class->highest_attribute_number = attribute_number;
+      }
+      return;
     }
     }
+    attribute++;
+  }
 
 
-  OPENER_TRACE_ERR("Tried to insert to many attributes into class: %"PRIu32", instance %"PRIu32"\n", pa_pInstance->pstClass->m_stSuper.nInstanceNr, pa_pInstance->nInstanceNr );
+  OPENER_TRACE_ERR(
+      "Tried to insert to many attributes into class: %"PRIu32", instance %"PRIu32"\n",
+      instance->cip_class->m_stSuper.instance_number,
+      instance->instance_number);
   OPENER_ASSERT(0);
   OPENER_ASSERT(0);
   /* trying to insert too many attributes*/
   /* trying to insert too many attributes*/
 }
 }
 
 
-void
-insertService(S_CIP_Class * pa_pClass, EIP_UINT8 pa_nServiceNr,
-    TCIPServiceFunc pa_ptfuncService, char *name)
-{
+void InsertService(CipClass * class, EipUint8 service_number,
+                   CipServiceFunction service_function, char *service_name) {
   int i;
   int i;
-  S_CIP_service_struct *p;
+  CipServiceStruct *p;
 
 
-  p = pa_pClass->pstServices; /* get a pointer to the service array*/
-  OPENER_ASSERT(p!=0);
+  p = class->services; /* get a pointer to the service array*/
+  OPENER_ASSERT(p != 0);
   /* adding a service to a class that was not declared to have services is not allowed*/
   /* adding a service to a class that was not declared to have services is not allowed*/
-  for (i = 0; i < pa_pClass->nNr_of_Services; i++) /* Iterate over all service slots attached to the class */
+  for (i = 0; i < class->number_of_services; i++) /* Iterate over all service slots attached to the class */
+  {
+    if (p->service_number == service_number || p->service_function == 0) /* found undefined service slot*/
     {
     {
-      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++;
+      p->service_number = service_number; /* fill in service number*/
+      p->service_function = service_function; /* fill in function address*/
+      p->name = service_name;
+      return;
     }
     }
+    p++;
+  }
   OPENER_ASSERT(0);
   OPENER_ASSERT(0);
   /* adding more services than were declared is a no-no*/
   /* adding more services than were declared is a no-no*/
 }
 }
 
 
-S_CIP_attribute_struct *
-getAttribute(S_CIP_Instance * pa_pInstance, EIP_UINT16 pa_nAttributeNr)
-{
+CipAttributeStruct *GetCipAttribute(CipInstance * instance,
+                                    EipUint16 attribute_number) {
   int i;
   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++;
-    }
+  CipAttributeStruct *attribute = instance->attributes; /* init pointer to array of attributes*/
+  for (i = 0; i < instance->cip_class->number_of_attributes; i++) {
+    if (attribute_number == attribute->attribute_number)
+      return attribute;
+    else
+      attribute++;
+  }
 
 
-  OPENER_TRACE_WARN("attribute %d not defined\n", pa_nAttributeNr);
+  OPENER_TRACE_WARN("attribute %d not defined\n", attribute_number);
 
 
   return 0;
   return 0;
 }
 }
 
 
 /* TODO this needs to check for buffer overflow*/
 /* TODO this needs to check for buffer overflow*/
-EIP_STATUS
-getAttributeSingle(S_CIP_Instance *pa_pstInstance,
-    S_CIP_MR_Request *pa_pstMRRequest, S_CIP_MR_Response *pa_pstMRResponse)
-{
+EipStatus GetAttributeSingle(CipInstance *instance,
+                             CipMessageRouterRequest *message_router_request,
+                             CipMessageRouterResponse *message_router_response) {
   /* Mask for filtering get-ability */
   /* Mask for filtering get-ability */
-  EIP_BYTE nMask;
+  EipByte get_mask;
 
 
-  S_CIP_attribute_struct *p = getAttribute(pa_pstInstance,
-      pa_pstMRRequest->RequestPath.AttributNr);
-  EIP_BYTE *paMsg = pa_pstMRResponse->Data;
+  CipAttributeStruct *attribute = GetCipAttribute(
+      instance, message_router_request->request_path.attribute_number);
+  EipByte *message = message_router_response->data;
 
 
-  pa_pstMRResponse->DataLength = 0;
-  pa_pstMRResponse->ReplyService = (0x80 | pa_pstMRRequest->Service);
-  pa_pstMRResponse->GeneralStatus = CIP_ERROR_ATTRIBUTE_NOT_SUPPORTED;
-  pa_pstMRResponse->SizeofAdditionalStatus = 0;
+  message_router_response->data_length = 0;
+  message_router_response->reply_service = (0x80
+      | message_router_request->service);
+  message_router_response->general_status = kCipErrorAttributeNotSupported;
+  message_router_response->size_of_additional_status = 0;
 
 
   /* set filter according to service: get_attribute_all or get_attribute_single */
   /* set filter according to service: get_attribute_all or get_attribute_single */
-  if (CIP_GET_ATTRIBUTE_ALL == pa_pstMRRequest->Service) {
-      nMask = CIP_ATTRIB_GETABLEALL;
-      pa_pstMRResponse->GeneralStatus = CIP_ERROR_SUCCESS;
+  if (kGetAttributeAll == message_router_request->service) {
+    get_mask = kGetableAll;
+    message_router_response->general_status = kCipErrorSuccess;
   } else {
   } else {
-      nMask = CIP_ATTRIB_GETABLESINGLE;
+    get_mask = kGetableSingle;
   }
   }
 
 
-  if ((p != 0) && (p->pt2data != 0))
-    {
-      if (p->CIP_AttributeFlags & nMask) {
-         OPENER_TRACE_INFO("getAttribute %d\n",
-         pa_pstMRRequest->RequestPath.AttributNr); /* create a reply message containing the data*/
-
-         /*TODO think if it is better to put this code in an own
-          * getAssemblyAttributeSingle functions which will call get attribute
-          * single.
-          */
-
-         if(p->CIP_Type == CIP_BYTE_ARRAY
-            && pa_pstInstance->pstClass->nClassID == CIP_ASSEMBLY_CLASS_CODE)
-           {
-              /* we are getting a byte array of a assembly object, kick out to the app callback */
-              OPENER_TRACE_INFO(" -> getAttributeSingle CIP_BYTE_ARRAY\r\n");
-              IApp_BeforeAssemblyDataSend(pa_pstInstance);
-            }
-
-         pa_pstMRResponse->DataLength = encodeData(p->CIP_Type, p->pt2data,
-           &paMsg);
-         pa_pstMRResponse->GeneralStatus = CIP_ERROR_SUCCESS;
+  if ((attribute != 0) && (attribute->data != 0)) {
+    if (attribute->attribute_flags & get_mask) {
+      OPENER_TRACE_INFO("getAttribute %d\n",
+                        message_router_request->request_path.attribute_number); /* create a reply message containing the data*/
+
+      /*TODO think if it is better to put this code in an own
+       * getAssemblyAttributeSingle functions which will call get attribute
+       * single.
+       */
+
+      if (attribute->type == kCipByteArray
+          && instance->cip_class->class_id == kCipAssemblyClassCode) {
+        /* we are getting a byte array of a assembly object, kick out to the app callback */
+        OPENER_TRACE_INFO(" -> getAttributeSingle CIP_BYTE_ARRAY\r\n");
+        BeforeAssemblyDataSend(instance);
       }
       }
+
+      message_router_response->data_length = EncodeData(attribute->type,
+                                                        attribute->data,
+                                                        &message);
+      message_router_response->general_status = kCipErrorSuccess;
     }
     }
+  }
 
 
-  return EIP_OK_SEND;
+  return kEipStatusOkSend;
 }
 }
 
 
-int
-encodeData(EIP_UINT8 pa_nCIP_Type, void *pa_pt2data, EIP_UINT8 **pa_pnMsg)
-{
+int EncodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
   int counter = 0;
   int counter = 0;
-  S_CIP_Byte_Array *p;
 
 
-  switch (pa_nCIP_Type)
-    /* check the datatype of attribute */
-    {
-  case (CIP_BOOL):
-  case (CIP_SINT):
-  case (CIP_USINT):
-  case (CIP_BYTE):
-    **pa_pnMsg = *(EIP_UINT8 *) (pa_pt2data);
-    ++(*pa_pnMsg);
-    counter = 1;
-    break;
-
-  case (CIP_INT):
-  case (CIP_UINT):
-  case (CIP_WORD):
-    htols(*(EIP_UINT16 *) (pa_pt2data), pa_pnMsg);
-    counter = 2;
-    break;
-
-  case (CIP_DINT):
-  case (CIP_UDINT):
-  case (CIP_DWORD):
-  case (CIP_REAL):
-    htoll(*(EIP_UINT32 *) (pa_pt2data), pa_pnMsg);
-    counter = 4;
-    break;
+  switch (cip_type)
+  /* check the data type of attribute */
+  {
+    case (kCipBool):
+    case (kCipSint):
+    case (kCipUsint):
+    case (kCipByte):
+      **message = *(EipUint8 *) (data);
+      ++(*message);
+      counter = 1;
+      break;
 
 
-#ifdef OPENER_SUPPORT_64BIT_DATATYPES
-  case (CIP_LINT):
-  case (CIP_ULINT):
-  case (CIP_LWORD):
-  case (CIP_LREAL):
-    htol64(*(EIP_UINT64 *) (pa_pt2data), pa_pnMsg);
-    counter = 8;
-    break;
-#endif
+    case (kCipInt):
+    case (kCipUint):
+    case (kCipWord):
+      AddIntToMessage(*(EipUint16 *) (data), message);
+      counter = 2;
+      break;
 
 
-  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_pt2data;
+    case (kCipDint):
+    case (kCipUdint):
+    case (kCipDword):
+    case (kCipReal):
+      AddDintToMessage(*(EipUint32 *) (data), message);
+      counter = 4;
+      break;
 
 
-      htols(*(EIP_UINT16 *) &(s->Length), pa_pnMsg);
-      memcpy(*pa_pnMsg, s->String, s->Length);
-      *pa_pnMsg += s->Length;
+#ifdef OPENER_SUPPORT_64BIT_DATATYPES
+    case (kCipLint):
+    case (kCipUlint):
+    case (kCipLword):
+    case (kCipLreal):
+      AddLintToMessage(*(EipUint64 *) (data), message);
+      counter = 8;
+      break;
+#endif
 
 
-      counter = s->Length + 2; /* we have a two byte length field */
-      if (counter & 0x01)
-        {
-          /* we have an odd byte count */
-          **pa_pnMsg = 0;
-          ++(*pa_pnMsg);
-          counter++;
-        }
+    case (kCipStime):
+    case (kCipDate):
+    case (kCipTimeOfDay):
+    case (kCipDateAndTime):
+      break;
+    case (kCipString): {
+      CipString *string = (CipString *) data;
+
+      AddIntToMessage(*(EipUint16 *) &(string->length), message);
+      memcpy(*message, string->string, string->length);
+      *message += string->length;
+
+      counter = string->length + 2; /* we have a two byte length field */
+      if (counter & 0x01) {
+        /* we have an odd byte count */
+        **message = 0;
+        ++(*message);
+        counter++;
+      }
       break;
       break;
     }
     }
-  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_pt2data;
+    case (kCipString2):
+    case (kCipFtime):
+    case (kCipLtime):
+    case (kCipItime):
+    case (kCipStringN):
+      break;
 
 
-      **pa_pnMsg = ss->Length;
-      ++(*pa_pnMsg);
+    case (kCipShortString): {
+      CipShortString *short_string = (CipShortString *) data;
 
 
-      memcpy(*pa_pnMsg, ss->String, ss->Length);
-      *pa_pnMsg += ss->Length;
+      **message = short_string->length;
+      ++(*message);
 
 
-      counter = ss->Length + 1;
+      memcpy(*message, short_string->string, short_string->length);
+      *message += short_string->length;
+
+      counter = short_string->length + 1;
       break;
       break;
     }
     }
 
 
-  case (CIP_TIME):
-    break;
+    case (kCipTime):
+      break;
 
 
-  case (CIP_EPATH):
-    counter = encodeEPath((S_CIP_EPATH *) pa_pt2data, pa_pnMsg);
-    break;
+    case (kCipEpath):
+      counter = EncodeEPath((CipEpath *) data, message);
+      break;
 
 
-  case (CIP_ENGUNIT):
-    break;
+    case (kCipEngUnit):
+      break;
 
 
-  case (CIP_USINT_USINT):
-    {
-      S_CIP_Revision *rv = (S_CIP_Revision *) pa_pt2data;
+    case (kCipUsintUsint): {
+      CipRevision *revision = (CipRevision *) data;
 
 
-      **pa_pnMsg = rv->MajorRevision;
-      ++(*pa_pnMsg);
-      **pa_pnMsg = rv->MinorRevision;
-      ++(*pa_pnMsg);
+      **message = revision->major_revision;
+      ++(*message);
+      **message = revision->minor_revision;
+      ++(*message);
       counter = 2;
       counter = 2;
       break;
       break;
     }
     }
 
 
-  case (CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING):
-    {
+    case (kCipUdintUdintUdintUdintUdintString): {
       /* TCP/IP attribute 5 */
       /* TCP/IP attribute 5 */
-      S_CIP_TCPIPNetworkInterfaceConfiguration *p =
-          (S_CIP_TCPIPNetworkInterfaceConfiguration *) pa_pt2data;
-      htoll(ntohl(p->IPAddress), pa_pnMsg);
-      htoll(ntohl(p->NetworkMask), pa_pnMsg);
-      htoll(ntohl(p->Gateway), pa_pnMsg);
-      htoll(ntohl(p->NameServer), pa_pnMsg);
-      htoll(ntohl(p->NameServer2), pa_pnMsg);
+      CipTcpIpNetworkInterfaceConfiguration *tcp_ip_network_interface_configuration =
+          (CipTcpIpNetworkInterfaceConfiguration *) data;
+      AddDintToMessage(
+          ntohl(tcp_ip_network_interface_configuration->ip_address), message);
+      AddDintToMessage(
+          ntohl(tcp_ip_network_interface_configuration->network_mask), message);
+      AddDintToMessage(ntohl(tcp_ip_network_interface_configuration->gateway),
+                       message);
+      AddDintToMessage(
+          ntohl(tcp_ip_network_interface_configuration->name_server), message);
+      AddDintToMessage(
+          ntohl(tcp_ip_network_interface_configuration->name_server_2),
+          message);
       counter = 20;
       counter = 20;
-      counter += encodeData(CIP_STRING, &(p->DomainName), pa_pnMsg);
+      counter += EncodeData(
+          kCipString, &(tcp_ip_network_interface_configuration->domain_name),
+          message);
       break;
       break;
     }
     }
 
 
-  case (CIP_6USINT):
-    {
-      EIP_UINT8 *p = (EIP_UINT8 *) pa_pt2data;
-      memcpy(*pa_pnMsg, p, 6);
+    case (kCip6Usint): {
+      EipUint8 *p = (EipUint8 *) data;
+      memcpy(*message, p, 6);
       counter = 6;
       counter = 6;
       break;
       break;
     }
     }
 
 
-  case (CIP_MEMBER_LIST):
-    break;
+    case (kCipMemberList):
+      break;
 
 
-  case (CIP_BYTE_ARRAY):
-    {
+    case (kCipByteArray): {
+      CipByteArray *cip_byte_array;
       OPENER_TRACE_INFO(" -> get attribute byte array\r\n");
       OPENER_TRACE_INFO(" -> get attribute byte array\r\n");
-      p = (S_CIP_Byte_Array *) pa_pt2data;
-      memcpy(*pa_pnMsg, p->Data, p->len);
-      *pa_pnMsg += p->len;
-      counter = p->len;
+      cip_byte_array = (CipByteArray *) data;
+      memcpy(*message, cip_byte_array->data, cip_byte_array->length);
+      *message += cip_byte_array->length;
+      counter = cip_byte_array->length;
     }
     }
-    break;
+      break;
 
 
-  case (INTERNAL_UINT16_6): /* TODO for port class attribute 9, hopefully we can find a better way to do this*/
+    case (kInternalUint6): /* TODO for port class attribute 9, hopefully we can find a better way to do this*/
     {
     {
-      EIP_UINT16 *p = (EIP_UINT16 *) pa_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);
+      EipUint16 *internal_unit16_6 = (EipUint16 *) data;
+
+      AddIntToMessage(internal_unit16_6[0], message);
+      AddIntToMessage(internal_unit16_6[1], message);
+      AddIntToMessage(internal_unit16_6[2], message);
+      AddIntToMessage(internal_unit16_6[3], message);
+      AddIntToMessage(internal_unit16_6[4], message);
+      AddIntToMessage(internal_unit16_6[5], message);
       counter = 12;
       counter = 12;
       break;
       break;
     }
     }
-  default:
-    break;
+    default:
+      break;
 
 
-    }
+  }
 
 
   return counter;
   return counter;
 }
 }
 
 
-int
-decodeData(EIP_UINT8 pa_nCIP_Type, void *pa_pt2data, EIP_UINT8 **pa_pnMsg)
-{
-  int nRetVal = -1;
+int DecodeData(EipUint8 cip_type, void *data, EipUint8 **message) {
+  int number_of_decoded_bytes = -1;
+
+  switch (cip_type)
+  /* check the data type of attribute */
+  {
+    case (kCipBool):
+    case (kCipSint):
+    case (kCipUsint):
+    case (kCipByte):
+      *(EipUint8 *) (data) = **message;
+      ++(*message);
+      number_of_decoded_bytes = 1;
+      break;
+
+    case (kCipInt):
+    case (kCipUint):
+    case (kCipWord):
+      (*(EipUint16 *) (data)) = GetIntFromMessage(message);
+      number_of_decoded_bytes = 2;
+      break;
 
 
-  switch (pa_nCIP_Type)
-    /* check the datatype of attribute */
-    {
-  case (CIP_BOOL):
-  case (CIP_SINT):
-  case (CIP_USINT):
-  case (CIP_BYTE):
-    *(EIP_UINT8 *) (pa_pt2data) = **pa_pnMsg;
-    ++(*pa_pnMsg);
-    nRetVal = 1;
-    break;
-
-  case (CIP_INT):
-  case (CIP_UINT):
-  case (CIP_WORD):
-    (*(EIP_UINT16 *) (pa_pt2data)) = ltohs(pa_pnMsg);
-    nRetVal = 2;
-    break;
-
-  case (CIP_DINT):
-  case (CIP_UDINT):
-  case (CIP_DWORD):
-    (*(EIP_UINT32 *) (pa_pt2data)) = ltohl(pa_pnMsg);
-    nRetVal = 4;
-    break;
+    case (kCipDint):
+    case (kCipUdint):
+    case (kCipDword):
+      (*(EipUint32 *) (data)) = GetDintFromMessage(message);
+      number_of_decoded_bytes = 4;
+      break;
 
 
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
-  case (CIP_LINT):
-  case (CIP_ULINT):
-  case (CIP_LWORD):
-    {
-      (*(EIP_UINT64 *) (pa_pt2data)) = ltoh64(pa_pnMsg);
-      nRetVal = 8;
+    case (kCipLint):
+    case (kCipUlint):
+    case (kCipLword): {
+      (*(EipUint64 *) (data)) = GetLintFromMessage(message);
+      number_of_decoded_bytes = 8;
     }
     }
-    break;
+      break;
 #endif
 #endif
 
 
-  case (CIP_STRING):
-    {
-      S_CIP_String *s = (S_CIP_String *) pa_pt2data;
-      s->Length = ltohs(pa_pnMsg);
-      memcpy(s->String, *pa_pnMsg, s->Length);
-      *pa_pnMsg += s->Length;
-
-      nRetVal = s->Length + 2; /* we have a two byte length field */
-      if (nRetVal & 0x01)
-        {
-          /* we have an odd byte count */
-          ++(*pa_pnMsg);
-          nRetVal++;
-        }
+    case (kCipString): {
+      CipString *string = (CipString *) data;
+      string->length = GetIntFromMessage(message);
+      memcpy(string->string, *message, string->length);
+      *message += string->length;
+
+      number_of_decoded_bytes = string->length + 2; /* we have a two byte length field */
+      if (number_of_decoded_bytes & 0x01) {
+        /* we have an odd byte count */
+        ++(*message);
+        number_of_decoded_bytes++;
+      }
     }
     }
-    break;
-  case (CIP_SHORT_STRING):
-    {
-      S_CIP_Short_String *ss = (S_CIP_Short_String *) pa_pt2data;
+      break;
+    case (kCipShortString): {
+      CipShortString *short_string = (CipShortString *) data;
 
 
-      ss->Length = **pa_pnMsg;
-      ++(*pa_pnMsg);
+      short_string->length = **message;
+      ++(*message);
 
 
-      memcpy(ss->String, *pa_pnMsg, ss->Length);
-      *pa_pnMsg += ss->Length;
+      memcpy(short_string->string, *message, short_string->length);
+      *message += short_string->length;
 
 
-      nRetVal = ss->Length + 1;
+      number_of_decoded_bytes = short_string->length + 1;
       break;
       break;
     }
     }
 
 
-  default:
-    break;
-    }
+    default:
+      break;
+  }
 
 
-  return nRetVal;
+  return number_of_decoded_bytes;
 }
 }
 
 
-EIP_STATUS
-getAttributeAll(S_CIP_Instance * pa_pstInstance,
-    S_CIP_MR_Request * pa_stMRRequest, S_CIP_MR_Response * pa_stMRResponse)
-{
+EipStatus GetAttributeAll(CipInstance *instance,
+                          CipMessageRouterRequest *message_router_request,
+                          CipMessageRouterResponse *message_router_response) {
   int i, j;
   int i, j;
-  EIP_UINT8 *ptmp;
-  S_CIP_attribute_struct *p_attr;
-  S_CIP_service_struct *p_service;
+  EipUint8 *reply;
+  CipAttributeStruct *attribute;
+  CipServiceStruct *service;
 
 
-  ptmp = pa_stMRResponse->Data; /* 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*/
+  reply = message_router_response->data; /* pointer into the reply */
+  attribute = instance->attributes; /* pointer to list of attributes*/
+  service = instance->cip_class->services; /* pointer to list of services*/
 
 
-  if (pa_pstInstance->nInstanceNr == 2)
-    {
-      OPENER_TRACE_INFO("GetAttributeAll: instance number 2\n");
-    }
+  if (instance->instance_number == 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*/
+  for (i = 0; i < instance->cip_class->number_of_services; i++) /* hunt for the GET_ATTRIBUTE_SINGLE service*/
+  {
+    if (service->service_number == kGetAttributeSingle) /* found the service */
     {
     {
-      if (p_service->CIP_ServiceNr == CIP_GET_ATTRIBUTE_SINGLE) /* found the service */
+      if (0 == instance->cip_class->number_of_attributes) {
+        message_router_response->data_length = 0; /*there are no attributes to be sent back*/
+        message_router_response->reply_service = (0x80
+            | message_router_request->service);
+        message_router_response->general_status = kCipErrorServiceNotSupported;
+        message_router_response->size_of_additional_status = 0;
+      } else {
+        for (j = 0; j < instance->cip_class->number_of_attributes; j++) /* for each instance attribute of this class */
         {
         {
-          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;
-                      if (EIP_OK_SEND
-                          != p_service->m_ptfuncService(pa_pstInstance,
-                              pa_stMRRequest, pa_stMRResponse))
-                        {
-                          pa_stMRResponse->Data = ptmp;
-                          return EIP_ERROR;
-                        }
-                      pa_stMRResponse->Data += pa_stMRResponse->DataLength;
-                    }
-                  p_attr++;
-                }
-              pa_stMRResponse->DataLength = pa_stMRResponse->Data - ptmp;
-              pa_stMRResponse->Data = ptmp;
+          int attrNum = attribute->attribute_number;
+          if (attrNum < 32
+              && (instance->cip_class->get_attribute_all_mask & 1 << attrNum)) /* only return attributes that are flagged as being part of GetAttributeALl */
+              {
+            message_router_request->request_path.attribute_number = attrNum;
+            if (kEipStatusOkSend
+                != service->service_function(instance, message_router_request,
+                                             message_router_response)) {
+              message_router_response->data = reply;
+              return kEipStatusError;
             }
             }
-          return EIP_OK_SEND;
+            message_router_response->data += message_router_response
+                ->data_length;
+          }
+          attribute++;
         }
         }
-      p_service++;
+        message_router_response->data_length = message_router_response->data
+            - reply;
+        message_router_response->data = reply;
+      }
+      return kEipStatusOkSend;
     }
     }
-  return EIP_OK; /* Return 0 if cannot find GET_ATTRIBUTE_SINGLE service*/
+    service++;
+  }
+  return kEipStatusOk; /* Return kEipStatusOk if cannot find GET_ATTRIBUTE_SINGLE service*/
 }
 }
 
 
-int
-encodeEPath(S_CIP_EPATH *pa_pstEPath, EIP_UINT8 **pa_pnMsg)
-{
-  int nLen;
+int EncodeEPath(CipEpath *epath, EipUint8 **message) {
+  unsigned int length = epath->path_size;
+  AddIntToMessage(epath->path_size, message);
 
 
-  nLen = pa_pstEPath->PathSize;
-  htols(pa_pstEPath->PathSize, pa_pnMsg);
+  if (epath->class_id < 256) {
+    **message = 0x20; /*8Bit Class Id */
+    ++(*message);
+    **message = (EipUint8) epath->class_id;
+    ++(*message);
+    length -= 1;
+  } else {
+    **message = 0x21; /*16Bit Class Id */
+    ++(*message);
+    **message = 0; /*pad byte */
+    ++(*message);
+    AddIntToMessage(epath->class_id, message);
+    length -= 2;
+  }
 
 
-  if (pa_pstEPath->ClassID < 256)
-    {
-      **pa_pnMsg = 0x20; /*8Bit Class Id */
-      ++(*pa_pnMsg);
-      **pa_pnMsg = (EIP_UINT8) pa_pstEPath->ClassID;
-      ++(*pa_pnMsg);
-      nLen -= 1;
-    }
-  else
-    {
-      **pa_pnMsg = 0x21; /*16Bit Class Id */
-      ++(*pa_pnMsg);
-      **pa_pnMsg = 0; /*padd byte */
-      ++(*pa_pnMsg);
-      htols(pa_pstEPath->ClassID, pa_pnMsg);
-      nLen -= 2;
+  if (0 < length) {
+    if (epath->instance_number < 256) {
+      **message = 0x24; /*8Bit Instance Id */
+      ++(*message);
+      **message = (EipUint8) epath->instance_number;
+      ++(*message);
+      length -= 1;
+    } else {
+      **message = 0x25; /*16Bit Instance Id */
+      ++(*message);
+      **message = 0; /*padd byte */
+      ++(*message);
+      AddIntToMessage(epath->instance_number, message);
+      length -= 2;
     }
     }
 
 
-  if (0 < nLen)
-    {
-      if (pa_pstEPath->InstanceNr < 256)
-        {
-          **pa_pnMsg = 0x24; /*8Bit Instance Id */
-          ++(*pa_pnMsg);
-          **pa_pnMsg = (EIP_UINT8) pa_pstEPath->InstanceNr;
-          ++(*pa_pnMsg);
-          nLen -= 1;
-        }
-      else
-        {
-          **pa_pnMsg = 0x25; /*16Bit Instance Id */
-          ++(*pa_pnMsg);
-          **pa_pnMsg = 0; /*padd byte */
-          ++(*pa_pnMsg);
-          htols(pa_pstEPath->InstanceNr, pa_pnMsg);
-          nLen -= 2;
-        }
-
-      if (0 < nLen)
-        {
-          if (pa_pstEPath->AttributNr < 256)
-            {
-              **pa_pnMsg = 0x30; /*8Bit Attribute Id */
-              ++(*pa_pnMsg);
-              **pa_pnMsg = (EIP_UINT8) pa_pstEPath->AttributNr;
-              ++(*pa_pnMsg);
-              nLen -= 1;
-            }
-          else
-            {
-              **pa_pnMsg = 0x31; /*16Bit Attribute Id */
-              ++(*pa_pnMsg);
-              **pa_pnMsg = 0; /*padd byte */
-              ++(*pa_pnMsg);
-              htols(pa_pstEPath->AttributNr, pa_pnMsg);
-              nLen -= 2;
-            }
-        }
+    if (0 < length) {
+      if (epath->attribute_number < 256) {
+        **message = 0x30; /*8Bit Attribute Id */
+        ++(*message);
+        **message = (EipUint8) epath->attribute_number;
+        ++(*message);
+        length -= 1;
+      } else {
+        **message = 0x31; /*16Bit Attribute Id */
+        ++(*message);
+        **message = 0; /*pad byte */
+        ++(*message);
+        AddIntToMessage(epath->attribute_number, message);
+        length -= 2;
+      }
     }
     }
+  }
 
 
-  return 2 + pa_pstEPath->PathSize * 2; /*path size is in 16 bit chunks according to the spec */
+  return 2 + epath->path_size * 2; /* path size is in 16 bit chunks according to the specification */
 }
 }
 
 
-int
-decodePaddedEPath(S_CIP_EPATH *pa_pstEPath, EIP_UINT8 ** pa_pnMsg)
-{
-  int i;
-  EIP_UINT8 *pnRunner = *pa_pnMsg;
+int DecodePaddedEPath(CipEpath *epath, EipUint8 **message) {
+  unsigned int number_of_decoded_elements;
+  EipUint8 *message_runner = *message;
 
 
-  pa_pstEPath->PathSize = *pnRunner;
-  pnRunner++;
+  epath->path_size = *message_runner;
+  message_runner++;
   /* copy path to structure, in version 0.1 only 8 bit for Class,Instance and Attribute, need to be replaced with function */
   /* copy path to structure, in version 0.1 only 8 bit for Class,Instance and Attribute, need to be replaced with function */
-  pa_pstEPath->ClassID = 0;
-  pa_pstEPath->InstanceNr = 0;
-  pa_pstEPath->AttributNr = 0;
-
-  for (i = 0; i < pa_pstEPath->PathSize; i++)
-    {
-      if (0xE0 == ((*pnRunner) & 0xE0))
-        {
-          /*Invalid segment type*/
-          return EIP_ERROR;
-        }
+  epath->class_id = 0;
+  epath->instance_number = 0;
+  epath->attribute_number = 0;
+
+  for (number_of_decoded_elements = 0;
+      number_of_decoded_elements < epath->path_size;
+      number_of_decoded_elements++) {
+    if (kSegmentTypeReserved == ((*message_runner) & kSegmentTypeReserved)) {
+      /* If invalid/reserved segment type, segment type greater than 0xE0 */
+      return kEipStatusError;
+    }
 
 
-      switch (*pnRunner)
-        {
-      case 0x20: /* classID */
-        pa_pstEPath->ClassID = *(EIP_UINT8 *) (pnRunner + 1);
-        pnRunner += 2;
+    switch (*message_runner) {
+      case kLogicalSegment + kClassId + kEightBitValue:
+        epath->class_id = *(EipUint8 *) (message_runner + 1);
+        message_runner += 2;
         break;
         break;
 
 
-      case 0x21: /*classID 16Bit */
-        pnRunner += 2;
-        pa_pstEPath->ClassID = ltohs(&(pnRunner));
-        i++;
+      case kLogicalSegment + kClassId + kSixteenBitValue:
+        message_runner += 2;
+        epath->class_id = GetIntFromMessage(&(message_runner));
+        number_of_decoded_elements++;
         break;
         break;
 
 
-      case 0x24: /* InstanceNr */
-        pa_pstEPath->InstanceNr = *(EIP_UINT8 *) (pnRunner + 1);
-        pnRunner += 2;
+      case kLogicalSegment + kInstanceId + kEightBitValue:
+        epath->instance_number = *(EipUint8 *) (message_runner + 1);
+        message_runner += 2;
         break;
         break;
 
 
-      case 0x25: /* InstanceNr 16Bit */
-        pnRunner += 2;
-        pa_pstEPath->InstanceNr = ltohs(&(pnRunner));
-        i++;
+      case kLogicalSegment + kInstanceId + kSixteenBitValue:
+        message_runner += 2;
+        epath->instance_number = GetIntFromMessage(&(message_runner));
+        number_of_decoded_elements++;
         break;
         break;
 
 
-      case 0x30: /* AttributeNr */
-        pa_pstEPath->AttributNr = *(EIP_UINT8 *) (pnRunner + 1);
-        pnRunner += 2;
+      case kLogicalSegment + kAttributeId + kEightBitValue:
+        epath->attribute_number = *(EipUint8 *) (message_runner + 1);
+        message_runner += 2;
         break;
         break;
 
 
-      case 0x31: /* AttributeNr 16Bit */
-        pnRunner += 2;
-        pa_pstEPath->AttributNr = ltohs(&(pnRunner));
-        i++;
+      case kLogicalSegment + kAttributeId + kSixteenBitValue:
+        message_runner += 2;
+        epath->attribute_number = GetIntFromMessage(&(message_runner));
+        number_of_decoded_elements++;
         break;
         break;
 
 
       default:
       default:
         OPENER_TRACE_ERR("wrong path requested\n");
         OPENER_TRACE_ERR("wrong path requested\n");
-        return EIP_ERROR;
+        return kEipStatusError;
         break;
         break;
-        }
     }
     }
+  }
 
 
-  *pa_pnMsg = pnRunner;
-  return i * 2 + 1;
+  *message = message_runner;
+  return number_of_decoded_elements * 2 + 1; /* i times 2 as every encoding uses 2 bytes */
 }
 }

+ 27 - 22
source/src/cip/cipcommon.h

@@ -3,8 +3,8 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPCOMMON_H_
-#define CIPCOMMON_H_
+#ifndef OPENER_CIPCOMMON_H_
+#define OPENER_CIPCOMMON_H_
 
 
 /** @file cipcommon.h
 /** @file cipcommon.h
  * Common CIP object interface
  * Common CIP object interface
@@ -19,49 +19,54 @@
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    2. I/O Connections will use this buffer for the produced data
  *    2. I/O Connections will use this buffer for the produced data
  */
  */
-extern EIP_UINT8 g_acMessageDataReplyBuffer[];
+extern EipUint8 g_message_data_reply_buffer[];
 
 
 /** @brief Check if requested service present in class/instance and call appropriate service.
 /** @brief Check if requested service present in class/instance and call appropriate service.
  *
  *
- * @param pt2Class class receiving the message
- * @param pa_MRRequest request message
- * @param pa_MRResponse reply message
+ * @param class class receiving the message
+ * @param message_router_request request message
+ * @param message_router_response reply message
  * @return
  * @return
  *     - EIP_OK_SEND    ... success
  *     - EIP_OK_SEND    ... success
  *     - EIP_OK  ... no reply to send back
  *     - EIP_OK  ... no reply to send back
  *     - EIP_ERROR ... error
  *     - EIP_ERROR ... error
  */
  */
-EIP_STATUS notifyClass(S_CIP_Class *pt2Class, S_CIP_MR_Request *pa_MRRequest, S_CIP_MR_Response *pa_MRResponse);
+EipStatus NotifyClass(CipClass *class,
+                      CipMessageRouterRequest *message_router_request,
+                      CipMessageRouterResponse *message_router_response);
 
 
 /** @brief Generic implementation of the GetAttributeSingle CIP service
 /** @brief Generic implementation of the GetAttributeSingle CIP service
  *
  *
  *  Check from classID which Object requests an attribute, search if object has
  *  Check from classID which Object requests an attribute, search if object has
  *  the appropriate attribute implemented.
  *  the appropriate attribute implemented.
- * @param pa_pstInstance pointer to instance.
- * @param pa_pstMRRequest pointer to request.
- * @param pa_pstMRResponse pointer to response.
+ * @param instance pointer to instance.
+ * @param message_router_request pointer to request.
+ * @param message_router_response pointer to response.
  * @return status  >0 .. success
  * @return status  >0 .. success
  *          -1 .. requested attribute not available
  *          -1 .. requested attribute not available
  */
  */
-EIP_STATUS getAttributeSingle(S_CIP_Instance *pa_pstInstance,
-    S_CIP_MR_Request *pa_pstMRRequest, S_CIP_MR_Response *pa_pstMRResponse);
+EipStatus GetAttributeSingle(CipInstance *instance,
+                             CipMessageRouterRequest *message_router_request,
+                             CipMessageRouterResponse *message_router_response);
 
 
 /** @brief Generic implementation of the GetAttributeAll CIP service
 /** @brief Generic implementation of the GetAttributeAll CIP service
  *
  *
  * Copy all attributes from Object into the global message buffer.
  * Copy all attributes from Object into the global message buffer.
- * @param pa_pstObjectInstance pointer to object instance with data.
- * @param pa_stMRRequest pointer to MR request.
- * @param pa_stMRResponse pointer for MR response.
- * @param pa_msg pointer to global message buffer for response.
+ * @param instance pointer to object instance with data.
+ * @param message_router_request pointer to MR request.
+ * @param message_router_response pointer for MR response.
  * @return length of data stream >0 .. success
  * @return length of data stream >0 .. success
  *              0 .. no reply to send
  *              0 .. no reply to send
  */
  */
-EIP_STATUS getAttributeAll(S_CIP_Instance *pa_pstObjectInstance,
-    S_CIP_MR_Request *pa_stMRRequest, S_CIP_MR_Response *pa_stMRResponse);
+EipStatus GetAttributeAll(CipInstance *instance,
+                          CipMessageRouterRequest *message_router_request,
+                          CipMessageRouterResponse *message_router_response);
 
 
-/**
- *
+/** @brief Decodes padded EPath
+ *  @param epath EPath to the receiving element
+ *  @param message CIP Message to decode
+ *  @return Number of decoded bytes
  */
  */
-int decodePaddedEPath(S_CIP_EPATH *pa_pstEPath, EIP_UINT8 ** pa_pnData);
+int DecodePaddedEPath(CipEpath *epath, EipUint8 **data);
 
 
-#endif /*CIPCOMMON_H_*/
+#endif /* OPENER_CIPCOMMON_H_ */

文件差異過大導致無法顯示
+ 477 - 491
source/src/cip/cipconnectionmanager.c


+ 211 - 191
source/src/cip/cipconnectionmanager.h

@@ -1,267 +1,287 @@
 /*******************************************************************************
 /*******************************************************************************
  * Copyright (c) 2009, Rockwell Automation, Inc.
  * Copyright (c) 2009, Rockwell Automation, Inc.
- * All rights reserved. 
+ * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPCONNECTIONMANAGER_H_
-#define CIPCONNECTIONMANAGER_H_
+#ifndef OPENER_CIPCONNECTIONMANAGER_H_
+#define OPENER_CIPCONNECTIONMANAGER_H_
 
 
 #include "opener_user_conf.h"
 #include "opener_user_conf.h"
 #include "opener_api.h"
 #include "opener_api.h"
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
 
 
-#define CONSUMING 0           /* these are used as array indexes, watch out if changing these values */
-#define PRODUCING 1
-
-#define CIP_POINT_TO_POINT_CONNECTION 0x4000
-#define CIP_MULTICAST_CONNECTION      0x2000
-
-
-/* Connection Manager Error codes */
-#define CIP_CON_MGR_SUCCESS 0x00
-#define CIP_CON_MGR_ERROR_CONNECTION_IN_USE 0x0100
-#define CIP_CON_MGR_ERROR_TRANSPORT_TRIGGER_NOT_SUPPORTED 0x0103
-#define CIP_CON_MGR_ERROR_OWNERSHIP_CONFLICT 0x0106
-#define CIP_CON_MGR_ERROR_CONNECTION_NOT_FOUND_AT_TARGET_APPLICATION 0x0107
-#define CIP_CON_MGR_ERROR_INVALID_O_TO_T_CONNECTION_TYPE 0x123
-#define CIP_CON_MGR_ERROR_INVALID_T_TO_O_CONNECTION_TYPE 0x124
-#define CIP_CON_MGR_ERROR_INVALID_O_TO_T_CONNECTION_SIZE 0x127
-#define CIP_CON_MGR_ERROR_INVALID_T_TO_O_CONNECTION_SIZE 0x128
-#define CIP_CON_MGR_ERROR_NO_MORE_CONNECTIONS_AVAILABLE 0x0113
-#define CIP_CON_MGR_ERROR_VENDERID_OR_PRODUCTCODE_ERROR 0x0114
-#define CIP_CON_MGR_ERROR_DEVICE_TYPE_ERROR 0x0115
-#define CIP_CON_MGR_ERROR_REVISION_MISMATCH 0x0116
-#define CIP_CON_MGR_INVALID_CONFIGURATION_APP_PATH      0x0129
-#define CIP_CON_MGR_INVALID_CONSUMING_APPLICATION_PATH  0x012A
-#define CIP_CON_MGR_INVALID_PRODUCING_APPLICATION_PATH  0x012B
-#define CIP_CON_MGR_INCONSISTENT_APPLICATION_PATH_COMBO 0x012F
-#define CIP_CON_MGR_NON_LISTEN_ONLY_CONNECTION_NOT_OPENED 0x0119
-#define CIP_CON_MGR_ERROR_PARAMETER_ERROR_IN_UNCONNECTED_SEND_SERVICE 0x0205
-#define CIP_CON_MGR_ERROR_INVALID_SEGMENT_TYPE_IN_PATH 0x0315
-#define CIP_CON_MGR_TARGET_OBJECT_OUT_OF_CONNECTIONS 0x011A
-
-#define CIP_CONN_PRODUCTION_TRIGGER_MASK 0x70
-#define CIP_CONN_CYCLIC_CONNECTION       0x0
-#define CIP_CONN_COS_TRIGGERED_CONNECTION 0x10
-#define CIP_CONN_APLICATION_TRIGGERED_CONNECTION 0x20
-
-/*macros for comparing sequence numbers according to CIP spec vol 2 3-4.2*/
+/**
+ * @brief Sets the routing type of a connection, either
+ * - Point-to-point connections (unicast)
+ * - Multicast connection
+ */
+typedef enum {
+  kRoutingTypePointToPointConnection = 0x4000,
+  kRoutingTypeMulticastConnection = 0x2000
+} RoutingType;
+
+/** @brief Connection Manager Error codes */
+typedef enum {
+  kConnectionManagerStatusCodeSuccess = 0x00,
+  kConnectionManagerStatusCodeErrorConnectionInUse = 0x0100,
+  kConnectionManagerStatusCodeErrorTransportTriggerNotSupported = 0x0103,
+  kConnectionManagerStatusCodeErrorOwnershipConflict = 0x0106,
+  kConnectionManagerStatusCodeErrorConnectionNotFoundAtTargetApplication = 0x0107,
+  kConnectionManagerStatusCodeErrorInvalidOToTConnectionType = 0x123,
+  kConnectionManagerStatusCodeErrorInvalidTToOConnectionType = 0x124,
+  kConnectionManagerStatusCodeErrorInvalidOToTConnectionSize = 0x127,
+  kConnectionManagerStatusCodeErrorInvalidTToOConnectionSize = 0x128,
+  kConnectionManagerStatusCodeErrorNoMoreConnectionsAvailable = 0x0113,
+  kConnectionManagerStatusCodeErrorVendorIdOrProductcodeError = 0x0114,
+  kConnectionManagerStatusCodeErrorDeviceTypeError = 0x0115,
+  kConnectionManagerStatusCodeErrorRevisionMismatch = 0x0116,
+  kConnectionManagerStatusCodeInvalidConfigurationApplicationPath = 0x0129,
+  kConnectionManagerStatusCodeInvalidConsumingApllicationPath = 0x012A,
+  kConnectionManagerStatusCodeInvalidProducingApplicationPath = 0x012B,
+  kConnectionManagerStatusCodeInconsistentApplicationPathCombo = 0x012F,
+  kConnectionManagerStatusCodeNonListenOnlyConnectionNotOpened = 0x0119,
+  kConnectionManagerStatusCodeErrorParameterErrorInUnconnectedSendService = 0x0205,
+  kConnectionManagerStatusCodeErrorInvalidSegmentTypeInPath = 0x0315,
+  kConnectionManagerStatusCodeTargetObjectOutOfConnections = 0x011A
+} ConnectionManagerStatusCode;
+
+typedef enum {
+  kConnectionTriggerTypeProductionTriggerMask = 0x70,
+  kConnectionTriggerTypeCyclicConnection = 0x0,
+  kConnectionTriggerTypeChangeOfStateTriggeredConnection = 0x10,
+  kConnectionTriggerTypeApplicationTriggeredConnection = 0x20
+} ConnectionTriggerType;
+
+/** @brief macros for comparing sequence numbers according to CIP spec vol
+ * 2 3-4.2 for int type variables
+ * @define SEQ_LEQ32(a, b) Checks if sequence number a is less or equal than b
+ * @define SEQ_GEQ32(a, b) Checks if sequence number a is greater or equal than
+ *  b
+ *  @define SEQ_GT32(a, b) Checks if sequence number a is greater than b
+ */
 #define SEQ_LEQ32(a, b) ((int)((a) - (b)) <= 0)
 #define SEQ_LEQ32(a, b) ((int)((a) - (b)) <= 0)
 #define SEQ_GEQ32(a, b) ((int)((a) - (b)) >= 0)
 #define SEQ_GEQ32(a, b) ((int)((a) - (b)) >= 0)
+#define SEQ_GT32(a, b) ((int)((a) - (b)) > 0)
 
 
-/* similar macros for comparing 16 bit sequence numbers */
+/** @brief similar macros for comparing 16 bit sequence numbers
+ * @define SEQ_LEQ16(a, b) Checks if sequence number a is less or equal than b
+ * @define SEQ_GEQ16(a, b) Checks if sequence number a is greater or equal than
+ *  b
+ */
 #define SEQ_LEQ16(a, b) ((short)((a) - (b)) <= 0)
 #define SEQ_LEQ16(a, b) ((short)((a) - (b)) <= 0)
 #define SEQ_GEQ16(a, b) ((short)((a) - (b)) >= 0)
 #define SEQ_GEQ16(a, b) ((short)((a) - (b)) >= 0)
-#define SEQ_GT32(a,b)   ((int)((a) - (b)) > 0)
-
-/*! States of a connection */
-typedef enum
-{
-  CONN_STATE_NONEXISTENT = 0,
-  CONN_STATE_CONFIGURING = 1,
-  CONN_STATE_WAITINGFORCONNECTIONID = 2 /* only used in DeviceNet*/,
-  CONN_STATE_ESTABLISHED = 3,
-  CONN_STATE_TIMEDOUT = 4,
-  CONN_STATE_DEFERREDDELETE = 5 /* only used in DeviceNet */,
-  CONN_STATE_CLOSING
-} CONN_STATE;
-
-/* instance_type attributes */
-typedef enum
-{
-  enConnTypeExplicit         = 0,
-  enConnTypeIOExclusiveOwner = 0x01,
-  enConnTypeIOInputOnly      = 0x11,
-  enConnTypeIOListenOnly     = 0x21
-} EConnType;
-
-/*! Possible values for the watch dog time out action of a connection */
-typedef enum
-{
-  enWatchdogTransitionToTimedOut = 0, /*!< , invalid for explicit message connections */
-  enWatchdogAutoDelete = 1, /*!< Default for explicit message connections, default for I/O connections on EIP*/
-  enWatchdogAutoReset = 2, /*!< Invalid for explicit message connections */
-  enWatchdogDeferredDelete = 3
-/*!< Only valid for DeviceNet, invalid for I/O connections */
-} EWatchdogTimeOutAction;
-
-typedef struct
-{
-  CONN_STATE state;
-  EIP_UINT16 ConnectionID;
+
+/** @brief States of a connection */
+typedef enum {
+  kConnectionStateNonExistent = 0,
+  kConnectionStateConfiguring = 1,
+  kConnectionStateWaitingForConnectionId = 2 /**< only used in DeviceNet */,
+  kConnectionStateEstablished = 3,
+  kConnectionStateTimedOut = 4,
+  kConnectionStateDeferredDelete = 5 /**< only used in DeviceNet */,
+  kConnectionStateClosing
+} ConnectionState;
+
+/** @brief instance_type attributes */
+typedef enum {
+  kConnectionTypeExplicit = 0,
+  kConnectionTypeIoExclusiveOwner = 0x01,
+  kConnectionTypeIoInputOnly = 0x11,
+  kConnectionTypeIoListenOnly = 0x21
+} ConnectionType;
+
+/** @brief Possible values for the watch dog time out action of a connection */
+typedef enum {
+  kWatchdogTimeoutActionTransitionToTimedOut = 0, /**< , invalid for explicit message connections */
+  kWatchdogTimeoutActionAutoDelete = 1, /**< Default for explicit message connections,
+   default for I/O connections on EIP */
+  kWatchdogTimeoutActionAutoReset = 2, /**< Invalid for explicit message connections */
+  kWatchdogTimeoutActionDeferredDelete = 3 /**< Only valid for DeviceNet, invalid for I/O connections */
+} WatchdogTimeoutAction;
+
+typedef struct {
+  ConnectionState state;
+  EipUint16 connection_id;
 /*TODO think if this is needed anymore
 /*TODO think if this is needed anymore
  TCMReceiveDataFunc m_ptfuncReceiveData; */
  TCMReceiveDataFunc m_ptfuncReceiveData; */
-} S_Link_Consumer;
+} LinkConsumer;
 
 
-typedef struct
-{
-  CONN_STATE state;
-  EIP_UINT16 ConnectionID;
-} S_Link_Producer;
+typedef struct {
+  ConnectionState state;
+  EipUint16 connection_id;
+} LinkProducer;
 
 
-typedef struct
-{
-  S_Link_Consumer Consumer;
-  S_Link_Producer Producer;
-} S_Link_Object;
+typedef struct {
+  LinkConsumer consumer;
+  LinkProducer producer;
+} LinkObject;
 
 
-/*! The data needed for handling connections. This data is strongly related to
+/** The data needed for handling connections. This data is strongly related to
  * the connection object defined in the CIP-specification. However the full
  * the connection object defined in the CIP-specification. However the full
  * functionality of the connection object is not implemented. Therefore this
  * functionality of the connection object is not implemented. Therefore this
  * data can not be accessed with CIP means.
  * data can not be accessed with CIP means.
  */
  */
-typedef struct CIP_ConnectionObject
-{
-  CONN_STATE State;
-  EConnType m_eInstanceType;
+typedef struct connection_object {
+  ConnectionState state;
+  ConnectionType instance_type;
 
 
   /* conditional
   /* conditional
-   UINT16 DeviceNetProductedConnectionID;
-   UINT16 DeviceNetConsumedConnectionID;
+   EipUint16 DeviceNetProductedConnectionID;
+   EipUint16 DeviceNetConsumedConnectionID;
    */
    */
-  EIP_BYTE DeviceNetInitialCommCharacteristics;
-  EIP_UINT16 ProducedConnectionSize;
-  EIP_UINT16 ConsumedConnectionSize;
-  EIP_UINT16 ExpectedPacketRate;
+  EipByte device_net_initial_comm_characteristcs;
+  EipUint16 produced_connection_size;
+  EipUint16 consumed_connection_size;
+  EipUint16 expected_packet_rate;
 
 
   /*conditional*/
   /*conditional*/
-  EIP_UINT32 CIPProducedConnectionID;
-  EIP_UINT32 CIPConsumedConnectionID;
+  EipUint32 produced_connection_id;
+  EipUint32 consumed_connection_id;
   /**/
   /**/
-  EWatchdogTimeOutAction WatchdogTimeoutAction;
-  EIP_UINT16 ProducedConnectionPathLength;
-  S_CIP_EPATH ProducedConnectionPath;
-  EIP_UINT16 ConsumedConnectionPathLength;
-  S_CIP_EPATH ConsumedConnectionPath;
+  WatchdogTimeoutAction watchdog_timeout_action;
+  EipUint16 produced_connection_path_length;
+  CipEpath produced_connection_path;
+  EipUint16 consumed_connection_path_length;
+  CipEpath consumed_connection_path;
   /* conditional
   /* conditional
    UINT16 ProductionInhibitTime;
    UINT16 ProductionInhibitTime;
    */
    */
   /* non CIP Attributes, only relevant for opened connections */
   /* non CIP Attributes, only relevant for opened connections */
-  EIP_BYTE Priority_Timetick;
-  EIP_UINT8 Timeoutticks;
-  EIP_UINT16 ConnectionSerialNumber;
-  EIP_UINT16 OriginatorVendorID;
-  EIP_UINT32 OriginatorSerialNumber;
-  EIP_UINT16 ConnectionTimeoutMultiplier;
-  EIP_UINT32 O_to_T_RPI;
-  EIP_UINT16 O_to_T_NetworkConnectionParameter;
-  EIP_UINT32 T_to_O_RPI;
-  EIP_UINT16 T_to_O_NetworkConnectionParameter;
-  EIP_BYTE TransportTypeClassTrigger;
-  EIP_UINT8 ConnectionPathSize;
-  S_CIP_ElectronicKey ElectronicKey;
-  S_CIP_ConnectionPath ConnectionPath; /* padded EPATH*/
-  S_Link_Object stLinkObject;
-
-  S_CIP_Instance *p_stConsumingInstance;
+  EipByte priority_timetick;
+  EipUint8 timeout_ticks;
+  EipUint16 connection_serial_number;
+  EipUint16 originator_vendor_id;
+  EipUint32 originator_serial_number;
+  EipUint16 connection_timeout_multiplier;
+  EipUint32 o_to_t_requested_packet_interval;
+  EipUint16 o_to_t_network_connection_parameter;
+  EipUint32 t_to_o_requested_packet_interval;
+  EipUint16 t_to_o_network_connection_parameter;
+  EipByte transport_type_class_trigger;
+  EipUint8 connection_path_size;
+  CipElectronicKey electronic_key;
+  CipConnectionPath connection_path; /* padded EPATH*/
+  LinkObject link_object;
+
+  CipInstance *consuming_instance;
   /*S_CIP_CM_Object *p_stConsumingCMObject; */
   /*S_CIP_CM_Object *p_stConsumingCMObject; */
 
 
-  S_CIP_Instance *p_stProducingInstance;
+  CipInstance *producing_instance;
   /*S_CIP_CM_Object *p_stProducingCMObject; */
   /*S_CIP_CM_Object *p_stProducingCMObject; */
 
 
-  EIP_UINT32 EIPSequenceCountProducing; /* the EIP level sequence Count for Class 0/1 Producing Connections may have a different value than SequenceCountProducing*/
-  EIP_UINT32 EIPSequenceCountConsuming; /* the EIP level sequence Count for Class 0/1 Producing Connections may have a different value than SequenceCountProducing*/
-
-  EIP_UINT16 SequenceCountProducing; /* sequence Count for Class 1 Producing Connections*/
-  EIP_UINT16 SequenceCountConsuming; /* sequence Count for Class 1 Producing Connections*/
-
-  EIP_INT32 TransmissionTriggerTimer;
-  EIP_INT32 InnacitvityWatchdogTimer;
-
-
-  /*! Minimal time between the production of two application triggered or change of state triggered
-   * I/O connection messages
+  EipUint32 eip_level_sequence_count_producing; /* the EIP level sequence Count
+   for Class 0/1
+   Producing Connections may have a
+   different
+   value than SequenceCountProducing */
+  EipUint32 eip_level_sequence_count_consuming; /* the EIP level sequence Count
+   for Class 0/1
+   Producing Connections may have a
+   different
+   value than SequenceCountProducing */
+
+  EipUint16 sequence_count_producing; /* sequence Count for Class 1 Producing
+   Connections */
+  EipUint16 sequence_count_consuming; /* sequence Count for Class 1 Producing
+   Connections */
+
+  EipInt32 transmission_trigger_timer;
+  EipInt32 inactivity_watchdog_timer;
+
+  /** @brief Minimal time between the production of two application triggered
+   * or change of state triggered I/O connection messages
    */
    */
-  EIP_UINT16 m_unProductionInhibitTime;
-  /*! Timer for the production inhibition of application triggered or change-of-state
-   *  I/O connections.
+  EipUint16 production_inhibit_time;
+
+  /** @brief Timer for the production inhibition of application triggered or
+   * change-of-state I/O connections.
    */
    */
-  EIP_INT32 m_nProductionInhibitTimer;
+  EipInt32 production_inhibit_timer;
 
 
-  struct sockaddr_in remote_addr; /* socket address for produce */
-  struct sockaddr_in m_stOriginatorAddr;  /* the address of the originator that established the connection. needed for scanning if the right packet is arriving */
-  int sockfd[2]; /* socket handles, indexed by CONSUMING or PRODUCING */
+  struct sockaddr_in remote_address; /* socket address for produce */
+  struct sockaddr_in originator_address; /* the address of the originator that
+   established the connection. needed
+   for scanning if the right packet is
+   arriving */
+  int socket[2]; /* socket handles, indexed by kConsuming or kProducing */
 
 
   /* pointers to connection handling functions */
   /* pointers to connection handling functions */
-  TConnCloseFunc m_pfCloseFunc;
-  TConnTimeOutFunc m_pfTimeOutFunc;
-  TConnSendDataFunc m_pfSendDataFunc;
-  TConnRecvDataFunc m_pfReceiveDataFunc;
+  ConnectionCloseFunction connection_close_function;
+  ConnectionTimeoutFunction connection_timeout_function;
+  ConnectionSendDataFunction connection_send_data_function;
+  ConnectionReceiveDataFunction connection_receive_data_function;
 
 
   /* pointers to be used in the active connection list */
   /* pointers to be used in the active connection list */
-  struct CIP_ConnectionObject *m_pstNext;
-  struct CIP_ConnectionObject *m_pstFirst;
+  struct connection_object *next_connection_object;
+  struct connection_object *first_connection_object;
 
 
-  EIP_UINT16 CorrectOTSize;
-  EIP_UINT16 CorrectTOSize;
-} S_CIP_ConnectionObject;
+  EipUint16 correct_originator_to_target_size;
+  EipUint16 correct_target_to_originator_size;
+} ConnectionObject;
 
 
-#define CIP_CONNECTION_MANAGER_CLASS_CODE 0x06
+/** @brief Connection Manager class code */
+static const int g_kCipConnectionManagerClassCode = 0x06;
 
 
 /* public functions */
 /* public functions */
 
 
-/*! Initialize the data of the connection manager object
+/** @brief Initialize the data of the connection manager object
  */
  */
-EIP_STATUS
-Connection_Manager_Init(EIP_UINT16 pa_nUniqueConnID);
+EipStatus ConnectionManagerInit(EipUint16 unique_connection_id);
 
 
-/*!  Get a connected object dependent on requested ConnectionID.
+/** @brief Get a connected object dependent on requested ConnectionID.
  *
  *
- *   @param ConnectionID  requested ConnectionID of opened connection
+ *   @param connection_id  requested @var connection_id of opened connection
  *   @return pointer to connected Object
  *   @return pointer to connected Object
  *           0 .. connection not present in device
  *           0 .. connection not present in device
  */
  */
-S_CIP_ConnectionObject *
-getConnectedObject(EIP_UINT32 ConnectionID);
+ConnectionObject* GetConnectedObject(EipUint32 connection_id);
 
 
-/*!  Get a connection object for a given output assembly.
+/**  Get a connection object for a given output assembly.
  *
  *
- *   @param pa_unOutputAssemblyId requested output assembly of requested connection
+ *   @param output_assembly_id requested output assembly of requested
+ *connection
  *   @return pointer to connected Object
  *   @return pointer to connected Object
  *           0 .. connection not present in device
  *           0 .. connection not present in device
  */
  */
-S_CIP_ConnectionObject *
-getConnectedOutputAssembly(EIP_UINT32 pa_unOutputAssemblyId);
+ConnectionObject *GetConnectedOutputAssembly(EipUint32 output_assembly_id);
 
 
-
-/*! Copy the given connection data from pa_pstSrc to pa_pstDst
+/** Copy the given connection data from pa_pstSrc to pa_pstDst
  */
  */
-void
-copyConnectionData(S_CIP_ConnectionObject *pa_pstDst,
-    S_CIP_ConnectionObject *pa_pstSrc);
+void CopyConnectionData(ConnectionObject *destination, ConnectionObject *source);
 
 
-/** \brief Close the given connection
+/** @brief Close the given connection
  *
  *
- * This function will take the data form the connection and correctly closes the connection (e.g., open sockets)
- * @param pa_pstConnObj pointer to the connection object structure to be closed
+ * This function will take the data form the connection and correctly closes the
+ *connection (e.g., open sockets)
+ * @param connection_object pointer to the connection object structure to be
+ *closed
  */
  */
-void
-closeConnection(S_CIP_ConnectionObject *pa_pstConnObj);
+void CloseConnection(ConnectionObject *connection_object);
 
 
-EIP_BOOL8 isConnectedOutputAssembly(EIP_UINT32 pa_nInstanceNr);
+/* TODO: Missing documentation */
+EipBool8 IsConnectedOutputAssembly(EipUint32 instance_number);
 
 
-/** \brief Generate the ConnectionIDs and set the general configuration parameter
- * in the given connection object.
+/** @brief Generate the ConnectionIDs and set the general configuration
+ * parameter in the given connection object.
  *
  *
- * @param pa_pstConnObj pointer to the connection object that should be set up.
+ * @param connection_object pointer to the connection object that should be set
+ *up.
  */
  */
-void
-generalConnectionConfiguration(S_CIP_ConnectionObject *pa_pstConnObj);
-
+void GeneralConnectionConfiguration(ConnectionObject *connection_object);
 
 
-/** \brief Insert the given connection object to the list of currently active and managed connections.
+/** @brief Insert the given connection object to the list of currently active
+ *  and managed connections.
  *
  *
- * By adding a connection to the active connection list the connection manager will
- * perform the supervision and handle the timing (e.g., timeout, production inhibit, etc).
+ * By adding a connection to the active connection list the connection manager
+ * will perform the supervision and handle the timing (e.g., timeout,
+ * production inhibit, etc).
  *
  *
- * @param pa_pstConn pointer to the connection object to be added.
+ * @param connection_object pointer to the connection object to be added.
  */
  */
-void
-addNewActiveConnection(S_CIP_ConnectionObject *pa_pstConn);
-
-void
-removeFromActiveConnections(S_CIP_ConnectionObject *pa_pstConn);
+void AddNewActiveConnection(ConnectionObject *connection_object);
 
 
-#endif /*CIPCONNECTIONMANAGER_H_*/
+/* TODO: Missing documentation */
+void RemoveFromActiveConnections(ConnectionObject *connection_object);
 
 
+#endif /* OPENER_CIPCONNECTIONMANAGER_H_ */

+ 48 - 70
source/src/cip/ciperror.h

@@ -3,74 +3,52 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPERROR_H_
-#define CIPERROR_H_
+#ifndef OPENER_CIPERROR_H_
+#define OPENER_CIPERROR_H_
 
 
-#define CIP_ERROR_SUCCESS 0x00 /*!< Service was successfully performed by the object specified. */
-#define CIP_ERROR_CONNECTION_FAILURE 0x01 /*!< A connection related service failed along the connection path. */
-#define CIP_ERROR_RESOURCE_UNAVAILABLE 0x02 /*!< Resources needed for the object to perform the requested service were unavailable */
-#define CIP_ERROR_INVALID_PARAMETER_VALUE 0x03 /*!< See Status Code 0x20, which is the preferred value to use for this condition. */
-#define CIP_ERROR_PATH_SEGMENT_ERROR 0x04 /*!< The path segment identifier or the segment syntax was not understood by the
-processing node. Path processing shall stop when a path segment error is encountered. */
-#define CIP_ERROR_PATH_DESTINATION_UNKNOWN 0x05 /*!< The path is referencing an object class, instance or structure element that is not
-known or is not contained in the processing node. Path processing shall stop when a path destination unknown error is encountered. */
-#define CIP_ERROR_PARTIAL_TRANSFER 0x06 /*!< Only part of the expected data was transferred. */
-#define CIP_ERROR_CONNECTION_LOST 0x07 /*!< The messaging connection was lost. */
-#define CIP_ERROR_SERVICE_NOT_SUPPORTED 0x08 /*!< The requested service was not implemented or was not defined for this Object
-Class/Instance. */
-#define CIP_ERROR_INVALID_ATTRIBUTE_VALUE 0x09 /*!< Invalid attribute data detected */
-#define CIP_ERROR_ATTRIBUTE_LIST_ERROR 0x0A /*!< An attribute in the Get_Attribute_List or Set_Attribute_List response has a
-non-zero status. */
-#define CIP_ERROR_ALREADY_IN_REQUESTED_MODE 0x0B /*!< The object is already in the mode/state being requested by the service */
-#define CIP_ERROR_OBJECT_STATE_CONFLICT 0x0C /*!< The object cannot perform the requested service in its current mode/state */
-#define CIP_ERROR_OBJECT_ALREADY_EXISTS 0x0D /*!< The requested instance of object to be created already exists.*/
-#define CIP_ERROR_ATTRIBUTE_NOT_SETTABLE 0x0E /*!< A request to modify a non-modifiable attribute was received. */
-#define CIP_ERROR_PRIVILEGE_VIOLATION 0x0F /*!< A permission/privilege check failed */
-#define CIP_ERROR_DEVICE_STATE_CONFLICT 0x10 /*!< The device's current mode/state prohibits the execution of the requested service. */
-#define CIP_ERROR_REPLY_DATA_TOO_LARGE 0x11 /*!< The data to be transmitted in the response buffer is larger than the allocated response buffer */
-#define CIP_ERROR_FRAGMENTATION_OF_A_PRIMITIVE_VALUE 0x12 /*!< The service specified an operation that is going to fragment a primitive data
-value, i.e. half a REAL data type. */
-#define CIP_ERROR_NOT_ENOUGH_DATA 0x13 /*!< The service did not supply enough data to perform the specified operation. */
-#define CIP_ERROR_ATTRIBUTE_NOT_SUPPORTED 0x14 /*!< The attribute specified in the request is not supported */
-#define CIP_ERROR_TOO_MUCH_DATA 0x15 /*!< The service supplied more data than was expected */
-#define CIP_ERROR_OBJECT_DOES_NOT_EXIST 0x16 /*!< The object specified does not exist in the device. */
-#define CIP_ERROR_SERVICE_FRAGEMENTATION_SEQUENCE_NOT_IN_PROGRESS 0x17 /*!< The fragmentation sequence for this service is not currently active for this
-data. */
-#define CIP_ERROR_NO_STORED_ATTRIBUTE_DATA 0x18 /*!< The attribute data of this object was not saved prior to the requested service. */
-#define CIP_ERROR_STORE_OPERATION_FAILURE 0x19 /*!< The attribute data of this object was not saved due to a failure during the attempt. */
-#define CIP_ERROR_ROUTING_FAILURE_REQUEST_PACKET_TOO_LARGE 0x1A /*!< The service request packet was too large for transmission on a network in the
-path to the destination. The routing device was forced to abort the service. */
-#define CIP_ERROR_ROUTING_FAILURE_RESPONSE_PACKET_TOO_LARGE 0x1B /*!< The service response packet was too large for transmission on a network in the
-path from the destination. The routing device was forced to abort the service. */
-#define CIP_ERROR_MISSING_ATTIRBUTE_LIST_ENTRIY 0x1C /*!< The service did not supply an attribute in a list of attributes that was needed by
-the service to perform the requested behavior. */
-#define CIP_ERROR_INVALID_ATTRIBUTE_VALUE_LIST 0x1D /*!< The service is returning the list of attributes supplied with status information
-for those attributes that were invalid. */
-#define CIP_ERROR_EMBEDDED_SERVICE_ERROR 0x1E /*!< An embedded service resulted in an error. */
-#define CIP_ERROR_VENDOR_SPECIFIC_ERROR 0x1F /*!< A vendor specific error has been encountered. The Additional Code Field of
-the Error Response defines the particular error encountered. Use of this
-General Error Code should only be performed when none of the Error Codes
-presented in this table or within an Object Class definition accurately reflect
-the error. */
-#define CIP_ERROR_INVALID_PARAMETER 0x20 /*!< A parameter associated with the request was invalid. This code is used when a
-parameter does not meet the requirements of this specification and/or the
-requirements defined in an Application Object Specification. */
-#define CIP_ERROR_WRITEONCE_VALUE_OR_MEDIUM_ALREADY_WRITTEN 0x21 /*!< An attempt was made to write to a write-once medium (e.g. WORM drive,
-PROM) that has already been written, or to modify a value that cannot be changed once established. */
-#define CIP_ERROR_INVALID_REPLY_RECEIVED 0x22 /*!< An invalid reply is received (e.g. reply service code does not match the request
-service code, or reply message is shorter than the minimum expected reply
-size). This status code can serve for other causes of invalid replies. */
-/*23-24 Reserved by CIP for future extensions*/
-#define CIP_ERROR_KEY_FAILURE_IN_PATH 0x25 /*!< The Key Segment that was included as the first segment in the path does not
-match the destination module. The object specific status shall indicate which part of the key check failed. */
-#define CIP_ERROR_PATH_SIZE_INVALID 0x26 /*!< The size of the path which was sent with the Service Request is either not large
-enough to allow the Request to be routed to an object or too much routing data was included. */
-#define CIP_ERROR_UNEXPECTED_ATTRIBUTE_IN_LIST 0x27 /*!< An attempt was made to set an attribute that is not able to be set at this time. */
-#define CIP_ERROR_INVALID_MEMBER_ID 0x28 /*!< The Member ID specified in the request does not exist in the specified Class/Instance/Attribute */
-#define CIP_ERROR_MEMBER_NOT_SETTABLE 0x29 /*!< A request to modify a non-modifiable member was received */
-#define CIP_ERROR_GROUP2_ONLY_SERVER_GENERAL_FAILURE 0x2A /*!< This error code may only be reported by DeviceNet group 2 only servers with
-4K or less code space and only in place of Service not supported, Attribute
-not supported and Attribute not settable. */
-/*2B - CF Reserved by CIP for future extensions
- D0 - FF Reserved for Object Class and service errors*/
-#endif /*CIPERROR_H_*/
+typedef enum {
+  kCipErrorSuccess = 0x00, /**< Service was successfully performed by the object specified. */
+  kCipErrorConnectionFailure = 0x01, /**< A connection related service failed along the connection path. */
+  kCipErrorResourceUnavailable = 0x02, /**< Resources needed for the object to perform the requested service were unavailable */
+  kCipErrorInvalidParameterValue = 0x03, /**< See Status Code 0x20, which is the preferred value to use for this condition. */
+  kCipErrorPathSegmentError = 0x04, /**< The path segment identifier or the segment syntax was not understood by the processing node. Path processing shall stop when a path segment error is encountered. */
+  kCipErrorPathDestinationUnknown = 0x05, /**< The path is referencing an object class, instance or structure element that is not known or is not contained in the processing node. Path processing shall stop when a path destination unknown error is encountered. */
+  kCipErrorPartialTransfer = 0x06, /**< Only part of the expected data was transferred. */
+  kCipErrorConnectionLost = 0x07, /**< The messaging connection was lost. */
+  kCipErrorServiceNotSupported = 0x08, /**< The requested service was not implemented or was not defined for this Object Class/Instance. */
+  kCipErrorInvalidAttributeValue = 0x09, /**< Invalid attribute data detected */
+  kCipErrorAttributeListError = 0x0A, /**< An attribute in the Get_Attribute_List or Set_Attribute_List response has a non-zero status. */
+  kCipErrorAlreadyInRequestedMode = 0x0B, /**< The object is already in the mode/state being requested by the service */
+  kCipErrorObjectStateConflict = 0x0C, /**< The object cannot perform the requested service in its current mode/state */
+  kCipErrorObjectAlreadyExists = 0x0D, /**< The requested instance of object to be created already exists.*/
+  kCipErrorAttributeNotSetable = 0x0E, /**< A request to modify a non-modifiable attribute was received. */
+  kCipErrorPrivilegeViolation = 0x0F, /**< A permission/privilege check failed */
+  kCipErrorDeviceStateConflict = 0x10, /**< The device's current mode/state prohibits the execution of the requested service. */
+  kCipErrorReplyDataTooLarge = 0x11, /**< The data to be transmitted in the response buffer is larger than the allocated response buffer */
+  kCipErrorFragmentationOfAPrimitiveValue = 0x12, /**< The service specified an operation that is going to fragment a primitive data value, i.e. half a REAL data type. */
+  kCipErrorNotEnoughData = 0x13, /**< The service did not supply enough data to perform the specified operation. */
+  kCipErrorAttributeNotSupported = 0x14, /**< The attribute specified in the request is not supported */
+  kCipErrorTooMuchData = 0x15, /**< The service supplied more data than was expected */
+  kCipErrorObjectDoesNotExist = 0x16, /**< The object specified does not exist in the device. */
+  kCipErrorServiceFragmentationSequenceNotInProgress = 0x17, /**< The fragmentation sequence for this service is not currently active for this data. */
+  kCipErrorNoStoredAttributeData = 0x18, /**< The attribute data of this object was not saved prior to the requested service. */
+  kCipErrorStoreOperationFailure = 0x19, /**< The attribute data of this object was not saved due to a failure during the attempt. */
+  kCipErrorRoutingFailureRequestPacketTooLarge = 0x1A, /**< The service request packet was too large for transmission on a network in the path to the destination. The routing device was forced to abort the service. */
+  kCipErrorRoutingFailureResponsePacketTooLarge = 0x1B, /**< The service response packet was too large for transmission on a network in the path from the destination. The routing device was forced to abort the service. */
+  kCipErrorMissingAttributeListEntry = 0x1C, /**< The service did not supply an attribute in a list of attributes that was needed by the service to perform the requested behavior. */
+  kCipErrorInvalidAttributeValueList = 0x1D, /**< The service is returning the list of attributes supplied with status information for those attributes that were invalid. */
+  kCipErrorEmbeddedServiceError = 0x1E, /**< An embedded service resulted in an error. */
+  kCipErrorVendorSpecificError = 0x1F, /**< A vendor specific error has been encountered. The Additional Code Field of the Error Response defines the particular error encountered. Use of this General Error Code should only be performed when none of the Error Codes presented in this table or within an Object Class definition accurately reflect the error. */
+  kCipErrorInvalidParameter = 0x20, /**< A parameter associated with the request was invalid. This code is used when a parameter does not meet the requirements of this specification and/or the requirements defined in an Application Object Specification. */
+  kCipErrorWriteonceValueOrMediumAlreadyWritten = 0x21, /**< An attempt was made to write to a write-once medium (e.g. WORM drive, PROM) that has already been written, or to modify a value that cannot be changed once established. */
+  kCipErrorInvalidReplyReceived = 0x22, /**< An invalid reply is received (e.g. reply service code does not match the request service code, or reply message is shorter than the minimum expected reply size). This status code can serve for other causes of invalid replies. */
+  /* 23-24 Reserved by CIP for future extensions */
+  kCipErrorKeyFailureInPath = 0x25, /**< The Key Segment that was included as the first segment in the path does not match the destination module. The object specific status shall indicate which part of the key check failed. */
+  kCipErrorPathSizeInvalid = 0x26, /**< The size of the path which was sent with the Service Request is either not large enough to allow the Request to be routed to an object or too much routing data was included. */
+  kCipErrorUnexpectedAttributeInList = 0x27, /**< An attempt was made to set an attribute that is not able to be set at this time. */
+  kCipErrorInvalidMemberId = 0x28, /**< The Member ID specified in the request does not exist in the specified Class/Instance/Attribute */
+  kCipErrorMemberNotSetable = 0x29, /**< A request to modify a non-modifiable member was received */
+  kCipErrorGroup2OnlyServerGeneralFailure = 0x2A /**< This error code may only be reported by DeviceNet group 2 only servers with 4K or less code space and only in place of Service not supported, Attribute not supported and Attribute not setable. */
+/*2B - CF Reserved by CIP for future extensions D0 - FF Reserved for Object Class and service errors*/
+} CipError;
+#endif /* OPENER_CIPERROR_H_ */

+ 39 - 44
source/src/cip/cipethernetlink.c

@@ -6,60 +6,55 @@
 #include <string.h>
 #include <string.h>
 
 
 #include "cipethernetlink.h"
 #include "cipethernetlink.h"
+
 #include "cipcommon.h"
 #include "cipcommon.h"
 #include "cipmessagerouter.h"
 #include "cipmessagerouter.h"
 #include "ciperror.h"
 #include "ciperror.h"
 #include "endianconv.h"
 #include "endianconv.h"
 #include "opener_api.h"
 #include "opener_api.h"
 
 
-typedef struct
-  {
-    EIP_UINT32 InterfaceSpeed;
-    EIP_UINT32 InterfaceFlags;
-    EIP_UINT8 PhysicalAddress[6];
-  } S_CIP_EthernetLinkObject;
+typedef struct {
+  EipUint32 interface_speed;
+  EipUint32 interface_flags;
+  EipUint8 physical_address[6];
+} CipEthernetLinkObject;
 
 
 /* global private variables */
 /* global private variables */
-S_CIP_EthernetLinkObject stEthernetLink;
-
+CipEthernetLinkObject g_ethernet_link;
 
 
-void configureMACAddress(const EIP_UINT8 *pa_acMACAddress){
-  memcpy(&stEthernetLink.PhysicalAddress, pa_acMACAddress,
-      sizeof(stEthernetLink.PhysicalAddress));
+void ConfigureMacAddress(const EipUint8 *mac_address) {
+  memcpy(&g_ethernet_link.physical_address, mac_address,
+         sizeof(g_ethernet_link.physical_address));
 
 
 }
 }
 
 
-EIP_STATUS CIP_Ethernet_Link_Init()
-  {
-    S_CIP_Class *pstEthernetLinkClass;
-    S_CIP_Instance *pstEthernetLinkInstance;
-
-    /* set attributes to initial values */
-    stEthernetLink.InterfaceSpeed = 100;
-    stEthernetLink.InterfaceFlags = 0xF; /* successful speed and duplex neg, full duplex active link, TODO in future it should be checked if link is active */
-
-    if ((pstEthernetLinkClass = createCIPClass(CIP_ETHERNETLINK_CLASS_CODE, 0, /* # class attributes*/
-        0xffffffff, /* class getAttributeAll mask*/
-        0, /* # class services*/
-        3, /* # instance attributes*/
-        0xffffffff, /* instance getAttributeAll mask*/
-        0, /* # instance services*/
-        1, /* # instances*/
-        "Ethernet link", 1)) != 0)
-      {
-
-        pstEthernetLinkInstance = getCIPInstance(pstEthernetLinkClass, 1);
-        insertAttribute(pstEthernetLinkInstance, 1, CIP_UDINT,
-            &stEthernetLink.InterfaceSpeed, CIP_ATTRIB_GETABLE); /* bind attributes to the instance*/
-        insertAttribute(pstEthernetLinkInstance, 2, CIP_DWORD,
-            &stEthernetLink.InterfaceFlags, CIP_ATTRIB_GETABLE);
-        insertAttribute(pstEthernetLinkInstance, 3, CIP_6USINT,
-            &stEthernetLink.PhysicalAddress, CIP_ATTRIB_GETABLE);
-      }
-    else
-      {
-        return EIP_ERROR;
-      }
-
-    return EIP_OK;
+EipStatus CipEthernetLinkInit() {
+  CipClass *ethernet_link_class;
+  CipInstance *ethernet_link_instance;
+
+  /* set attributes to initial values */
+  g_ethernet_link.interface_speed = 100;
+  g_ethernet_link.interface_flags = 0xF; /* successful speed and duplex neg, full duplex active link, TODO in future it should be checked if link is active */
+
+  if ((ethernet_link_class = CreateCipClass(CIP_ETHERNETLINK_CLASS_CODE, 0, /* # class attributes*/
+                                            0xffffffff, /* class getAttributeAll mask*/
+                                            0, /* # class services*/
+                                            3, /* # instance attributes*/
+                                            0xffffffff, /* instance getAttributeAll mask*/
+                                            0, /* # instance services*/
+                                            1, /* # instances*/
+                                            "Ethernet Link", 1)) != 0) {
+
+    ethernet_link_instance = GetCipInstance(ethernet_link_class, 1);
+    InsertAttribute(ethernet_link_instance, 1, kCipUdint,
+                    &g_ethernet_link.interface_speed, kGetableSingleAndAll); /* bind attributes to the instance*/
+    InsertAttribute(ethernet_link_instance, 2, kCipDword,
+                    &g_ethernet_link.interface_flags, kGetableSingleAndAll);
+    InsertAttribute(ethernet_link_instance, 3, kCip6Usint,
+                    &g_ethernet_link.physical_address, kGetableSingleAndAll);
+  } else {
+    return kEipStatusError;
   }
   }
+
+  return kEipStatusOk;
+}

+ 5 - 6
source/src/cip/cipethernetlink.h

@@ -3,8 +3,8 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPETHERNETLINK_H_
-#define CIPETHERNETLINK_H_
+#ifndef OPENER_CIPETHERNETLINK_H_
+#define OPENER_CIPETHERNETLINK_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
@@ -12,9 +12,8 @@
 #define CIP_ETHERNETLINK_CLASS_CODE 0xF6
 #define CIP_ETHERNETLINK_CLASS_CODE 0xF6
 
 
 /* public functions */
 /* public functions */
-/*!Initialize the Ethernet Link Objects data
+/** @brief Initialize the Ethernet Link Objects data
  */
  */
-EIP_STATUS CIP_Ethernet_Link_Init(void);
+EipStatus CipEthernetLinkInit(void);
 
 
-
-#endif /*CIPETHERNETLINK_H_*/
+#endif /* OPENER_CIPETHERNETLINK_H_*/

+ 101 - 109
source/src/cip/cipidentity.c

@@ -35,129 +35,121 @@
 
 
 /* attributes in CIP Identity Object */
 /* attributes in CIP Identity Object */
 
 
-EIP_UINT16 VendorID = OPENER_DEVICE_VENDOR_ID; /**< Attribute 1: Vendor ID */
-EIP_UINT16 DeviceType = OPENER_DEVICE_TYPE; /**< Attribute 2: Device Type */
-EIP_UINT16 ProductCode = OPENER_DEVICE_PRODUCT_CODE; /**< Attribute 3: Product Code */
-S_CIP_Revision Revison =
-  { OPENER_DEVICE_MAJOR_REVISION, OPENER_DEVICE_MINOR_REVISION }; /**< Attribute 4: Revision / USINT Major, USINT Minor */
-EIP_UINT16 ID_Status = 0; /**< Attribute 5: Status */
-EIP_UINT32 SerialNumber = 0; /**< Attribute 6: Serial Number, has to be set prior to OpENer initialization */
-S_CIP_Short_String ProductName =
-  { sizeof(OPENER_DEVICE_NAME) - 1, OPENER_DEVICE_NAME }; /**< Attribute 7: Product Name */
-
+EipUint16 vendor_id_ = OPENER_DEVICE_VENDOR_ID; /**< Attribute 1: Vendor ID */
+EipUint16 device_type_ = OPENER_DEVICE_TYPE; /**< Attribute 2: Device Type */
+EipUint16 product_code_ = OPENER_DEVICE_PRODUCT_CODE; /**< Attribute 3: Product Code */
+CipRevision revision_ = { OPENER_DEVICE_MAJOR_REVISION,
+    OPENER_DEVICE_MINOR_REVISION }; /**< Attribute 4: Revision / USINT Major, USINT Minor */
+EipUint16 status_ = 0; /**< Attribute 5: Status */
+EipUint32 serial_number_ = 0; /**< Attribute 6: Serial Number, has to be set prior to OpENer initialization */
+CipShortString product_name_ = { sizeof(OPENER_DEVICE_NAME) - 1,
+    OPENER_DEVICE_NAME }; /**< Attribute 7: Product Name */
 
 
 /** Private functions, sets the devices serial number
 /** Private functions, sets the devices serial number
- * @param pa_unSerialNumber The serial number of the deivce
+ * @param serial_number The serial number of the device
  */
  */
-void setDeviceSerialNumber(EIP_UINT32 pa_unSerialNumber)
-  {
-    SerialNumber = pa_unSerialNumber;
-  }
+void SetDeviceSerialNumber(EipUint32 serial_number) {
+  serial_number_ = serial_number;
+}
 
 
 /** Private functions, sets the devices status
 /** Private functions, sets the devices status
- * @param pa_unStatus The serial number of the deivce
+ * @param status The serial number of the deivce
  */
  */
-void setDeviceStatus(EIP_UINT16 pa_unStatus)
-{
-  ID_Status = pa_unStatus;
+void SetDeviceStatus(EipUint16 status) {
+  status_ = status;
 }
 }
 
 
 /** Reset service
 /** Reset service
  *
  *
- * @param pa_pstInstance
- * @param pa_stMRRequest
- * @param pa_stMRResponse
- * @returns Currently always EIP_OK_SEND is returned
+ * @param instance
+ * @param message_router_request
+ * @param message_router_response
+ * @returns Currently always kEipOkDend is returned
  */
  */
-static EIP_STATUS Reset(S_CIP_Instance *pa_pstInstance, /* pointer to instance*/
-    S_CIP_MR_Request *pa_stMRRequest, /* pointer to message router request*/
-    S_CIP_MR_Response *pa_stMRResponse) /* pointer to message router response*/
+static EipStatus Reset(CipInstance *instance, /* pointer to instance*/
+                       CipMessageRouterRequest *message_router_request, /* pointer to message router request*/
+                       CipMessageRouterResponse *message_router_response) /* pointer to message router response*/
+{
+  EipStatus eip_status;
+  (void) instance;
+
+  eip_status = kEipStatusOkSend;
+
+  message_router_response->reply_service = (0x80
+      | message_router_request->service);
+  message_router_response->size_of_additional_status = 0;
+  message_router_response->general_status = kCipErrorSuccess;
+
+  if (message_router_request->data_length == 1) {
+    switch (message_router_request->data[0]) {
+      case 0: /* Reset type 0 -> emulate device reset / Power cycle */
+        if (kEipStatusError == ResetDevice()) {
+          message_router_response->general_status = kCipErrorInvalidParameter;
+        }
+        break;
+
+      case 1: /* Reset type 1 -> reset to device settings */
+        if (kEipStatusError == ResetDeviceToInitialConfiguration()) {
+          message_router_response->general_status = kCipErrorInvalidParameter;
+        }
+        break;
+
+        /* case 2: Not supported Reset type 2 -> Return to factory defaults except communications parameters */
+
+      default:
+        message_router_response->general_status = kCipErrorInvalidParameter;
+        break;
+    }
+  } else  /*TODO: Should be if (pa_stMRRequest->DataLength == 0)*/
   {
   {
-	EIP_STATUS nRetVal;
-    (void)pa_pstInstance;
-
-    nRetVal = EIP_OK_SEND;
-
-    pa_stMRResponse->ReplyService = (0x80 | pa_stMRRequest->Service);
-    pa_stMRResponse->SizeofAdditionalStatus = 0;
-    pa_stMRResponse->GeneralStatus = CIP_ERROR_SUCCESS;
-
-    if (pa_stMRRequest->DataLength == 1)
-      {
-        switch (pa_stMRRequest->Data[0])
-          {
-        case 0: /* Reset type 0 -> emulate device reset / Power cycle */
-          if (EIP_ERROR == IApp_ResetDevice())
-            {
-              pa_stMRResponse->GeneralStatus = CIP_ERROR_INVALID_PARAMETER;
-            }
-          break;
-
-        case 1: /* Reset type 1 -> reset to device settings */
-          if (EIP_ERROR == IApp_ResetDeviceToInitialConfiguration())
-            {
-              pa_stMRResponse->GeneralStatus = CIP_ERROR_INVALID_PARAMETER;
-            }
-          break;
-
-        // case 2: Not supported /* Reset type 2 -> Return to factory defaults except communications parameters */
-
-        default:
-          pa_stMRResponse->GeneralStatus = CIP_ERROR_INVALID_PARAMETER;
-          break;
-          }
-      }
-    else //TODO: Should be if (pa_stMRRequest->DataLength == 0)
-      {
-        /* The same behavior as if the data value given would be 0
-          emulate device reset */
-
-        if (EIP_ERROR == IApp_ResetDevice())
-          {
-            pa_stMRResponse->GeneralStatus = CIP_ERROR_INVALID_PARAMETER;
-          }
-        else
-          {
-         // nRetVal = EIP_OK;
-          }
-      }
-    pa_stMRResponse->DataLength = 0;
-    return nRetVal;
+    /* The same behavior as if the data value given would be 0
+     emulate device reset */
+
+    if (kEipStatusError == ResetDevice()) {
+      message_router_response->general_status = kCipErrorInvalidParameter;
+    } else {
+      /* eip_status = EIP_OK; */
+    }
   }
   }
+  message_router_response->data_length = 0;
+  return eip_status;
+}
 
 
-/** CIP Identity object constructor
+/** @brief CIP Identity object constructor
  *
  *
  * @returns EIP_ERROR if the class could not be created, otherwise EIP_OK
  * @returns EIP_ERROR if the class could not be created, otherwise EIP_OK
  */
  */
-EIP_STATUS CIP_Identity_Init()
-  {
-    S_CIP_Class *pClass;
-    S_CIP_Instance *pInstance;
-
-    pClass = createCIPClass(CIP_IDENTITY_CLASS_CODE, 0, /* # of non-default class attributes */
-        MASK4(1, 2, 6, 7), /* class getAttributeAll mask		CIP spec 5-2.3.2 */
-        0, /* # of class services*/
-        7, /* # of instance attributes*/
-        MASK7(1, 2, 3, 4, 5, 6, 7), /* instance getAttributeAll mask	CIP spec 5-2.3.2 */
-        1, /* # of instance services*/
-        1, /* # of instances*/
-        "identity", /* class name (for debug)*/
-        1); /* class revision*/
-
-    if (pClass == 0)
-      return EIP_ERROR;
-
-    pInstance = getCIPInstance(pClass, 1);
-
-    insertAttribute(pInstance, 1, CIP_UINT, &VendorID, CIP_ATTRIB_GETABLE);
-    insertAttribute(pInstance, 2, CIP_UINT, &DeviceType, CIP_ATTRIB_GETABLE);
-    insertAttribute(pInstance, 3, CIP_UINT, &ProductCode, CIP_ATTRIB_GETABLE);
-    insertAttribute(pInstance, 4, CIP_USINT_USINT, &Revison, CIP_ATTRIB_GETABLE);
-    insertAttribute(pInstance, 5, CIP_WORD, &ID_Status, CIP_ATTRIB_GETABLE);
-    insertAttribute(pInstance, 6, CIP_UDINT, &SerialNumber, CIP_ATTRIB_GETABLE);
-    insertAttribute(pInstance, 7, CIP_SHORT_STRING, &ProductName, CIP_ATTRIB_GETABLE);
-
-    insertService(pClass, CIP_RESET, &Reset, "Reset");
-
-    return EIP_OK;
-  }
+EipStatus CipIdentityInit() {
+  CipClass *class;
+  CipInstance *instance;
+
+  class = CreateCipClass(kIdentityClassCode, 0, /* # of non-default class attributes */
+                         MASK4(1, 2, 6, 7), /* class getAttributeAll mask		CIP spec 5-2.3.2 */
+                         0, /* # of class services*/
+                         7, /* # of instance attributes*/
+                         MASK7(1, 2, 3, 4, 5, 6, 7), /* instance getAttributeAll mask	CIP spec 5-2.3.2 */
+                         1, /* # of instance services*/
+                         1, /* # of instances*/
+                         "identity", /* class name (for debug)*/
+                         1); /* class revision*/
+
+  if (class == 0)
+    return kEipStatusError;
+
+  instance = GetCipInstance(class, 1);
+
+  InsertAttribute(instance, 1, kCipUint, &vendor_id_, kGetableSingleAndAll);
+  InsertAttribute(instance, 2, kCipUint, &device_type_, kGetableSingleAndAll);
+  InsertAttribute(instance, 3, kCipUint, &product_code_, kGetableSingleAndAll);
+  InsertAttribute(instance, 4, kCipUsintUsint, &revision_,
+                  kGetableSingleAndAll);
+  InsertAttribute(instance, 5, kCipWord, &status_, kGetableSingleAndAll);
+  InsertAttribute(instance, 6, kCipUdint, &serial_number_,
+                  kGetableSingleAndAll);
+  InsertAttribute(instance, 7, kCipShortString, &product_name_,
+                  kGetableSingleAndAll);
+
+  InsertService(class, kReset, &Reset, "Reset");
+
+  return kEipStatusOk;
+}

+ 37 - 25
source/src/cip/cipidentity.h

@@ -3,39 +3,51 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPIDENTITY_H_
-#define CIPIDENTITY_H_
+#ifndef OPENER_CIPIDENTITY_H_
+#define OPENER_CIPIDENTITY_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
 
 
-#define CIP_IDENTITY_CLASS_CODE 0x01
-
-#define CIP_IDENTITY_STATUS_OWNED 0x0001
-#define CIP_IDENTITY_STATUS_CONFIGURED 0x0004
-#define CIP_IDENTITY_STATUS_MINOR_RECOV_FLT 0x0100
-#define CIP_IDENTITY_STATUS_MINOR_UNRECOV_FLT 0x0200
-#define CIP_IDENTITY_STATUS_MAJOR_RECOV_FLT 0x0400
-#define CIP_IDENTITY_STATUS_MAJOR_UNRECOV_FLT 0x0800
-
-#define CIP_IDENTITY_EXTENDED_STATUS_SELFTESTING_UNKNOWN                                     0x0000
-#define CIP_IDENTITY_EXTENDED_STATUS_FIRMEWARE_UPDATE_IN_PROGRESS                            0x0010
-#define CIP_IDENTITY_EXTENDED_STATUS_AT_LEAST_ONE_FAULTED_IO_CONNECTION                      0x0020
-#define CIP_IDENTITY_EXTENDED_STATUS_NO_IO_CONNECTIONS_ESTABLISHED                           0x0030
-#define CIP_IDENTITY_EXTENDED_STATUS_NON_VOLATILE_CONFIGURATION_BAD                          0x0040
-#define CIP_IDENTITY_EXTENDED_STATUS_MAJOR_FAULT                                             0x0050
-#define CIP_IDENTITY_EXTENDED_STATUS_AT_LEAST_ONE_IO_CONNECTION_IN_RUN_MODE                  0x0060
-#define CIP_IDENTITY_EXTENDED_STATUS_AT_LEAST_ONE_IO_CONNECTION_ESTABLISHED_ALL_IN_IDLE_MODE 0x0070
-
+static const int kIdentityClassCode = 0x01;
+
+/** @brief Status of the CIP Identity object */
+typedef enum {
+  kOwned = 0x0001, /**< Indicates that the device has an owner */
+  kConfigured = 0x0004, /**< Indicates that the device is configured to do
+   something different, than the out-of-the-box default. */
+  kMinorRecoverableFault = 0x0100, /**< Indicates that the device detected a
+   fault with itself, which was thought to be recoverable. The device did not
+   switch to a faulted state. */
+  kMinorUncoverableFault = 0x0200, /**< Indicates that the device detected a
+   fault with itself, which was thought to be recoverable. The device did not
+   switch to a faulted state. */
+  kMajorRecoveralbeFault = 0x0400, /**< Indicates that the device detected a
+   fault with itself,which was thought to be recoverable. The device changed
+   to the "Major Recoverable Fault" state */
+  kMajorUnrecoverableFault = 0x0800 /**< Indicates that the device detected a
+   fault with itself,which was thought to be recoverable. The device changed
+   to the "Major Unrecoverable Fault" state */
+} CipIdentityStatus;
+
+typedef enum {
+  kSelftestingUnknown = 0x0000,
+  FirmwareUpdateInProgress = 0x0010,
+  kStatusAtLeastOneFaultedIoConnection = 0x0020,
+  kNoIoConnectionsEstablished = 0x0030,
+  kNonVolatileConfigurationBad = 0x0040,
+  kMajorFault = 0x0050,
+  kAtLeastOneIoConnectionInRuneMode = 0x0060,
+  kAtLeastOneIoConnectionEstablishedAllInIdleMode = 0x0070
+} CipIdentityExtendedStatus;
 
 
 /* global public variables */
 /* global public variables */
 
 
 /* public functions */
 /* public functions */
-/** CIP Identity object contructor
+/** @brief CIP Identity object constructor
  *
  *
- * @returns EIP_ERROR if the class could not be created, otherwise EIP_OK
+ * @returns EipError if the class could not be created, otherwise EipOk
  */
  */
-EIP_STATUS
-CIP_Identity_Init(void);
+EipStatus CipIdentityInit(void);
 
 
-#endif /*CIPIDENTITY_H_*/
+#endif /* OPENER_CIPIDENTITY_H_ */

+ 660 - 720
source/src/cip/cipioconnection.c

@@ -3,7 +3,11 @@
  * All rights reserved.
  * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
+
+#include <string.h>
+
 #include "cipioconnection.h"
 #include "cipioconnection.h"
+
 #include "cipconnectionmanager.h"
 #include "cipconnectionmanager.h"
 #include "cipassembly.h"
 #include "cipassembly.h"
 #include "ciptcpipinterface.h"
 #include "ciptcpipinterface.h"
@@ -12,831 +16,767 @@
 #include "cpf.h"
 #include "cpf.h"
 #include "trace.h"
 #include "trace.h"
 #include "endianconv.h"
 #include "endianconv.h"
-#include <string.h>
 
 
 /*The port to be used per default for I/O messages on UDP.*/
 /*The port to be used per default for I/O messages on UDP.*/
-#define OPENER_EIP_IO_UDP_PORT   0x08AE
+const int kOpenerEipIoUdpPort = 0x08AE;
 
 
 /* producing multicast connection have to consider the rules that apply for
 /* producing multicast connection have to consider the rules that apply for
  * application connection types.
  * application connection types.
  */
  */
-EIP_STATUS
-openProducingMulticastConnection(S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data);
+EipStatus OpenProducingMulticastConnection(
+    ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data);
+
+EipStatus OpenMulticastConnection(
+    UdpCommuncationDirection direction, ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data);
 
 
-EIP_STATUS
-OpenMulticastConnection(int pa_direction, S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data);
+EipStatus OpenConsumingPointToPointConnection(
+    ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data);
 
 
-EIP_STATUS
-OpenConsumingPointToPointConnection(S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data);
+EipStatus OpenProducingPointToPointConnection(
+    ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data);
 
 
-int
-OpenProducingPointToPointConnection(S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data);
-EIP_UINT16
-handleConfigData(S_CIP_Class *pa_pstAssemblyClass,
-    S_CIP_ConnectionObject *pa_pstIOConnObj);
+EipUint16 HandleConfigData(CipClass *assembly_class,
+                           ConnectionObject *connection_object);
 
 
 /* Regularly close the IO connection. If it is an exclusive owner or input only
 /* Regularly close the IO connection. If it is an exclusive owner or input only
  * connection and in charge of the connection a new owner will be searched
  * connection and in charge of the connection a new owner will be searched
  */
  */
-void
-closeIOConnection(S_CIP_ConnectionObject *pa_pstConnObjData);
+void CloseIoConnection(ConnectionObject *connection_object);
 
 
-void
-handleIOConnectionTimeOut(S_CIP_ConnectionObject *pa_pstConn);
+void HandleIoConnectionTimeOut(ConnectionObject *connection_object);
 
 
-/*!  Send the data from the produced CIP Object of the connection via the socket of the connection object
+/** @brief  Send the data from the produced CIP Object of the connection via the socket of the connection object
  *   on UDP.
  *   on UDP.
- *      @param pa_pstConnection  pointer to the connection object
+ *      @param connection_object  pointer to the connection object
  *      @return status  EIP_OK .. success
  *      @return status  EIP_OK .. success
  *                     EIP_ERROR .. error
  *                     EIP_ERROR .. error
  */
  */
-EIP_STATUS
-sendConnectedData(S_CIP_ConnectionObject *pa_pstConnection);
+EipStatus SendConnectedData(ConnectionObject *connection_object);
+
+EipStatus HandleReceivedIoConnectionData(ConnectionObject *connection_object,
+                                         EipUint8 *data, EipUint16 data_length);
 
 
-EIP_STATUS
-handleReceivedIOConnData(struct CIP_ConnectionObject *pa_pstConnection,
-    EIP_UINT8 * pa_pnData, EIP_UINT16 pa_nDataLength);
 /**** Global variables ****/
 /**** Global variables ****/
-/* buffers for the config data coming with a forward open request.
- */EIP_UINT8 *g_pnConfigDataBuffer = NULL;
-unsigned int g_unConfigDataLen = 0;
-/*! buffer for holding the run idle information.                             */EIP_UINT32 g_nRunIdleState;
+EipUint8 *g_config_data_buffer = NULL; /**< buffers for the config data coming with a forward open request. */
+unsigned int g_config_data_length = 0;
 
 
-/**** Implementation ****/
+EipUint32 g_run_idle_state; /**< buffer for holding the run idle information. */
 
 
-int
-establishIOConnction(struct CIP_ConnectionObject *pa_pstConnObjData,
-    EIP_UINT16 *pa_pnExtendedError)
-{
-  int O2TConnectionType, T2OConnectionType;
-  int nRetVal = EIP_OK;
-  S_CIP_attribute_struct *pstAttribute;
+/**** Implementation ****/
+int EstablishIoConnction(ConnectionObject *connection_object,
+                         EipUint16 *extended_error) {
+  int originator_to_target_connection_type,
+      target_to_originator_connection_type;
+  int eip_status = kEipStatusOk;
+  CipAttributeStruct *attribute;
   /* currently we allow I/O connections only to assembly objects */
   /* currently we allow I/O connections only to assembly objects */
-  S_CIP_Class *pstAssemblyClass = getCIPClass(CIP_ASSEMBLY_CLASS_CODE); /* we don't need to check for zero as this is handled in the connection path parsing */
-  S_CIP_Instance *pstInstance = NULL;
-
-  S_CIP_ConnectionObject *pstIOConnObj = getIOConnectionForConnectionData(
-      pa_pstConnObjData, pa_pnExtendedError);
-
-  if (NULL == pstIOConnObj)
-    {
-      return CIP_ERROR_CONNECTION_FAILURE;
-    }
-
-  //TODO add check for transport type trigger
-
-  if (CIP_CONN_CYCLIC_CONNECTION
-      != (pstIOConnObj->TransportTypeClassTrigger
-          & CIP_CONN_PRODUCTION_TRIGGER_MASK))
-    {
-      if (256 == pstIOConnObj->m_unProductionInhibitTime)
-        {
-          /* there was no PIT segment in the connection path set PIT to one fourth of RPI */
-          pstIOConnObj->m_unProductionInhibitTime = ((EIP_UINT16)(
-              pstIOConnObj->T_to_O_RPI) / 4000);
+  CipClass *assembly_class = GetCipClass(kCipAssemblyClassCode); /* we don't need to check for zero as this is handled in the connection path parsing */
+  CipInstance *instance = NULL;
+
+  ConnectionObject *io_connection_object = GetIoConnectionForConnectionData(
+      connection_object, extended_error);
+
+  if (NULL == io_connection_object) {
+    return kCipErrorConnectionFailure;
+  }
+
+  /* TODO add check for transport type trigger */
+
+  if (kConnectionTriggerTypeCyclicConnection
+      != (io_connection_object->transport_type_class_trigger
+          & kConnectionTriggerTypeProductionTriggerMask)) {
+    if (256 == io_connection_object->production_inhibit_time) {
+      /* there was no PIT segment in the connection path set PIT to one fourth of RPI */
+      io_connection_object->production_inhibit_time =
+          ((EipUint16) (io_connection_object->t_to_o_requested_packet_interval)
+              / 4000);
+    } else {
+      /* if production inhibit time has been provided it needs to be smaller than the RPI */
+      if (io_connection_object->production_inhibit_time
+          > ((EipUint16) ((io_connection_object
+              ->t_to_o_requested_packet_interval) / 1000))) {
+        /* see section C-1.4.3.3 */
+        *extended_error = 0x111; /**< RPI not supported. Extended Error code deprecated */
+        return kCipErrorConnectionFailure;
+      }
+    }
+  }
+  /* set the connection call backs */
+  io_connection_object->connection_close_function = CloseIoConnection;
+  io_connection_object->connection_timeout_function = HandleIoConnectionTimeOut;
+  io_connection_object->connection_send_data_function = SendConnectedData;
+  io_connection_object->connection_receive_data_function =
+      HandleReceivedIoConnectionData;
+
+  GeneralConnectionConfiguration(io_connection_object);
+
+  originator_to_target_connection_type = (io_connection_object
+      ->o_to_t_network_connection_parameter & 0x6000) >> 13;
+  target_to_originator_connection_type = (io_connection_object
+      ->t_to_o_network_connection_parameter & 0x6000) >> 13;
+
+  if ((originator_to_target_connection_type == 0)
+      && (target_to_originator_connection_type == 0)) { /* this indicates an re-configuration of the connection currently not supported and we should not come here as this is handled in the forwardopen function*/
+
+  } else {
+    int producing_index = 0;
+    int data_size;
+    int diff_size;
+    int is_heartbeat;
+
+    if ((originator_to_target_connection_type != 0)
+        && (target_to_originator_connection_type != 0)) { /* we have a producing and consuming connection*/
+      producing_index = 1;
+    }
+
+    io_connection_object->consuming_instance = 0;
+    io_connection_object->consumed_connection_path_length = 0;
+    io_connection_object->producing_instance = 0;
+    io_connection_object->produced_connection_path_length = 0;
+
+    if (originator_to_target_connection_type != 0) { /*setup consumer side*/
+      if (0
+          != (instance = GetCipInstance(
+              assembly_class,
+              io_connection_object->connection_path.connection_point[0]))) { /* consuming Connection Point is present */
+        io_connection_object->consuming_instance = instance;
+
+        io_connection_object->consumed_connection_path_length = 6;
+        io_connection_object->consumed_connection_path.path_size = 6;
+        io_connection_object->consumed_connection_path.class_id =
+            io_connection_object->connection_path.class_id;
+        io_connection_object->consumed_connection_path.instance_number =
+            io_connection_object->connection_path.connection_point[0];
+        io_connection_object->consumed_connection_path.attribute_number = 3;
+
+        attribute = GetCipAttribute(instance, 3);
+        OPENER_ASSERT(attribute != NULL);
+        /* an assembly object should always have an attribute 3 */
+        data_size = io_connection_object->consumed_connection_size;
+        diff_size = 0;
+        is_heartbeat = (((CipByteArray *) attribute->data)->length == 0);
+
+        if ((io_connection_object->transport_type_class_trigger & 0x0F) == 1) {
+          /* class 1 connection */
+          data_size -= 2; /* remove 16-bit sequence count length */
+          diff_size += 2;
         }
         }
-      else
-        {
-          /* if production inhibit time has been provided it needs to be smaller than the RPI */
-          if (pstIOConnObj->m_unProductionInhibitTime
-              > ((EIP_UINT16)((pstIOConnObj->T_to_O_RPI) / 1000)))
-            {
-              /* see section C-1.4.3.3 */
-              *pa_pnExtendedError = 0x111;
-              return 0x01;
-            }
+        if ((kOpenerConsumedDataHasRunIdleHeader) &&(data_size > 0)
+            && (!is_heartbeat)) { /* we only have an run idle header if it is not an heartbeat connection */
+          data_size -= 4; /* remove the 4 bytes needed for run/idle header */
+          diff_size += 4;
         }
         }
-    }
-  /* set the connection call backs */
-  pstIOConnObj->m_pfCloseFunc = closeIOConnection;
-  pstIOConnObj->m_pfTimeOutFunc = handleIOConnectionTimeOut;
-  pstIOConnObj->m_pfSendDataFunc = sendConnectedData;
-  pstIOConnObj->m_pfReceiveDataFunc = handleReceivedIOConnData;
-
-  generalConnectionConfiguration(pstIOConnObj);
-
-  O2TConnectionType = (pstIOConnObj->O_to_T_NetworkConnectionParameter & 0x6000)
-      >> 13;
-  T2OConnectionType = (pstIOConnObj->T_to_O_NetworkConnectionParameter & 0x6000)
-      >> 13;
-
-  if ((O2TConnectionType == 0) && (T2OConnectionType == 0))
-    { /* this indicates an re-configuration of the connection currently not supported and we should not come here as this is handled in the forwardopen function*/
-
-    }
-  else
-    {
-      int nProducingIndex = 0;
-      int nDataSize;
-      int nDiffSize;
-      int nIsHeartbeat;
-
-      if ((O2TConnectionType != 0) && (T2OConnectionType != 0))
-        { /* we have a producing and consuming connection*/
-          nProducingIndex = 1;
+        if (((CipByteArray *) attribute->data)->length != data_size) {
+          /*wrong connection size */
+          connection_object->correct_originator_to_target_size =
+              ((CipByteArray *) attribute->data)->length + diff_size;
+          *extended_error =
+              kConnectionManagerStatusCodeErrorInvalidOToTConnectionSize;
+          return kCipErrorConnectionFailure;
         }
         }
-
-      pstIOConnObj->p_stConsumingInstance = 0;
-      pstIOConnObj->ConsumedConnectionPathLength = 0;
-      pstIOConnObj->p_stProducingInstance = 0;
-      pstIOConnObj->ProducedConnectionPathLength = 0;
-
-      if (O2TConnectionType != 0)
-        { /*setup consumer side*/
-          if (0
-              != (pstInstance = getCIPInstance(pstAssemblyClass,
-                  pstIOConnObj->ConnectionPath.ConnectionPoint[0])))
-            { /* consuming Connection Point is present */
-              pstIOConnObj->p_stConsumingInstance = pstInstance;
-
-              pstIOConnObj->ConsumedConnectionPathLength = 6;
-              pstIOConnObj->ConsumedConnectionPath.PathSize = 6;
-              pstIOConnObj->ConsumedConnectionPath.ClassID =
-                  pstIOConnObj->ConnectionPath.ClassID;
-              pstIOConnObj->ConsumedConnectionPath.InstanceNr =
-                  pstIOConnObj->ConnectionPath.ConnectionPoint[0];
-              pstIOConnObj->ConsumedConnectionPath.AttributNr = 3;
-
-              pstAttribute = getAttribute(pstInstance, 3);
-              OPENER_ASSERT(pstAttribute != NULL);
-              /* an assembly object should always have an attribute 3 */
-              nDataSize = pstIOConnObj->ConsumedConnectionSize;
-              nDiffSize = 0;
-              nIsHeartbeat = (((S_CIP_Byte_Array *) pstAttribute->pt2data)->len == 0);
-
-              if ((pstIOConnObj->TransportTypeClassTrigger & 0x0F) == 1)
-                {
-                  /* class 1 connection */
-                  nDataSize -= 2; /* remove 16-bit sequence count length */
-                  nDiffSize += 2;
-                }
-              if ((OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER) && (nDataSize > 0) && (!nIsHeartbeat))
-                { /* we only have an run idle header if it is not an heartbeat connection */
-                  nDataSize -= 4; /* remove the 4 bytes needed for run/idle header */
-                  nDiffSize += 4;
-                }
-              if (((S_CIP_Byte_Array *) pstAttribute->pt2data)->len
-                  != nDataSize)
-                {
-                  /*wrong connection size */
-                  pa_pstConnObjData->CorrectOTSize = ((S_CIP_Byte_Array *) pstAttribute->pt2data)->len + nDiffSize;
-                  *pa_pnExtendedError = CIP_CON_MGR_ERROR_INVALID_O_TO_T_CONNECTION_SIZE;
-                  return CIP_ERROR_CONNECTION_FAILURE;
-                }
-            }
-          else
-            {
-              *pa_pnExtendedError =
-                  CIP_CON_MGR_INVALID_CONSUMING_APPLICATION_PATH;
-              return CIP_ERROR_CONNECTION_FAILURE;
-            }
+      } else {
+        *extended_error =
+            kConnectionManagerStatusCodeInvalidConsumingApllicationPath;
+        return kCipErrorConnectionFailure;
+      }
+    }
+
+    if (target_to_originator_connection_type != 0) { /*setup producer side*/
+      if (0
+          != (instance =
+              GetCipInstance(
+                  assembly_class,
+                  io_connection_object->connection_path.connection_point[producing_index]))) {
+        io_connection_object->producing_instance = instance;
+
+        io_connection_object->produced_connection_path_length = 6;
+        io_connection_object->produced_connection_path.path_size = 6;
+        io_connection_object->produced_connection_path.class_id =
+            io_connection_object->connection_path.class_id;
+        io_connection_object->produced_connection_path.instance_number =
+            io_connection_object->connection_path.connection_point[producing_index];
+        io_connection_object->produced_connection_path.attribute_number = 3;
+
+        attribute = GetCipAttribute(instance, 3);
+        OPENER_ASSERT(attribute != NULL);
+        /* an assembly object should always have an attribute 3 */
+        data_size = io_connection_object->produced_connection_size;
+        diff_size = 0;
+        is_heartbeat = (((CipByteArray *) attribute->data)->length == 0);
+
+        if ((io_connection_object->transport_type_class_trigger & 0x0F) == 1) {
+          /* class 1 connection */
+          data_size -= 2; /* remove 16-bit sequence count length */
+          diff_size += 2;
         }
         }
-
-      if (T2OConnectionType != 0)
-        { /*setup producer side*/
-          if (0
-              != (pstInstance = getCIPInstance(pstAssemblyClass,
-                  pstIOConnObj->ConnectionPath.ConnectionPoint[nProducingIndex])))
-            {
-              pstIOConnObj->p_stProducingInstance = pstInstance;
-
-              pstIOConnObj->ProducedConnectionPathLength = 6;
-              pstIOConnObj->ProducedConnectionPath.PathSize = 6;
-              pstIOConnObj->ProducedConnectionPath.ClassID =
-                  pstIOConnObj->ConnectionPath.ClassID;
-              pstIOConnObj->ProducedConnectionPath.InstanceNr =
-                  pstIOConnObj->ConnectionPath.ConnectionPoint[nProducingIndex];
-              pstIOConnObj->ProducedConnectionPath.AttributNr = 3;
-
-              pstAttribute = getAttribute(pstInstance, 3);
-              OPENER_ASSERT(pstAttribute != NULL);
-              /* an assembly object should always have an attribute 3 */
-              nDataSize = pstIOConnObj->ProducedConnectionSize;
-              nDiffSize = 0;
-              nIsHeartbeat = (((S_CIP_Byte_Array *) pstAttribute->pt2data)->len == 0);
-
-              if ((pstIOConnObj->TransportTypeClassTrigger & 0x0F) == 1)
-                {
-                  /* class 1 connection */
-                  nDataSize -= 2; /* remove 16-bit sequence count length */
-                  nDiffSize += 2;
-                }
-              if ((OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER) && (nDataSize > 0) && (!nIsHeartbeat))
-                { /* we only have an run idle header if it is not an heartbeat connection */
-                  nDataSize -= 4; /* remove the 4 bytes needed for run/idle header */
-                  nDiffSize += 4;
-                }
-              if (((S_CIP_Byte_Array *) pstAttribute->pt2data)->len
-                  != nDataSize)
-                {
-                  /*wrong connection size*/
-                  pa_pstConnObjData->CorrectTOSize = ((S_CIP_Byte_Array *) pstAttribute->pt2data)->len + nDiffSize;
-                  *pa_pnExtendedError = CIP_CON_MGR_ERROR_INVALID_T_TO_O_CONNECTION_SIZE;
-                  return CIP_ERROR_CONNECTION_FAILURE;
-                }
-
-            }
-          else
-            {
-              *pa_pnExtendedError =
-                  CIP_CON_MGR_INVALID_PRODUCING_APPLICATION_PATH;
-              return CIP_ERROR_CONNECTION_FAILURE;
-            }
+        if ((kOpenerProducedDataHasRunIdleHeader) &&(data_size > 0)
+            && (!is_heartbeat)) { /* we only have an run idle header if it is not an heartbeat connection */
+          data_size -= 4; /* remove the 4 bytes needed for run/idle header */
+          diff_size += 4;
         }
         }
-
-      if (NULL != g_pnConfigDataBuffer)
-        { /* config data has been sent with this forward open request */
-          *pa_pnExtendedError = handleConfigData(pstAssemblyClass,
-              pstIOConnObj);
-          if (0 != *pa_pnExtendedError)
-            {
-              return CIP_ERROR_CONNECTION_FAILURE;
-            }
+        if (((CipByteArray *) attribute->data)->length != data_size) {
+          /*wrong connection size*/
+          connection_object->correct_target_to_originator_size =
+              ((CipByteArray *) attribute->data)->length + diff_size;
+          *extended_error =
+              kConnectionManagerStatusCodeErrorInvalidTToOConnectionSize;
+          return kCipErrorConnectionFailure;
         }
         }
 
 
-      nRetVal = openCommunicationChannels(pstIOConnObj);
-      if (EIP_OK != nRetVal)
-        {
-          *pa_pnExtendedError = 0; /*TODO find out the correct extended error code*/
-          return nRetVal;
-        }
+      } else {
+        *extended_error =
+            kConnectionManagerStatusCodeInvalidProducingApplicationPath;
+        return kCipErrorConnectionFailure;
+      }
+    }
+
+    if (NULL != g_config_data_buffer) { /* config data has been sent with this forward open request */
+      *extended_error = HandleConfigData(assembly_class, io_connection_object);
+      if (0 != *extended_error) {
+        return kCipErrorConnectionFailure;
+      }
+    }
+
+    eip_status = OpenCommunicationChannels(io_connection_object);
+    if (kEipStatusOk != eip_status) {
+      *extended_error = 0; /*TODO find out the correct extended error code*/
+      return eip_status;
     }
     }
+  }
 
 
-  addNewActiveConnection(pstIOConnObj);
-  IApp_IOConnectionEvent(pstIOConnObj->ConnectionPath.ConnectionPoint[0],
-      pstIOConnObj->ConnectionPath.ConnectionPoint[1], enOpened);
-  return nRetVal;
+  AddNewActiveConnection(io_connection_object);
+  IoConnectionEvent(io_connection_object->connection_path.connection_point[0],
+                    io_connection_object->connection_path.connection_point[1],
+                    kOpenedEvent);
+  return eip_status;
 }
 }
 
 
-/*   EIP_STATUS OpenPointToPointConnection(S_CIP_CPF_Data *pa_CPF_data, S_CIP_CM_Object *pa_pstCMObject, INT8 pa_direction, int pa_index)
- *   open a Point2Point connection dependent on pa_direction.
- *      pa_pstCMObject  pointer to registered Object in ConnectionManager.
- *      pa_index        index of the connection object
- *  return status
+/*   @brief Open a Point2Point connection dependent on pa_direction.
+ *   @param connection_object Pointer to registered Object in ConnectionManager.
+ *   @param common_packet_format_data Index of the connection object
+ *   @return status
  *               0 .. success
  *               0 .. success
  *              -1 .. error
  *              -1 .. error
  */
  */
-
-EIP_STATUS
-OpenConsumingPointToPointConnection(S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data)
-{
+EipStatus OpenConsumingPointToPointConnection(
+    ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data) {
   /*static EIP_UINT16 nUDPPort = 2222; TODO think on improving the udp port assigment for point to point connections */
   /*static EIP_UINT16 nUDPPort = 2222; TODO think on improving the udp port assigment for point to point connections */
-  int j;
+  int j = 0;
   struct sockaddr_in addr;
   struct sockaddr_in addr;
-  int newfd;
+  int socket;
 
 
-  j = 0;
-  if (pa_CPF_data->AddrInfo[0].TypeID == 0)
-    { /* it is not used yet */
-      j = 0;
-    }
-  else if (pa_CPF_data->AddrInfo[1].TypeID == 0)
-    {
-      j = 1;
-    }
+  if (common_packet_format_data->address_info_item[0].type_id == 0) { /* it is not used yet */
+    j = 0;
+  } else if (common_packet_format_data->address_info_item[1].type_id == 0) {
+    j = 1;
+  }
 
 
   addr.sin_family = AF_INET;
   addr.sin_family = AF_INET;
   addr.sin_addr.s_addr = INADDR_ANY;
   addr.sin_addr.s_addr = INADDR_ANY;
   /*addr.in_port = htons(nUDPPort++);*/
   /*addr.in_port = htons(nUDPPort++);*/
-  addr.sin_port = htons(OPENER_EIP_IO_UDP_PORT);
-
-  newfd = IApp_CreateUDPSocket(CONSUMING, &addr); /* the address is only needed for bind used if consuming */
-  if (newfd == EIP_INVALID_SOCKET)
-    {
-      OPENER_TRACE_ERR(
-          "cannot create UDP socket in OpenPointToPointConnection\n");
-      return EIP_ERROR;
-    }
+  addr.sin_port = htons(kOpenerEipIoUdpPort);
 
 
-  pa_pstConnObj->m_stOriginatorAddr = addr; /* store the address of the originator for packet scanning */
+  socket = CreateUdpSocket(kUdpCommuncationDirectionConsuming, &addr); /* the address is only needed for bind used if consuming */
+  if (socket == kEipInvalidSocket) {
+    OPENER_TRACE_ERR(
+        "cannot create UDP socket in OpenPointToPointConnection\n");
+    return kEipStatusError;
+  }
+
+  connection_object->originator_address = addr; /* store the address of the originator for packet scanning */
   addr.sin_addr.s_addr = INADDR_ANY; /* restore the address */
   addr.sin_addr.s_addr = INADDR_ANY; /* restore the address */
-  pa_pstConnObj->sockfd[CONSUMING] = newfd;
+  connection_object->socket[kUdpCommuncationDirectionConsuming] = socket;
 
 
-  pa_CPF_data->AddrInfo[j].Length = 16;
-  pa_CPF_data->AddrInfo[j].TypeID = CIP_ITEM_ID_SOCKADDRINFO_O_TO_T;
+  common_packet_format_data->address_info_item[j].length = 16;
+  common_packet_format_data->address_info_item[j].type_id =
+      kSocketAddressInfoOriginatorToTargetId;
 
 
-  pa_CPF_data->AddrInfo[j].nsin_port = addr.sin_port;
+  common_packet_format_data->address_info_item[j].nsin_port = addr.sin_port;
   /*TODO should we add our own address here? */
   /*TODO should we add our own address here? */
-  pa_CPF_data->AddrInfo[j].nsin_addr = addr.sin_addr.s_addr;
-  memset(pa_CPF_data->AddrInfo[j].nasin_zero, 0, 8);
-  pa_CPF_data->AddrInfo[j].nsin_family = htons(AF_INET);
+  common_packet_format_data->address_info_item[j].nsin_addr = addr.sin_addr
+      .s_addr;
+  memset(common_packet_format_data->address_info_item[j].nasin_zero, 0, 8);
+  common_packet_format_data->address_info_item[j].nsin_family = htons(AF_INET);
 
 
-  return EIP_OK;
+  return kEipStatusOk;
 }
 }
 
 
-int
-OpenProducingPointToPointConnection(S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data)
-{
-  int newfd;
-  in_port_t nPort = htons(OPENER_EIP_IO_UDP_PORT); /* the default port to be used if no port information is part of the forward open request */
-
-  if (CIP_ITEM_ID_SOCKADDRINFO_T_TO_O == pa_CPF_data->AddrInfo[0].TypeID)
-    {
-      nPort = pa_CPF_data->AddrInfo[0].nsin_port;
-    }
-  else
-    {
-      if (CIP_ITEM_ID_SOCKADDRINFO_T_TO_O == pa_CPF_data->AddrInfo[1].TypeID)
-        {
-          nPort = pa_CPF_data->AddrInfo[1].nsin_port;
-        }
-    }
-
-  pa_pstConnObj->remote_addr.sin_family = AF_INET;
-  pa_pstConnObj->remote_addr.sin_addr.s_addr = 0; /* we don't know the address of the originate will be set in the IApp_CreateUDPSocket */
-  pa_pstConnObj->remote_addr.sin_port = nPort;
-
-  newfd = IApp_CreateUDPSocket(PRODUCING, &pa_pstConnObj->remote_addr); /* the address is only needed for bind used if consuming */
-  if (newfd == EIP_INVALID_SOCKET)
-    {
-      OPENER_TRACE_ERR(
-          "cannot create UDP socket in OpenPointToPointConnection\n");
-      //*pa_pnExtendedError = 0x0315; /* miscellaneous*/
-      return CIP_ERROR_CONNECTION_FAILURE;
-    }
-  pa_pstConnObj->sockfd[PRODUCING] = newfd;
-
-  return EIP_OK;
+EipStatus OpenProducingPointToPointConnection(
+    ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data) {
+  int socket;
+  in_port_t port = htons(kOpenerEipIoUdpPort); /* the default port to be used if no port information is part of the forward open request */
+
+  if (kSocketAddressInfoTargetToOriginatorId
+      == common_packet_format_data->address_info_item[0].type_id) {
+    port = common_packet_format_data->address_info_item[0].nsin_port;
+  } else {
+    if (kSocketAddressInfoTargetToOriginatorId
+        == common_packet_format_data->address_info_item[1].type_id) {
+      port = common_packet_format_data->address_info_item[1].nsin_port;
+    }
+  }
+
+  connection_object->remote_address.sin_family = AF_INET;
+  connection_object->remote_address.sin_addr.s_addr = 0; /* we don't know the address of the originate will be set in the IApp_CreateUDPSocket */
+  connection_object->remote_address.sin_port = port;
+
+  socket = CreateUdpSocket(kUdpCommuncationDirectionProducing,
+                           &connection_object->remote_address); /* the address is only needed for bind used if consuming */
+  if (socket == kEipInvalidSocket) {
+    OPENER_TRACE_ERR(
+        "cannot create UDP socket in OpenPointToPointConnection\n");
+    /* *pa_pnExtendedError = 0x0315; miscellaneous*/
+    return kCipErrorConnectionFailure;
+  }
+  connection_object->socket[kUdpCommuncationDirectionProducing] = socket;
+
+  return kEipStatusOk;
 }
 }
 
 
-EIP_STATUS
-openProducingMulticastConnection(S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data)
-{
-  S_CIP_ConnectionObject *pstExistingConn = getExistingProdMulticastConnection(
-      pa_pstConnObj->ConnectionPath.ConnectionPoint[1]);
+EipStatus OpenProducingMulticastConnection(
+    ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data) {
+  ConnectionObject *existing_connection_object =
+      GetExistingProducerMulticastConnection(
+          connection_object->connection_path.connection_point[1]);
   int j;
   int j;
 
 
-  if (NULL == pstExistingConn)
-    { /* we are the first connection producing for the given Input Assembly */
-      return OpenMulticastConnection(PRODUCING, pa_pstConnObj, pa_CPF_data);
-    }
-  else
-    {
-      /* we need to infrom our originator on the correct connection id */
-      pa_pstConnObj->CIPProducedConnectionID =
-          pstExistingConn->CIPProducedConnectionID;
-    }
+  if (NULL == existing_connection_object) { /* we are the first connection producing for the given Input Assembly */
+    return OpenMulticastConnection(kUdpCommuncationDirectionProducing,
+                                   connection_object, common_packet_format_data);
+  } else {
+    /* we need to infrom our originator on the correct connection id */
+    connection_object->produced_connection_id = existing_connection_object
+        ->produced_connection_id;
+  }
 
 
   /* we have a connection reuse the data and the socket */
   /* we have a connection reuse the data and the socket */
 
 
   j = 0; /* allocate an unused sockaddr struct to use */
   j = 0; /* allocate an unused sockaddr struct to use */
-  if (g_stCPFDataItem.AddrInfo[0].TypeID == 0)
-    { /* it is not used yet */
-      j = 0;
-    }
-  else if (g_stCPFDataItem.AddrInfo[1].TypeID == 0)
-    {
-      j = 1;
-    }
-
-  if (enConnTypeIOExclusiveOwner == pa_pstConnObj->m_eInstanceType)
-    {
-      /* eclusive owners take the socket and further manage the connection
-       * especially in the case of time outs.
-       */
-      pa_pstConnObj->sockfd[PRODUCING] = pstExistingConn->sockfd[PRODUCING];
-      pstExistingConn->sockfd[PRODUCING] = EIP_INVALID_SOCKET;
-    }
-  else
-    { /* this connection will not produce the data */
-      pa_pstConnObj->sockfd[PRODUCING] = EIP_INVALID_SOCKET;
-    }
-
-  pa_CPF_data->AddrInfo[j].Length = 16;
-  pa_CPF_data->AddrInfo[j].TypeID = CIP_ITEM_ID_SOCKADDRINFO_T_TO_O;
-  pa_pstConnObj->remote_addr.sin_family = AF_INET;
-  pa_pstConnObj->remote_addr.sin_port = pa_CPF_data->AddrInfo[j].nsin_port =
-      htons(OPENER_EIP_IO_UDP_PORT);
-  pa_pstConnObj->remote_addr.sin_addr.s_addr =
-      pa_CPF_data->AddrInfo[j].nsin_addr =
-          g_stMultiCastconfig.m_unMcastStartAddr;
-  memset(pa_CPF_data->AddrInfo[j].nasin_zero, 0, 8);
-  pa_CPF_data->AddrInfo[j].nsin_family = htons(AF_INET);
-
-  return EIP_OK;
+  if (g_common_packet_format_data_item.address_info_item[0].type_id == 0) { /* it is not used yet */
+    j = 0;
+  } else if (g_common_packet_format_data_item.address_info_item[1].type_id
+      == 0) {
+    j = 1;
+  }
+
+  if (kConnectionTypeIoExclusiveOwner == connection_object->instance_type) {
+    /* exclusive owners take the socket and further manage the connection
+     * especially in the case of time outs.
+     */
+    connection_object->socket[kUdpCommuncationDirectionProducing] =
+        existing_connection_object->socket[kUdpCommuncationDirectionProducing];
+    existing_connection_object->socket[kUdpCommuncationDirectionProducing] =
+        kEipInvalidSocket;
+  } else { /* this connection will not produce the data */
+    connection_object->socket[kUdpCommuncationDirectionProducing] =
+        kEipInvalidSocket;
+  }
+
+  common_packet_format_data->address_info_item[j].length = 16;
+  common_packet_format_data->address_info_item[j].type_id =
+      kSocketAddressInfoTargetToOriginatorId;
+  connection_object->remote_address.sin_family = AF_INET;
+  connection_object->remote_address.sin_port = common_packet_format_data
+      ->address_info_item[j].nsin_port = htons(kOpenerEipIoUdpPort);
+  connection_object->remote_address.sin_addr.s_addr = common_packet_format_data
+      ->address_info_item[j].nsin_addr = g_multicast_configuration
+      .starting_multicast_address;
+  memset(common_packet_format_data->address_info_item[j].nasin_zero, 0, 8);
+  common_packet_format_data->address_info_item[j].nsin_family = htons(AF_INET);
+
+  return kEipStatusOk;
 }
 }
 
 
-/*   INT8 OpenMulticastConnection(S_CIP_CPF_Data *pa_CPF_data, S_CIP_CM_Object *pa_pstCMObject, INT8 pa_direction, int pa_index)
- *   open a Multicast connection dependent on pa_direction.
- *      pa_CPF_data     received CPF Data Item.
- *      pa_pstCMObject  pointer to registered Object in ConnectionManager.
- *      pa_direction    flag to indicate if consuming or producing.
- *      pa_index        index of the connection object
- *  return status
+/*   @brief Open a Multicast connection dependent on @var direction.
+ *
+ *   @param direction Flag to indicate if consuming or producing.
+ *   @param connection_object  pointer to registered Object in ConnectionManager.
+ *   @param common_packet_format_data     received CPF Data Item.
+ *   @return status
  *               0 .. success
  *               0 .. success
  *              -1 .. error
  *              -1 .. error
  */
  */
-EIP_STATUS
-OpenMulticastConnection(int pa_direction, S_CIP_ConnectionObject *pa_pstConnObj,
-    S_CIP_CPF_Data *pa_CPF_data)
-{
+EipStatus OpenMulticastConnection(
+    UdpCommuncationDirection direction, ConnectionObject *connection_object,
+    CipCommonPacketFormatData *common_packet_format_data) {
   int j;
   int j;
-  struct sockaddr_in addr;
-  int newfd;
+  struct sockaddr_in socket_address;
+  int socket;
 
 
   j = 0; /* allocate an unused sockaddr struct to use */
   j = 0; /* allocate an unused sockaddr struct to use */
-  if (0 != g_stCPFDataItem.AddrInfo[0].TypeID)
-    {
-      if ((CONSUMING == pa_direction)
-          && (CIP_ITEM_ID_SOCKADDRINFO_O_TO_T == pa_CPF_data->AddrInfo[0].TypeID))
-        {
-          /* for consuming connection points the originator can choos the multicast address to use
-           * we have a given address type so use it */
-        }
-      else
-        {
-          j = 1;
-          /* if the type is not zero (not used) or if a given tpye it has to be the correct one */
-          if ((0 != g_stCPFDataItem.AddrInfo[1].TypeID)
-              && (!((CONSUMING == pa_direction)
-                  && (CIP_ITEM_ID_SOCKADDRINFO_O_TO_T
-                      == pa_CPF_data->AddrInfo[0].TypeID))))
-            {
-              OPENER_TRACE_ERR("no suitable addr info item available\n");
-              return EIP_ERROR;
-            }
-        }
-    }
-
-  if (0 == pa_CPF_data->AddrInfo[j].TypeID)
-    { /* we are using an unused item initialize it with the default multicast address */
-      pa_CPF_data->AddrInfo[j].nsin_family = htons(AF_INET);
-      pa_CPF_data->AddrInfo[j].nsin_port = htons(OPENER_EIP_IO_UDP_PORT);
-      pa_CPF_data->AddrInfo[j].nsin_addr =
-          g_stMultiCastconfig.m_unMcastStartAddr;
-      memset(pa_CPF_data->AddrInfo[j].nasin_zero, 0, 8);
-      pa_CPF_data->AddrInfo[j].Length = 16;
-    }
-
-  if (htons(AF_INET) != pa_CPF_data->AddrInfo[j].nsin_family)
-    {
-      OPENER_TRACE_ERR("Sockaddr Info Item with wrong sin family value recieved\n");
-      return EIP_ERROR;
-    }
-
-  addr.sin_family = ntohs(pa_CPF_data->AddrInfo[j].nsin_family);
-  addr.sin_addr.s_addr = pa_CPF_data->AddrInfo[j].nsin_addr;
-  addr.sin_port = pa_CPF_data->AddrInfo[j].nsin_port;
-
-  newfd = IApp_CreateUDPSocket(pa_direction, &addr); /* the address is only needed for bind used if consuming */
-  if (newfd == EIP_INVALID_SOCKET)
-    {
-      OPENER_TRACE_ERR("cannot create UDP socket in OpenMulticastConnection\n");
-      return EIP_ERROR;
-    }
-  pa_pstConnObj->sockfd[pa_direction] = newfd;
-
-  if (pa_direction == CONSUMING)
-    {
-      pa_CPF_data->AddrInfo[j].TypeID = CIP_ITEM_ID_SOCKADDRINFO_O_TO_T;
-      pa_pstConnObj->m_stOriginatorAddr = addr;
-    }
-  else
-    {
-      pa_CPF_data->AddrInfo[j].TypeID = CIP_ITEM_ID_SOCKADDRINFO_T_TO_O;
-      pa_pstConnObj->remote_addr = addr;
-    }
-
-  return EIP_OK;
+  if (0 != g_common_packet_format_data_item.address_info_item[0].type_id) {
+    if ((kUdpCommuncationDirectionConsuming == direction)
+        && (kSocketAddressInfoOriginatorToTargetId
+            == common_packet_format_data->address_info_item[0].type_id)) {
+      /* for consuming connection points the originator can choos the multicast address to use
+       * we have a given address type so use it */
+    } else {
+      j = 1;
+      /* if the type is not zero (not used) or if a given tpye it has to be the correct one */
+      if ((0 != g_common_packet_format_data_item.address_info_item[1].type_id)
+          && (!((kUdpCommuncationDirectionConsuming == direction)
+              && (kSocketAddressInfoOriginatorToTargetId
+                  == common_packet_format_data->address_info_item[0].type_id)))) {
+        OPENER_TRACE_ERR("no suitable addr info item available\n");
+        return kEipStatusError;
+      }
+    }
+  }
+
+  if (0 == common_packet_format_data->address_info_item[j].type_id) { /* we are using an unused item initialize it with the default multicast address */
+    common_packet_format_data->address_info_item[j].nsin_family = htons(
+        AF_INET);
+    common_packet_format_data->address_info_item[j].nsin_port = htons(
+        kOpenerEipIoUdpPort);
+    common_packet_format_data->address_info_item[j].nsin_addr =
+        g_multicast_configuration.starting_multicast_address;
+    memset(common_packet_format_data->address_info_item[j].nasin_zero, 0, 8);
+    common_packet_format_data->address_info_item[j].length = 16;
+  }
+
+  if (htons(AF_INET)
+      != common_packet_format_data->address_info_item[j].nsin_family) {
+    OPENER_TRACE_ERR(
+        "Sockaddr Info Item with wrong sin family value recieved\n");
+    return kEipStatusError;
+  }
+
+  socket_address.sin_family = ntohs(
+      common_packet_format_data->address_info_item[j].nsin_family);
+  socket_address.sin_addr.s_addr =
+      common_packet_format_data->address_info_item[j].nsin_addr;
+  socket_address.sin_port = common_packet_format_data->address_info_item[j]
+      .nsin_port;
+
+  socket = CreateUdpSocket(direction, &socket_address); /* the address is only needed for bind used if consuming */
+  if (socket == kEipInvalidSocket) {
+    OPENER_TRACE_ERR("cannot create UDP socket in OpenMulticastConnection\n");
+    return kEipStatusError;
+  }
+  connection_object->socket[direction] = socket;
+
+  if (direction == kUdpCommuncationDirectionConsuming) {
+    common_packet_format_data->address_info_item[j].type_id =
+        kSocketAddressInfoOriginatorToTargetId;
+    connection_object->originator_address = socket_address;
+  } else {
+    common_packet_format_data->address_info_item[j].type_id =
+        kSocketAddressInfoTargetToOriginatorId;
+    connection_object->remote_address = socket_address;
+  }
+
+  return kEipStatusOk;
 }
 }
 
 
-EIP_UINT16
-handleConfigData(S_CIP_Class *pa_pstAssemblyClass,
-    S_CIP_ConnectionObject *pa_pstIOConnObj)
-{
-  EIP_UINT16 unRetVal = 0;
-  S_CIP_Instance *pstConfigInstance = getCIPInstance(pa_pstAssemblyClass,
-      pa_pstIOConnObj->ConnectionPath.ConnectionPoint[2]);
-
-  if (0 != g_unConfigDataLen)
-    {
-      if (connectionWithSameConfigPointExists(
-          pa_pstIOConnObj->ConnectionPath.ConnectionPoint[2]))
-        { /* there is a connected connection with the same config point
+EipUint16 HandleConfigData(CipClass *assembly_class,
+                           ConnectionObject *connection_object) {
+  EipUint16 connection_manager_status = 0;
+  CipInstance *config_instance = GetCipInstance(
+      assembly_class, connection_object->connection_path.connection_point[2]);
+
+  if (0 != g_config_data_length) {
+    if (ConnectionWithSameConfigPointExists(
+        connection_object->connection_path.connection_point[2])) { /* there is a connected connection with the same config point
          * we have to have the same data as already present in the config point*/
          * we have to have the same data as already present in the config point*/
-          S_CIP_Byte_Array *p = (S_CIP_Byte_Array *) getAttribute(
-              pstConfigInstance, 3)->pt2data;
-          if (p->len != g_unConfigDataLen)
-            {
-              unRetVal = CIP_CON_MGR_ERROR_OWNERSHIP_CONFLICT;
-            }
-          else
-            {
-              /*FIXME check if this is correct */
-              if (memcmp(p->Data, g_pnConfigDataBuffer, g_unConfigDataLen))
-                {
-                  unRetVal = CIP_CON_MGR_ERROR_OWNERSHIP_CONFLICT;
-                }
-            }
+      CipByteArray *p = (CipByteArray *) GetCipAttribute(config_instance, 3)
+          ->data;
+      if (p->length != g_config_data_length) {
+        connection_manager_status =
+            kConnectionManagerStatusCodeErrorOwnershipConflict;
+      } else {
+        /*FIXME check if this is correct */
+        if (memcmp(p->data, g_config_data_buffer, g_config_data_length)) {
+          connection_manager_status =
+              kConnectionManagerStatusCodeErrorOwnershipConflict;
         }
         }
-      else
-        {
-          /*put the data on the configuration assembly object with the current
-           design this can be done rather efficiently */
-          if (EIP_OK
-              != notifyAssemblyConnectedDataReceived(pstConfigInstance,
-                  g_pnConfigDataBuffer, g_unConfigDataLen))
-            {
-              OPENER_TRACE_WARN("Configuration data was invalid\n");
-              unRetVal = CIP_CON_MGR_INVALID_CONFIGURATION_APP_PATH;
-            }
-        }
-    }
-  return unRetVal;
+      }
+    } else {
+      /* put the data on the configuration assembly object with the current
+       design this can be done rather efficiently */
+      if (kEipStatusOk
+          != NotifyAssemblyConnectedDataReceived(config_instance,
+                                                 g_config_data_buffer,
+                                                 g_config_data_length)) {
+        OPENER_TRACE_WARN("Configuration data was invalid\n");
+        connection_manager_status =
+            kConnectionManagerStatusCodeInvalidConfigurationApplicationPath;
+      }
+    }
+  }
+  return connection_manager_status;
 }
 }
 
 
-void
-closeIOConnection(S_CIP_ConnectionObject *pa_pstConnObjData)
-{
-  S_CIP_ConnectionObject *pstNextNonCtrlMasterCon;
-
-  IApp_IOConnectionEvent(pa_pstConnObjData->ConnectionPath.ConnectionPoint[0],
-      pa_pstConnObjData->ConnectionPath.ConnectionPoint[1], enClosed);
-
-  if ((enConnTypeIOExclusiveOwner == pa_pstConnObjData->m_eInstanceType)
-      || (enConnTypeIOInputOnly == pa_pstConnObjData->m_eInstanceType))
-    {
-      if ((CIP_MULTICAST_CONNECTION
-          == (pa_pstConnObjData->T_to_O_NetworkConnectionParameter
-              & CIP_MULTICAST_CONNECTION))
-          && (EIP_INVALID_SOCKET != pa_pstConnObjData->sockfd[PRODUCING]))
-        {
-          pstNextNonCtrlMasterCon = getNextNonCtrlMasterCon(
-              pa_pstConnObjData->ConnectionPath.ConnectionPoint[1]);
-          if (NULL != pstNextNonCtrlMasterCon)
-            {
-              pstNextNonCtrlMasterCon->sockfd[PRODUCING] =
-                  pa_pstConnObjData->sockfd[PRODUCING];
-              memcpy(&(pstNextNonCtrlMasterCon->remote_addr),
-                  &(pa_pstConnObjData->remote_addr),
-                  sizeof(pstNextNonCtrlMasterCon->remote_addr));
-              pstNextNonCtrlMasterCon->EIPSequenceCountProducing =
-                  pa_pstConnObjData->EIPSequenceCountProducing;
-              pstNextNonCtrlMasterCon->SequenceCountProducing =
-                  pa_pstConnObjData->SequenceCountProducing;
-              pa_pstConnObjData->sockfd[PRODUCING] = EIP_INVALID_SOCKET;
-              pstNextNonCtrlMasterCon->TransmissionTriggerTimer =
-                  pa_pstConnObjData->TransmissionTriggerTimer;
-            }
-          else
-            { /* this was the last master connection close all listen only connections listening on the port */
-              closeAllConnsForInputWithSameType(
-                  pa_pstConnObjData->ConnectionPath.ConnectionPoint[1],
-                  enConnTypeIOListenOnly);
-            }
-        }
-    }
-
-  closeCommChannelsAndRemoveFromActiveConnsList(pa_pstConnObjData);
+void CloseIoConnection(ConnectionObject *connection_object) {
+  ConnectionObject *next_non_control_master_connection;
+
+  IoConnectionEvent(connection_object->connection_path.connection_point[0],
+                    connection_object->connection_path.connection_point[1],
+                    kClosedEvent);
+
+  if ((kConnectionTypeIoExclusiveOwner == connection_object->instance_type)
+      || (kConnectionTypeIoInputOnly == connection_object->instance_type)) {
+    if ((kRoutingTypeMulticastConnection
+        == (connection_object->t_to_o_network_connection_parameter
+            & kRoutingTypeMulticastConnection))
+        && (kEipInvalidSocket
+            != connection_object->socket[kUdpCommuncationDirectionProducing])) {
+      next_non_control_master_connection = GetNextNonControlMasterConnection(
+          connection_object->connection_path.connection_point[1]);
+      if (NULL != next_non_control_master_connection) {
+        next_non_control_master_connection->socket[kUdpCommuncationDirectionProducing] =
+            connection_object->socket[kUdpCommuncationDirectionProducing];
+        memcpy(&(next_non_control_master_connection->remote_address),
+               &(connection_object->remote_address),
+               sizeof(next_non_control_master_connection->remote_address));
+        next_non_control_master_connection->eip_level_sequence_count_producing =
+            connection_object->eip_level_sequence_count_producing;
+        next_non_control_master_connection->sequence_count_producing =
+            connection_object->sequence_count_producing;
+        connection_object->socket[kUdpCommuncationDirectionProducing] =
+            kEipInvalidSocket;
+        next_non_control_master_connection->transmission_trigger_timer =
+            connection_object->transmission_trigger_timer;
+      } else { /* this was the last master connection close all listen only connections listening on the port */
+        CloseAllConnectionsForInputWithSameType(
+            connection_object->connection_path.connection_point[1],
+            kConnectionTypeIoListenOnly);
+      }
+    }
+  }
+
+  CloseCommunicationChannelsAndRemoveFromActiveConnectionsList(
+      connection_object);
 }
 }
 
 
-void
-handleIOConnectionTimeOut(S_CIP_ConnectionObject *pa_pstConn)
-{
-  S_CIP_ConnectionObject *pstNextNonCtrlMasterCon;
-  IApp_IOConnectionEvent(pa_pstConn->ConnectionPath.ConnectionPoint[0],
-      pa_pstConn->ConnectionPath.ConnectionPoint[1], enTimedOut);
-
-  if (CIP_MULTICAST_CONNECTION
-      == (pa_pstConn->T_to_O_NetworkConnectionParameter
-          & CIP_MULTICAST_CONNECTION))
-    {
-      switch (pa_pstConn->m_eInstanceType)
-        {
-      case enConnTypeIOExclusiveOwner:
-        closeAllConnsForInputWithSameType(
-            pa_pstConn->ConnectionPath.ConnectionPoint[1],
-            enConnTypeIOInputOnly);
-        closeAllConnsForInputWithSameType(
-            pa_pstConn->ConnectionPath.ConnectionPoint[1],
-            enConnTypeIOListenOnly);
+void HandleIoConnectionTimeOut(ConnectionObject *connection_object) {
+  ConnectionObject *next_non_control_master_connection;
+  IoConnectionEvent(connection_object->connection_path.connection_point[0],
+                    connection_object->connection_path.connection_point[1],
+                    kTimedOutEvent);
+
+  if (kRoutingTypeMulticastConnection
+      == (connection_object->t_to_o_network_connection_parameter
+          & kRoutingTypeMulticastConnection)) {
+    switch (connection_object->instance_type) {
+      case kConnectionTypeIoExclusiveOwner:
+        CloseAllConnectionsForInputWithSameType(
+            connection_object->connection_path.connection_point[1],
+            kConnectionTypeIoInputOnly);
+        CloseAllConnectionsForInputWithSameType(
+            connection_object->connection_path.connection_point[1],
+            kConnectionTypeIoListenOnly);
         break;
         break;
-      case enConnTypeIOInputOnly:
-        if (EIP_INVALID_SOCKET != pa_pstConn->sockfd[PRODUCING])
-          { /* we are the controlling input only connection find a new controller*/
-            pstNextNonCtrlMasterCon = getNextNonCtrlMasterCon(
-                pa_pstConn->ConnectionPath.ConnectionPoint[1]);
-            if (NULL != pstNextNonCtrlMasterCon)
-              {
-                pstNextNonCtrlMasterCon->sockfd[PRODUCING] =
-                    pa_pstConn->sockfd[PRODUCING];
-                pa_pstConn->sockfd[PRODUCING] = EIP_INVALID_SOCKET;
-                pstNextNonCtrlMasterCon->TransmissionTriggerTimer =
-                    pa_pstConn->TransmissionTriggerTimer;
-              }
-            else
-              { /* this was the last master connection close all listen only connections listening on the port */
-                closeAllConnsForInputWithSameType(
-                    pa_pstConn->ConnectionPath.ConnectionPoint[1],
-                    enConnTypeIOListenOnly);
-              }
+      case kConnectionTypeIoInputOnly:
+        if (kEipInvalidSocket
+            != connection_object->socket[kUdpCommuncationDirectionProducing]) { /* we are the controlling input only connection find a new controller*/
+          next_non_control_master_connection =
+              GetNextNonControlMasterConnection(
+                  connection_object->connection_path.connection_point[1]);
+          if (NULL != next_non_control_master_connection) {
+            next_non_control_master_connection->socket[kUdpCommuncationDirectionProducing] =
+                connection_object->socket[kUdpCommuncationDirectionProducing];
+            connection_object->socket[kUdpCommuncationDirectionProducing] =
+                kEipInvalidSocket;
+            next_non_control_master_connection->transmission_trigger_timer =
+                connection_object->transmission_trigger_timer;
+          } else { /* this was the last master connection close all listen only connections listening on the port */
+            CloseAllConnectionsForInputWithSameType(
+                connection_object->connection_path.connection_point[1],
+                kConnectionTypeIoListenOnly);
           }
           }
+        }
         break;
         break;
       default:
       default:
         break;
         break;
-        }
     }
     }
+  }
 
 
-  OPENER_ASSERT(NULL != pa_pstConn->m_pfCloseFunc);
-  pa_pstConn->m_pfCloseFunc(pa_pstConn);
+  OPENER_ASSERT(NULL != connection_object->connection_close_function);
+  connection_object->connection_close_function(connection_object);
 }
 }
 
 
-EIP_STATUS
-sendConnectedData(S_CIP_ConnectionObject *pa_pstConnection)
-{
-  S_CIP_CPF_Data *pCPFDataItem;
-  S_CIP_Byte_Array *p;
-  EIP_UINT16 replylength;
-  EIP_UINT8 *pnBuf;
+EipStatus SendConnectedData(ConnectionObject *connection_object) {
+  CipCommonPacketFormatData *common_packet_format_data;
+  EipUint16 reply_length;
+  EipUint8 *message_data_reply_buffer;
 
 
   /* TODO think of adding an own send buffer to each connection object in order to preset up the whole message on connection opening and just change the variable data items e.g., sequence number */
   /* TODO think of adding an own send buffer to each connection object in order to preset up the whole message on connection opening and just change the variable data items e.g., sequence number */
 
 
-  pCPFDataItem = &g_stCPFDataItem; /* TODO think on adding a CPF data item to the S_CIP_ConnectionObject in order to remove the code here or even better allocate memory in the connection object for storing the message to send and just change the application data*/
+  common_packet_format_data = &g_common_packet_format_data_item; /* TODO think on adding a CPF data item to the S_CIP_ConnectionObject in order to remove the code here or even better allocate memory in the connection object for storing the message to send and just change the application data*/
 
 
-  pa_pstConnection->EIPSequenceCountProducing++;
+  connection_object->eip_level_sequence_count_producing++;
 
 
   /* assembleCPFData */
   /* assembleCPFData */
-  pCPFDataItem->ItemCount = 2;
-  if ((pa_pstConnection->TransportTypeClassTrigger & 0x0F) != 0)
-    { /* use Sequenced Address Items if not Connection Class 0 */
-      pCPFDataItem->stAddr_Item.TypeID = CIP_ITEM_ID_SEQUENCEDADDRESS;
-      pCPFDataItem->stAddr_Item.Length = 8;
-      pCPFDataItem->stAddr_Item.Data.SequenceNumber =
-          pa_pstConnection->EIPSequenceCountProducing;
-    }
-  else
-    {
-      pCPFDataItem->stAddr_Item.TypeID = CIP_ITEM_ID_CONNECTIONBASED;
-      pCPFDataItem->stAddr_Item.Length = 4;
-
-    }
-  pCPFDataItem->stAddr_Item.Data.ConnectionIdentifier =
-      pa_pstConnection->CIPProducedConnectionID;
-
-  pCPFDataItem->stDataI_Item.TypeID = CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET;
-
-  p =
-      (S_CIP_Byte_Array *) pa_pstConnection->p_stProducingInstance->pstAttributes->pt2data;
-  pCPFDataItem->stDataI_Item.Length = 0;
+  common_packet_format_data->item_count = 2;
+  if ((connection_object->transport_type_class_trigger & 0x0F) != 0) { /* use Sequenced Address Items if not Connection Class 0 */
+    common_packet_format_data->address_item.type_id = kSequencedAddressItemId;
+    common_packet_format_data->address_item.length = 8;
+    common_packet_format_data->address_item.data.sequence_number =
+        connection_object->eip_level_sequence_count_producing;
+  } else {
+    common_packet_format_data->address_item.type_id = kConnectionBasedId;
+    common_packet_format_data->address_item.length = 4;
+
+  }
+  common_packet_format_data->address_item.data.connection_identifier =
+      connection_object->produced_connection_id;
+
+  common_packet_format_data->data_item.type_id = kConnectedTransportPacketId;
+
+  CipByteArray *producing_instance_attributes =
+      (CipByteArray *) connection_object->producing_instance->attributes->data;
+  common_packet_format_data->data_item.length = 0;
 
 
   /* notify the application that data will be sent immediately after the call */
   /* notify the application that data will be sent immediately after the call */
-  if (IApp_BeforeAssemblyDataSend(pa_pstConnection->p_stProducingInstance))
-    {
-      /* the data has changed increase sequence counter */
-      pa_pstConnection->SequenceCountProducing++;
-    }
+  if (BeforeAssemblyDataSend(connection_object->producing_instance)) {
+    /* the data has changed increase sequence counter */
+    connection_object->sequence_count_producing++;
+  }
 
 
   /* set AddressInfo Items to invalid Type */
   /* set AddressInfo Items to invalid Type */
-  pCPFDataItem->AddrInfo[0].TypeID = 0;
-  pCPFDataItem->AddrInfo[1].TypeID = 0;
-
-  replylength = assembleLinearMsg(0, pCPFDataItem,
-      &g_acMessageDataReplyBuffer[0]);
-
-  pnBuf = &g_acMessageDataReplyBuffer[replylength - 2];
-  pCPFDataItem->stDataI_Item.Length = p->len;
-  if (OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER)
-    {
-      pCPFDataItem->stDataI_Item.Length += 4;
-    }
-
-  if ((pa_pstConnection->TransportTypeClassTrigger & 0x0F) == 1)
-    {
-      pCPFDataItem->stDataI_Item.Length += 2;
-      htols(pCPFDataItem->stDataI_Item.Length, &pnBuf);
-      htols(pa_pstConnection->SequenceCountProducing, &pnBuf);
-    }
-  else
-    {
-      htols(pCPFDataItem->stDataI_Item.Length, &pnBuf);
-    }
-
-  if (OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER)
-    {
-      htoll(g_nRunIdleState, &(pnBuf));
-    }
-
-  memcpy(pnBuf, p->Data, p->len);
-
-  replylength += pCPFDataItem->stDataI_Item.Length;
-
-  return IApp_SendUDPData(&pa_pstConnection->remote_addr,
-      pa_pstConnection->sockfd[PRODUCING], &g_acMessageDataReplyBuffer[0],
-      replylength);
+  common_packet_format_data->address_info_item[0].type_id = 0;
+  common_packet_format_data->address_info_item[1].type_id = 0;
+
+  reply_length = AssembleLinearMessage(0, common_packet_format_data,
+                                       &g_message_data_reply_buffer[0]);
+
+  message_data_reply_buffer = &g_message_data_reply_buffer[reply_length - 2];
+  common_packet_format_data->data_item.length = producing_instance_attributes
+      ->length;
+  if (kOpenerProducedDataHasRunIdleHeader) {
+    common_packet_format_data->data_item.length += 4;
+  }
+
+  if ((connection_object->transport_type_class_trigger & 0x0F) == 1) {
+    common_packet_format_data->data_item.length += 2;
+    AddIntToMessage(common_packet_format_data->data_item.length,
+                    &message_data_reply_buffer);
+    AddIntToMessage(connection_object->sequence_count_producing,
+                    &message_data_reply_buffer);
+  } else {
+    AddIntToMessage(common_packet_format_data->data_item.length,
+                    &message_data_reply_buffer);
+  }
+
+  if (kOpenerProducedDataHasRunIdleHeader) {
+    AddDintToMessage(g_run_idle_state, &(message_data_reply_buffer));
+  }
+
+  memcpy(message_data_reply_buffer, producing_instance_attributes->data,
+         producing_instance_attributes->length);
+
+  reply_length += common_packet_format_data->data_item.length;
+
+  return SendUdpData(
+      &connection_object->remote_address,
+      connection_object->socket[kUdpCommuncationDirectionProducing],
+      &g_message_data_reply_buffer[0], reply_length);
 }
 }
 
 
-EIP_STATUS
-handleReceivedIOConnData(struct CIP_ConnectionObject *pa_pstConnection,
-    EIP_UINT8 * pa_pnData, EIP_UINT16 pa_nDataLength)
-{
+EipStatus HandleReceivedIoConnectionData(ConnectionObject *connection_object,
+                                         EipUint8 *data, EipUint16 data_length) {
 
 
   /* check class 1 sequence number*/
   /* check class 1 sequence number*/
-  if ((pa_pstConnection->TransportTypeClassTrigger & 0x0F) == 1)
-    {
-      EIP_UINT16 nSequenceBuf = ltohs(&(pa_pnData));
-      if (SEQ_LEQ16(nSequenceBuf, pa_pstConnection->SequenceCountConsuming))
-        {
-          return EIP_OK; /* no new data for the assembly */
-        }
-      pa_pstConnection->SequenceCountConsuming = nSequenceBuf;
-      pa_nDataLength -= 2;
-    }
-
-  if (pa_nDataLength > 0)
-    {
-      /* we have no heartbeat connection */
-      if (OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER)
-        {
-          EIP_UINT32 nRunIdleBuf = ltohl(&(pa_pnData));
-          if (g_nRunIdleState != nRunIdleBuf)
-            {
-              IApp_RunIdleChanged(nRunIdleBuf);
-            }
-          g_nRunIdleState = nRunIdleBuf;
-          pa_nDataLength -= 4;
-        }
-
-      if (notifyAssemblyConnectedDataReceived(
-          pa_pstConnection->p_stConsumingInstance, pa_pnData, pa_nDataLength)
-          != 0)
-        {
-          return EIP_ERROR;
-        }
-    }
-  return EIP_OK;
+  if ((connection_object->transport_type_class_trigger & 0x0F) == 1) {
+    EipUint16 sequence_buffer = GetIntFromMessage(&(data));
+    if (SEQ_LEQ16(sequence_buffer,
+                  connection_object->sequence_count_consuming)) {
+      return kEipStatusOk; /* no new data for the assembly */
+    }
+    connection_object->sequence_count_consuming = sequence_buffer;
+    data_length -= 2;
+  }
+
+  if (data_length > 0) {
+    /* we have no heartbeat connection */
+    if (kOpenerConsumedDataHasRunIdleHeader) {
+      EipUint32 nRunIdleBuf = GetDintFromMessage(&(data));
+      if (g_run_idle_state != nRunIdleBuf) {
+        RunIdleChanged(nRunIdleBuf);
+      }
+      g_run_idle_state = nRunIdleBuf;
+      data_length -= 4;
+    }
+
+    if (NotifyAssemblyConnectedDataReceived(
+        connection_object->consuming_instance, data, data_length) != 0) {
+      return kEipStatusError;
+    }
+  }
+  return kEipStatusOk;
 }
 }
 
 
-int
-openCommunicationChannels(struct CIP_ConnectionObject *pa_pstIOConnObj)
-{
-  int O2TConnectionType, T2OConnectionType;
-  int nRetVal = EIP_OK;
-  /*get pointer to the cpf data, currently we have just one global instance of the struct. This may change in the future*/
-  S_CIP_CPF_Data *pstCPF_data = &g_stCPFDataItem;
+EipStatus OpenCommunicationChannels(ConnectionObject *connection_object) {
+  int originator_to_target_connection_type,
+      target_to_originator_connection_type;
+  int eip_status = kEipStatusOk;
+  /*get pointer to the CPF data, currently we have just one global instance of the struct. This may change in the future*/
+  CipCommonPacketFormatData *common_packet_format_data =
+      &g_common_packet_format_data_item;
 
 
-  O2TConnectionType = (pa_pstIOConnObj->O_to_T_NetworkConnectionParameter
-      & 0x6000) >> 13;
-  T2OConnectionType = (pa_pstIOConnObj->T_to_O_NetworkConnectionParameter
-      & 0x6000) >> 13;
+  originator_to_target_connection_type = (connection_object
+      ->o_to_t_network_connection_parameter & 0x6000) >> 13;
+  target_to_originator_connection_type = (connection_object
+      ->t_to_o_network_connection_parameter & 0x6000) >> 13;
 
 
   /* open a connection "point to point" or "multicast" based on the ConnectionParameter */
   /* open a connection "point to point" or "multicast" based on the ConnectionParameter */
-  if (O2TConnectionType == 1) /* Multicast consuming */
-    {
-      if (OpenMulticastConnection(CONSUMING, pa_pstIOConnObj, pstCPF_data)
-          == EIP_ERROR)
-        {
-          OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
-          return CIP_ERROR_CONNECTION_FAILURE;
-        }
-    }
-  else if (O2TConnectionType == 2) /* Point to Point consuming */
-    {
-      if (OpenConsumingPointToPointConnection(pa_pstIOConnObj, pstCPF_data)
-          == EIP_ERROR)
-        {
-          OPENER_TRACE_ERR("error in PointToPoint consuming connection\n");
-          return CIP_ERROR_CONNECTION_FAILURE;
-        }
-    }
-
-  if (T2OConnectionType == 1) /* Multicast producing */
-    {
-      if (openProducingMulticastConnection(pa_pstIOConnObj, pstCPF_data)
-          == EIP_ERROR)
-        {
-          OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
-          return CIP_ERROR_CONNECTION_FAILURE;
-        }
-    }
-  else if (T2OConnectionType == 2) /* Point to Point producing */
-    {
-
-      if (OpenProducingPointToPointConnection(pa_pstIOConnObj, pstCPF_data)
-          != EIP_OK)
-        {
-          OPENER_TRACE_ERR("error in PointToPoint producing connection\n");
-          return CIP_ERROR_CONNECTION_FAILURE;
-        }
-    }
-
-  return nRetVal;
+  if (originator_to_target_connection_type == 1) /*TODO: Fix magic number; Multicast consuming */
+  {
+    if (OpenMulticastConnection(kUdpCommuncationDirectionConsuming,
+                                connection_object, common_packet_format_data)
+        == kEipStatusError) {
+      OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
+      return kCipErrorConnectionFailure;
+    }
+  } else if (originator_to_target_connection_type == 2) /* TODO: Fix magic number; Point to Point consuming */
+  {
+    if (OpenConsumingPointToPointConnection(connection_object,
+                                            common_packet_format_data)
+        == kEipStatusError) {
+      OPENER_TRACE_ERR("error in PointToPoint consuming connection\n");
+      return kCipErrorConnectionFailure;
+    }
+  }
+
+  if (target_to_originator_connection_type == 1) /* TODO: Fix magic number; Multicast producing */
+  {
+    if (OpenProducingMulticastConnection(connection_object,
+                                         common_packet_format_data)
+        == kEipStatusError) {
+      OPENER_TRACE_ERR("error in OpenMulticast Connection\n");
+      return kCipErrorConnectionFailure;
+    }
+  } else if (target_to_originator_connection_type == 2) /* TODO: Fix magic number; Point to Point producing */
+  {
+
+    if (OpenProducingPointToPointConnection(connection_object,
+                                            common_packet_format_data)
+        != kEipStatusOk) {
+      OPENER_TRACE_ERR("error in PointToPoint producing connection\n");
+      return kCipErrorConnectionFailure;
+    }
+  }
+
+  return eip_status;
 }
 }
 
 
-void
-closeCommChannelsAndRemoveFromActiveConnsList(
-    struct CIP_ConnectionObject *pa_pstConnObjData)
-{
-  IApp_CloseSocket_udp(pa_pstConnObjData->sockfd[CONSUMING]);
-  pa_pstConnObjData->sockfd[CONSUMING] = EIP_INVALID_SOCKET;
-  IApp_CloseSocket_udp(pa_pstConnObjData->sockfd[PRODUCING]);
-  pa_pstConnObjData->sockfd[PRODUCING] = EIP_INVALID_SOCKET;
-
-  removeFromActiveConnections(pa_pstConnObjData);
+void CloseCommunicationChannelsAndRemoveFromActiveConnectionsList(
+    ConnectionObject *connection_object) {
+  IApp_CloseSocket_udp(
+      connection_object->socket[kUdpCommuncationDirectionConsuming]);
+  connection_object->socket[kUdpCommuncationDirectionConsuming] =
+      kEipInvalidSocket;
+  IApp_CloseSocket_udp(
+      connection_object->socket[kUdpCommuncationDirectionProducing]);
+  connection_object->socket[kUdpCommuncationDirectionProducing] =
+      kEipInvalidSocket;
+
+  RemoveFromActiveConnections(connection_object);
 }
 }

+ 17 - 20
source/src/cip/cipioconnection.h

@@ -37,46 +37,43 @@
  *
  *
  */
  */
 
 
-#ifndef CIPIOCONNECTION_H_
-#define CIPIOCONNECTION_H_
+#ifndef OPENER_CIPIOCONNECTION_H_
+#define OPENER_CIPIOCONNECTION_H_
 
 
-#include <opener_api.h>
+#include "opener_api.h"
+#include "cipconnectionmanager.h"
 
 
 /** @brief Setup all data in order to establish an IO connection
 /** @brief Setup all data in order to establish an IO connection
  *
  *
  * This function can be called after all data has been parsed from the forward open request
  * This function can be called after all data has been parsed from the forward open request
- * @param pa_pstConnObjData pointer to the connection object structure holding the parsed data from the forward open request
- * @param pa_pnExtendedError the extended error code in case an error happened
+ * @param connection_object pointer to the connection object structure holding the parsed data from the forward open request
+ * @param extended_error the extended error code in case an error happened
  * @return general status on the establishment
  * @return general status on the establishment
  *    - EIP_OK ... on success
  *    - EIP_OK ... on success
  *    - On an error the general status code to be put into the response
  *    - On an error the general status code to be put into the response
  */
  */
-int
-establishIOConnction(struct CIP_ConnectionObject *pa_pstConnObjData,
-    EIP_UINT16 *pa_pnExtendedError);
+int EstablishIoConnction(ConnectionObject *connection_object,
+                         EipUint16 *extended_error);
 
 
 /** @brief Take the data given in the connection object structure and open the necessary communication channels
 /** @brief Take the data given in the connection object structure and open the necessary communication channels
  *
  *
  * This function will use the g_stCPFDataItem!
  * This function will use the g_stCPFDataItem!
- * @param pa_pstIOConnObj pointer to the connection object data
+ * @param connection_object pointer to the connection object data
  * @return general status on the open process
  * @return general status on the open process
  *    - EIP_OK ... on success
  *    - EIP_OK ... on success
  *    - On an error the general status code to be put into the response
  *    - On an error the general status code to be put into the response
  */
  */
-int
-openCommunicationChannels(struct CIP_ConnectionObject *pa_pstIOConnObj);
+int OpenCommunicationChannels(ConnectionObject *connection_object);
 
 
-
-/*! \brief close the communication channels of the given connection and remove it
+/** @brief close the communication channels of the given connection and remove it
  * from the active connections list.
  * from the active connections list.
  *
  *
- * @param pa_pstConnObjData pointer to the connection object data
+ * @param connection_object pointer to the connection object data
  */
  */
-void
-closeCommChannelsAndRemoveFromActiveConnsList(
-    struct CIP_ConnectionObject *pa_pstConnObjData);
+void CloseCommunicationChannelsAndRemoveFromActiveConnectionsList(
+    ConnectionObject *connection_object);
 
 
-extern EIP_UINT8 *g_pnConfigDataBuffer;
-extern unsigned int g_unConfigDataLen;
+extern EipUint8 *g_config_data_buffer;
+extern unsigned int g_config_data_length;
 
 
-#endif /* CIPIOCONNECTION_H_ */
+#endif /* OPENER_CIPIOCONNECTION_H_ */

+ 187 - 206
source/src/cip/cipmessagerouter.c

@@ -10,269 +10,250 @@
 #include "ciperror.h"
 #include "ciperror.h"
 #include "trace.h"
 #include "trace.h"
 
 
-S_CIP_MR_Request gMRRequest;
-S_CIP_MR_Response gMRResponse;
+CipMessageRouterRequest g_message_router_request;
+CipMessageRouterResponse g_message_router_response;
 
 
-/*! A class registry list node
- * a linked list of this  object is the registry of classes known to the message router
+/** @brief A class registry list node
+ *
+ * A linked list of this  object is the registry of classes known to the message router
  * for small devices with very limited memory it could make sense to change this list into an
  * for small devices with very limited memory it could make sense to change this list into an
  * array with a given max size for removing the need for having to dynamically allocate 
  * array with a given max size for removing the need for having to dynamically allocate 
  * memory. The size of the array could be a parameter in the platform config file.
  * memory. The size of the array could be a parameter 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;
+typedef struct cip_message_router_object {
+  struct cip_message_router_object *next; /*< link */
+  CipClass *cip_class; /*< object */
+} CipMessageRouterObject;
 
 
-/* pointer to first registered object in MessageRouter*/
-S_CIP_MR_Object *g_pt2firstObject = 0;
+/** @brief Pointer to first registered object in MessageRouter*/
+CipMessageRouterObject *g_first_object = 0;
 
 
-/*! Register an Class to the message router
- *  @param pa_pt2Class     pointer to a class object to be registered.
+/** @brief Register an Class to the message router
+ *  @param cip_class Pointer to a class object to be registered.
  *  @return status      0 .. success
  *  @return status      0 .. success
  *                     -1 .. error no memory available to register more objects
  *                     -1 .. error no memory available to register more objects
  */
  */
-EIP_STATUS
-registerClass(S_CIP_Class * pa_pt2Class);
+EipStatus RegisterClass(CipClass *cip_class);
 
 
-/*!  Create MRRequest structure out of the received data.
+/** @brief Create Message Router Request structure out of the received data.
  * 
  * 
  * Parses the UCMM header consisting of: service, IOI size, IOI, data into a request structure
  * Parses the UCMM header consisting of: service, IOI size, IOI, data into a request structure
- * @param pa_pnData    pointer to the message data received
- * @param pa_nLength   number of bytes in the message
- * @param pa_pstMRReqdata   pointer to structure of MRRequest data item.
+ * @param data pointer to the message data received
+ * @param data_length number of bytes in the message
+ * @param message_router_request pointer to structure of MRRequest data item.
  * @return status  0 .. success
  * @return status  0 .. success
  *                 -1 .. error
  *                 -1 .. error
- */EIP_BYTE
-createMRRequeststructure(EIP_UINT8 * pa_pnData, EIP_INT16 pa_nLength,
-    S_CIP_MR_Request * pa_pstMRReqdata);
-
-EIP_STATUS
-CIP_MessageRouter_Init()
-{
-  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;
+ */
+CipError CreateMessageRouterRequestStructure(
+    EipUint8 *data, EipInt16 data_length,
+    CipMessageRouterRequest *message_router_request);
+
+EipStatus CipMessageRouterInit() {
+  CipClass *message_router;
+
+  message_router = CreateCipClass(kCipMessageRouterClassCode, /* 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 (message_router == 0)
+    return kEipStatusError;
 
 
   /* reserved for future use -> set to zero */
   /* reserved for future use -> set to zero */
-  gMRResponse.Reserved = 0;
-  gMRResponse.Data = g_acMessageDataReplyBuffer; /* set reply buffer, using a fixed buffer (about 100 bytes) */
+  g_message_router_response.reserved = 0;
+  g_message_router_response.data = g_message_data_reply_buffer; /* set reply buffer, using a fixed buffer (about 100 bytes) */
 
 
-  return EIP_OK;
+  return kEipStatusOk;
 }
 }
 
 
-/*! get the registered MessageRouter object corresponding to ClassID.
+/** @brief Get the registered MessageRouter object corresponding to ClassID.
  *  given a class ID, return a pointer to the registration node for that object
  *  given a class ID, return a pointer to the registration node for that object
- *  @param pa_nClassID      ClassCode to be searched for.
- *  @return pointer to registered MR object
+ *
+ *  @param class_id Class code to be searched for.
+ *  @return Pointer to registered message router object
  *      0 .. Class not registered
  *      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*/
-    {
-      OPENER_ASSERT(p->pt2Class != NULL);
-      if (p->pt2Class->nClassID == pa_nClassID)
-        return p; /* return registration node if it matches class ID*/
-      p = p->next;
-    }
+CipMessageRouterObject *GetRegisteredObject(EipUint32 class_id) {
+  CipMessageRouterObject *object = g_first_object; /* get pointer to head of class registration list */
+
+  while (NULL != object) /* for each entry in list*/
+  {
+    OPENER_ASSERT(object->cip_class != NULL);
+    if (object->cip_class->class_id == class_id)
+      return object; /* return registration node if it matches class ID*/
+    object = object->next;
+  }
   return 0;
   return 0;
 }
 }
 
 
-S_CIP_Class *
-getCIPClass(EIP_UINT32 pa_nClassID)
-{
-  S_CIP_MR_Object *p = getRegisteredObject(pa_nClassID);
+CipClass *GetCipClass(EipUint32 class_id) {
+  CipMessageRouterObject *p = GetRegisteredObject(class_id);
 
 
   if (p)
   if (p)
-    return p->pt2Class;
+    return p->cip_class;
   else
   else
-    return 0;
+    return NULL;
 }
 }
 
 
-S_CIP_Instance *
-getCIPInstance(S_CIP_Class * pa_pstClass, EIP_UINT32 pa_nInstanceNr)
-{
-  S_CIP_Instance *p; /* pointer to linked list of instances from the class object*/
+CipInstance *GetCipInstance(CipClass *cip_class, EipUint32 instance_number) {
+  CipInstance *instance; /* 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*/
+  if (instance_number == 0)
+    return (CipInstance *) cip_class; /* 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*/
-    }
+  for (instance = cip_class->instances; instance; instance = instance->next) /* follow the list*/
+  {
+    if (instance->instance_number == instance_number)
+      return instance; /* if the number matches, return the instance*/
+  }
 
 
-  return 0;
+  return NULL;
 }
 }
 
 
-EIP_STATUS
-registerClass(S_CIP_Class * pa_pt2Class)
-{
-  S_CIP_MR_Object **p = &g_pt2firstObject;
+EipStatus RegisterClass(CipClass *cip_class) {
+  CipMessageRouterObject **message_router_object = &g_first_object;
 
 
-  while (*p)
-    p = &(*p)->next; /* follow the list until p points to an empty link (list end)*/
+  while (*message_router_object)
+    message_router_object = &(*message_router_object)->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*/
+  *message_router_object = (CipMessageRouterObject *) CipCalloc(
+      1, sizeof(CipMessageRouterObject)); /* create a new node at the end of the list*/
+  if (*message_router_object == 0)
+    return kEipStatusError; /* check for memory error*/
 
 
-  (*p)->pt2Class = pa_pt2Class; /* fill in the new node*/
-  (*p)->next = NULL;
+  (*message_router_object)->cip_class = cip_class; /* fill in the new node*/
+  (*message_router_object)->next = NULL;
 
 
-  return EIP_OK;
+  return kEipStatusOk;
 }
 }
 
 
-EIP_STATUS
-notifyMR(EIP_UINT8 * pa_pnData, int pa_nDataLength)
-{
-  EIP_STATUS nRetVal = EIP_OK_SEND;
-  EIP_BYTE nStatus;
+EipStatus NotifyMR(EipUint8 *data, int data_length) {
+  EipStatus eip_status = kEipStatusOkSend;
+  EipByte nStatus;
 
 
-  gMRResponse.Data = g_acMessageDataReplyBuffer; /* set reply buffer, using a fixed buffer (about 100 bytes) */
+  g_message_router_response.data = g_message_data_reply_buffer; /* set reply buffer, using a fixed buffer (about 100 bytes) */
 
 
   OPENER_TRACE_INFO("notifyMR: routing unconnected message\n");
   OPENER_TRACE_INFO("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;
-          OPENER_ASSERT(NULL != pt2regObject->pt2Class);
-          OPENER_TRACE_INFO(
-              "notifyMR: calling notify function of class '%s'\n",
-              pt2regObject->pt2Class->acName);
-          nRetVal = notifyClass(pt2regObject->pt2Class, &gMRRequest,
-              &gMRResponse);
+  if (kCipErrorSuccess
+      != (nStatus = CreateMessageRouterRequestStructure(
+          data, data_length, &g_message_router_request))) { /* error from create MR structure*/
+    OPENER_TRACE_ERR("notifyMR: error from createMRRequeststructure\n");
+    g_message_router_response.general_status = nStatus;
+    g_message_router_response.size_of_additional_status = 0;
+    g_message_router_response.reserved = 0;
+    g_message_router_response.data_length = 0;
+    g_message_router_response.reply_service = (0x80
+        | g_message_router_request.service);
+  } else {
+    /* forward request to appropriate Object if it is registered*/
+    CipMessageRouterObject *pt2regObject;
+
+    pt2regObject = GetRegisteredObject(
+        g_message_router_request.request_path.class_id);
+    if (pt2regObject == 0) {
+      OPENER_TRACE_ERR(
+          "notifyMR: sending CIP_ERROR_OBJECT_DOES_NOT_EXIST reply, class id 0x%x is not registered\n",
+          (unsigned ) g_message_router_request.request_path.class_id);
+      g_message_router_response.general_status =
+          kCipErrorPathDestinationUnknown; /*according to the test tool this should be the correct error flag instead of CIP_ERROR_OBJECT_DOES_NOT_EXIST;*/
+      g_message_router_response.size_of_additional_status = 0;
+      g_message_router_response.reserved = 0;
+      g_message_router_response.data_length = 0;
+      g_message_router_response.reply_service = (0x80
+          | g_message_router_request.service);
+    } else {
+      /* call notify function from Object with ClassID (gMRRequest.RequestPath.ClassID)
+       object will or will not make an reply into gMRResponse*/
+      g_message_router_response.reserved = 0;
+      OPENER_ASSERT(NULL != pt2regObject->cip_class);
+      OPENER_TRACE_INFO("notifyMR: calling notify function of class '%s'\n",
+                        pt2regObject->cip_class->class_name);
+      eip_status = NotifyClass(pt2regObject->cip_class,
+                               &g_message_router_request,
+                               &g_message_router_response);
 
 
 #ifdef OPENER_TRACE_ENABLED
 #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)
-            {
-              OPENER_TRACE_INFO(
-                  "notifyMR: notify function of class '%s' returned no reply\n",
-                  pt2regObject->pt2Class->acName);
-            }
-          else
-            {
-              OPENER_TRACE_INFO(
-                  "notifyMR: notify function of class '%s' returned a reply\n",
-                  pt2regObject->pt2Class->acName);
-            }
+      if (eip_status == kEipStatusError) {
+        OPENER_TRACE_ERR(
+            "notifyMR: notify function of class '%s' returned an error\n",
+            pt2regObject->cip_class->class_name);
+      } else if (eip_status == kEipStatusOk) {
+        OPENER_TRACE_INFO(
+            "notifyMR: notify function of class '%s' returned no reply\n",
+            pt2regObject->cip_class->class_name);
+      } else {
+        OPENER_TRACE_INFO(
+            "notifyMR: notify function of class '%s' returned a reply\n",
+            pt2regObject->cip_class->class_name);
+      }
 #endif
 #endif
-        }
     }
     }
-  return nRetVal;
+  }
+  return eip_status;
 }
 }
 
 
-EIP_BYTE
-createMRRequeststructure(EIP_UINT8 * pa_pnData, EIP_INT16 pa_nLength,
-    S_CIP_MR_Request * pa_pstMRReqdata)
-{
-  int nRetVal;
+CipError CreateMessageRouterRequestStructure(
+    EipUint8 *data, EipInt16 data_length,
+    CipMessageRouterRequest *message_router_request) {
+  int number_of_decoded_bytes;
 
 
-  pa_pstMRReqdata->Service = *pa_pnData;
-  pa_pnData++;
-  pa_nLength--;
+  message_router_request->service = *data;
+  data++;  /*TODO: Fix for 16 bit path lengths (+1 */
+  data_length--;
 
 
+  number_of_decoded_bytes = DecodePaddedEPath(
+      &(message_router_request->request_path), &data);
+  if (number_of_decoded_bytes < 0) {
+    return kCipErrorPathSegmentError;
+  }
 
 
-  nRetVal = decodePaddedEPath(&(pa_pstMRReqdata->RequestPath), &pa_pnData);
-  if(nRetVal < 0)
-    {
-      return CIP_ERROR_PATH_SEGMENT_ERROR;
-    }
+  message_router_request->data = data;
+  message_router_request->data_length = data_length - number_of_decoded_bytes;
 
 
-  pa_pstMRReqdata->Data = pa_pnData;
-  pa_pstMRReqdata->DataLength = pa_nLength - nRetVal;
-
-  if (pa_pstMRReqdata->DataLength < 0)
-    return CIP_ERROR_PATH_SIZE_INVALID;
+  if (message_router_request->data_length < 0)
+    return kCipErrorPathSizeInvalid;
   else
   else
-    return CIP_ERROR_SUCCESS;
+    return kCipErrorSuccess;
 }
 }
 
 
-void
-deleteAllClasses(void)
-{
-  S_CIP_MR_Object *pstRunner = g_pt2firstObject; /* get pointer to head of class registration list */
-  S_CIP_MR_Object *pstToDelete;
-  S_CIP_Instance *pstInstRunner, *pstInstDel;
-
-  while (NULL != pstRunner)
-    {
-      pstToDelete = pstRunner;
-      pstRunner = pstRunner->next;
-
-      pstInstRunner = pstToDelete->pt2Class->pstInstances;
-      while (NULL != pstInstRunner)
-        {
-          pstInstDel = pstInstRunner;
-          pstInstRunner = pstInstRunner->pstNext;
-          if (pstToDelete->pt2Class->nNr_of_Attributes) /* if the class has instance attributes */
-            { /* then free storage for the attribute array */
-              IApp_CipFree(pstInstDel->pstAttributes);
-            }
-          IApp_CipFree(pstInstDel);
-        }
-
-      /*clear meta class data*/
-      IApp_CipFree(pstToDelete->pt2Class->m_stSuper.pstClass->acName);
-      IApp_CipFree(pstToDelete->pt2Class->m_stSuper.pstClass->pstServices);
-      IApp_CipFree(pstToDelete->pt2Class->m_stSuper.pstClass);
-      /*clear class data*/
-      IApp_CipFree(pstToDelete->pt2Class->m_stSuper.pstAttributes);
-      IApp_CipFree(pstToDelete->pt2Class->pstServices);
-      IApp_CipFree(pstToDelete->pt2Class);
-      IApp_CipFree(pstToDelete);
+void DeleteAllClasses(void) {
+  CipMessageRouterObject *message_router_object = g_first_object; /* get pointer to head of class registration list */
+  CipMessageRouterObject *message_router_object_to_delete;
+  CipInstance *instance, *instance_to_delete;
+
+  while (NULL != message_router_object) {
+    message_router_object_to_delete = message_router_object;
+    message_router_object = message_router_object->next;
+
+    instance = message_router_object_to_delete->cip_class->instances;
+    while (NULL != instance) {
+      instance_to_delete = instance;
+      instance = instance->next;
+      if (message_router_object_to_delete->cip_class->number_of_attributes) /* if the class has instance attributes */
+      { /* then free storage for the attribute array */
+        CipFree(instance_to_delete->attributes);
+      }
+      CipFree(instance_to_delete);
     }
     }
-  g_pt2firstObject = NULL;
+
+    /*clear meta class data*/
+    CipFree(
+        message_router_object_to_delete->cip_class->m_stSuper.cip_class
+            ->class_name);
+    CipFree(
+        message_router_object_to_delete->cip_class->m_stSuper.cip_class
+            ->services);
+    CipFree(message_router_object_to_delete->cip_class->m_stSuper.cip_class);
+    /*clear class data*/
+    CipFree(message_router_object_to_delete->cip_class->m_stSuper.attributes);
+    CipFree(message_router_object_to_delete->cip_class->services);
+    CipFree(message_router_object_to_delete->cip_class);
+    CipFree(message_router_object_to_delete);
+  }
+  g_first_object = NULL;
 }
 }

+ 20 - 22
source/src/cip/cipmessagerouter.h

@@ -3,53 +3,51 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPMESSAGEROUTER_H_
-#define CIPMESSAGEROUTER_H_
+#ifndef OPENER_CIPMESSAGEROUTER_H_
+#define OPENER_CIPMESSAGEROUTER_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
 
 
-#define CIP_MESSAGE_ROUTER_CLASS_CODE 0x02
+static const int kCipMessageRouterClassCode = 0x02;
 
 
-/*! Structure for storing the Response generated by an explict message.
+/** @brief Structure for storing the Response generated by an explict message.
  * 
  * 
  *  This buffer will be used for storing the result. The response message will be generated
  *  This buffer will be used for storing the result. The response message will be generated
  *  by assembleLinearMsg. 
  *  by assembleLinearMsg. 
  */
  */
-extern S_CIP_MR_Response gMRResponse;
+extern CipMessageRouterResponse g_message_router_response;
 
 
 /* public functions */
 /* public functions */
 
 
-/*!Initialize the data structures of the message router
+/** @brief Initialize the data structures of the message router
+ *  @return kEipStatusOk if class was initialized, otherwise kEipStatusError
  */
  */
-EIP_STATUS
-CIP_MessageRouter_Init(void);
+EipStatus CipMessageRouterInit(void);
 
 
-/*! Free all data allocated by the classes created in the cip stack
+/** @brief Free all data allocated by the classes created in the CIP stack
  */
  */
-void deleteAllClasses(void);
+void DeleteAllClasses(void);
 
 
-/*! Notify the MessageRouter that an explicit message (connected or unnconnected)
- *  has been recieved. This function will be called from the encapsulation layer.
- *  The CPF strcuture is allready parsed an cann be accessed via the global variable: 
+/** @brief Notify the MessageRouter that an explicit message (connected or unconnected)
+ *  has been received. This function will be called from the encapsulation layer.
+ *  The CPF structure is already parsed an can be accessed via the global variable:
  *  g_stCPFDataItem.
  *  g_stCPFDataItem.
- *  @param pa_pnData pointer to the data buffer of the message directly at the beginning of the CIP part.
- *  @param pa_nDataLength number of bytes in the data buffer
+ *  @param data pointer to the data buffer of the message directly at the beginning of the CIP part.
+ *  @param data_length number of bytes in the data buffer
  *  @return  EIP_ERROR on fault
  *  @return  EIP_ERROR on fault
  *           EIP_OK on success           
  *           EIP_OK on success           
  */
  */
-EIP_STATUS
-notifyMR(EIP_UINT8 *pa_pnData, int pa_nDataLength);
+EipStatus NotifyMR(EipUint8 *data, int data_length);
 
 
 /*! Register a class at the message router.
 /*! Register a class at the message router.
  *  In order that the message router can deliver
  *  In order that the message router can deliver
  *  explicit messages each class has to register.
  *  explicit messages each class has to register.
- *  Will be automaticall done when invoking create
+ *  Will be automatically done when invoking create
  *  createCIPClass.
  *  createCIPClass.
- *  @param pa_pt2Object cip class to be registered
+ *  @param object CIP class to be registered
  *  @return EIP_OK on success
  *  @return EIP_OK on success
  */
  */
-EIP_STATUS
-registerClass(S_CIP_Class *pa_pt2Object);
+EipStatus RegisterClass(CipClass *object);
 
 
-#endif /*CIPMESSAGEROUTER_H_*/
+#endif /* OPENER_CIPMESSAGEROUTER_H_ */

+ 230 - 247
source/src/cip/ciptcpipinterface.c

@@ -4,293 +4,276 @@
  *
  *
  ******************************************************************************/
  ******************************************************************************/
 #include <string.h>
 #include <string.h>
-#include "opener_user_conf.h"
+
 #include "ciptcpipinterface.h"
 #include "ciptcpipinterface.h"
+
+#include "opener_user_conf.h"
 #include "cipcommon.h"
 #include "cipcommon.h"
 #include "cipmessagerouter.h"
 #include "cipmessagerouter.h"
 #include "ciperror.h"
 #include "ciperror.h"
 #include "endianconv.h"
 #include "endianconv.h"
 #include "cipethernetlink.h"
 #include "cipethernetlink.h"
 #include "opener_api.h"
 #include "opener_api.h"
-EIP_UINT32 TCP_Status = 0x1; /* #1  TCP status with 1 we indicate that we got a valid configuration from dhcp or bootp */
-EIP_UINT32 Configuration_Capability = 0x04 | 0x20; /* #2  This is a default value meaning that it is a DHCP client see 5-3.2.2.2 EIP spec*/
-                                                   /* #2  0x20 indicates "Hardware Configurable" */
-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 in 16 Bit chunks*/
-  CIP_ETHERNETLINK_CLASS_CODE, /* EIP_UINT16 ClassID*/
-  1, /* EIP_UINT16 InstanceNr*/
-  0 /* EIP_UINT16 AttributNr (not used as this is the EPATH the EthernetLink object)*/
-  };
-
-S_CIP_TCPIPNetworkInterfaceConfiguration Interface_Configuration = /* #5 */
-  { 0, /* default IP address */
-  0, /* NetworkMask */
-  0, /* Gateway */
-  0, /* NameServer */
-  0, /* NameServer2 */
-    { /* DomainName */
-    0, NULL, } };
-
-S_CIP_String Hostname = /* #6 */
-  { 0, NULL };
-/*! #8 the time to live value to be used for multi-cast connections
+
+CipDword tcp_status_ = 0x1; /**< #1  TCP status with 1 we indicate that we got a valid configuration from DHCP or BOOTP */
+CipDword configuration_capability_ = 0x04 | 0x20; /**< #2  This is a default value meaning that it is a DHCP client see 5-3.2.2.2 EIP specification; 0x20 indicates "Hardware Configurable" */
+CipDword configuration_control_ = 0; /**< #3  This is a TCP/IP object attribute. For now it is always zero and is not used for anything. */
+CipEpath physical_link_object_ = /**< #4 */
+{ 2, /**< EIP_UINT16 (UINT) PathSize in 16 Bit chunks*/
+CIP_ETHERNETLINK_CLASS_CODE, /**< EIP_UINT16 ClassID*/
+1, /**< EIP_UINT16 InstanceNr*/
+0 /**< EIP_UINT16 AttributNr (not used as this is the EPATH the EthernetLink object)*/
+};
+
+CipTcpIpNetworkInterfaceConfiguration interface_configuration_ = /**< #5 IP, network mask, gateway, name server 1 & 2, domain name*/
+{ 0, /* default IP address */
+0, /* NetworkMask */
+0, /* Gateway */
+0, /* NameServer */
+0, /* NameServer2 */
+{ /* DomainName */
+0, NULL, } };
+
+CipString hostname_ = /**< #6 Hostname*/
+{ 0, NULL };
+/** @brief #8 the time to live value to be used for multi-cast connections
  *
  *
- * Currently we implement it non setable and with the default value of 1.
- */EIP_UINT8 g_unTTLValue = 1;
+ * Currently we implement it non set-able and with the default value of 1.
+ */
+EipUint8 g_time_to_live_value = 1;
 
 
-/* ! #9 The multi cast configuration for this device
+/** @brief #9 The multicast configuration for this device
  *
  *
- * Currently we implement it non setable and use the default
+ * Currently we implement it non set-able and use the default
  * allocation algorithm
  * allocation algorithm
  */
  */
-SMcastConfig g_stMultiCastconfig =
-  { 0, /* us the default allocation algorithm */
-  0, /* reserved */
-  1, /* we currently use only one multicast address */
-  0 /* the multicast address will be allocated on ip address configuration */
-  };
+MulticastAddressConfiguration g_multicast_configuration = { 0, /* us the default allocation algorithm */
+0, /* reserved */
+1, /* we currently use only one multicast address */
+0 /* the multicast address will be allocated on ip address configuration */
+};
 
 
 /************** Functions ****************************************/
 /************** Functions ****************************************/
-EIP_STATUS
-getAttributeSingleTCPIPInterface(S_CIP_Instance *pa_pstInstance,
-    S_CIP_MR_Request *pa_pstMRRequest, S_CIP_MR_Response *pa_pstMRResponse);
+EipStatus GetAttributeSingleTcpIpInterface(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response);
 
 
-EIP_STATUS
-getAttributeAllTCPIPInterface(S_CIP_Instance * pa_pstInstance,
-    S_CIP_MR_Request * pa_stMRRequest, S_CIP_MR_Response * pa_stMRResponse);
+EipStatus GetAttributeAllTcpIpInterface(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response);
 
 
-EIP_STATUS
-configureNetworkInterface(const char *pa_acIpAdress,
-    const char *pa_acSubNetMask, const char *pa_acGateway)
-{
-  EIP_UINT32 nHostId;
+EipStatus ConfigureNetworkInterface(const char *ip_address,
+                                    const char *subnet_mask,
+                                    const char *gateway) {
+  EipUint32 host_id;
 
 
-  Interface_Configuration.IPAddress = inet_addr(pa_acIpAdress);
-  Interface_Configuration.NetworkMask = inet_addr(pa_acSubNetMask);
-  Interface_Configuration.Gateway = inet_addr(pa_acGateway);
+  interface_configuration_.ip_address = inet_addr(ip_address);
+  interface_configuration_.network_mask = inet_addr(subnet_mask);
+  interface_configuration_.gateway = inet_addr(gateway);
 
 
   /* calculate the CIP multicast address. The multicast address is calculated, not input*/
   /* calculate the CIP multicast address. The multicast address is calculated, not input*/
-  nHostId = ntohl(Interface_Configuration.IPAddress)
-      & ~ntohl(Interface_Configuration.NetworkMask); /* see CIP spec 3-5.3 for multicast address algorithm*/
-  nHostId -= 1;
-  nHostId &= 0x3ff;
+  host_id = ntohl(interface_configuration_.ip_address)
+      & ~ntohl(interface_configuration_.network_mask); /* see CIP spec 3-5.3 for multicast address algorithm*/
+  host_id -= 1;
+  host_id &= 0x3ff;
 
 
-  g_stMultiCastconfig.m_unMcastStartAddr = htonl(
-      ntohl(inet_addr("239.192.1.0")) + (nHostId << 5));
+  g_multicast_configuration.starting_multicast_address = htonl(
+      ntohl(inet_addr("239.192.1.0")) + (host_id << 5));
 
 
-  return EIP_OK;
+  return kEipStatusOk;
 }
 }
 
 
-void
-configureDomainName(const char *pa_acDomainName)
-{
-  if (NULL != Interface_Configuration.DomainName.String)
-    {
-      /* if the string is already set to a value we have to free the resources
-       * before we can set the new value in order to avoid memory leaks.
-       */
-      IApp_CipFree(Interface_Configuration.DomainName.String);
-    }
-  Interface_Configuration.DomainName.Length = strlen(pa_acDomainName);
-  if (Interface_Configuration.DomainName.Length)
-    {
-      Interface_Configuration.DomainName.String = (EIP_BYTE *) IApp_CipCalloc(
-          Interface_Configuration.DomainName.Length + 1, sizeof(EIP_INT8));
-      strcpy(Interface_Configuration.DomainName.String, pa_acDomainName);
-    }
-  else
-    {
-      Interface_Configuration.DomainName.String = NULL;
-    }
+void ConfigureDomainName(const char *domain_name) {
+  if (NULL != interface_configuration_.domain_name.string) {
+    /* if the string is already set to a value we have to free the resources
+     * before we can set the new value in order to avoid memory leaks.
+     */
+    CipFree(interface_configuration_.domain_name.string);
+  }
+  interface_configuration_.domain_name.length = strlen(domain_name);
+  if (interface_configuration_.domain_name.length) {
+    interface_configuration_.domain_name.string = (EipByte *) CipCalloc(
+        interface_configuration_.domain_name.length + 1, sizeof(EipInt8));
+    strcpy(interface_configuration_.domain_name.string, domain_name);
+  } else {
+    interface_configuration_.domain_name.string = NULL;
+  }
 }
 }
 
 
-void
-configureHostName(const char *pa_acHostName)
-{
-  if (NULL != Hostname.String)
-    {
-      /* if the string is already set to a value we have to free the resources
-       * before we can set the new value in order to avoid memory leaks.
-       */
-      IApp_CipFree(Hostname.String);
-    }
-  Hostname.Length = strlen(pa_acHostName);
-  if (Hostname.Length)
-    {
-      Hostname.String = (EIP_BYTE *) IApp_CipCalloc(Hostname.Length + 1,
-          sizeof(EIP_BYTE));
-      strcpy(Hostname.String, pa_acHostName);
-    }
-  else
-    {
-      Hostname.String = NULL;
-    }
+void ConfigureHostName(const char *hostname) {
+  if (NULL != hostname_.string) {
+    /* if the string is already set to a value we have to free the resources
+     * before we can set the new value in order to avoid memory leaks.
+     */
+    CipFree(hostname_.string);
+  }
+  hostname_.length = strlen(hostname);
+  if (hostname_.length) {
+    hostname_.string = (EipByte *) CipCalloc(hostname_.length + 1,
+                                             sizeof(EipByte));
+    strcpy(hostname_.string, hostname);
+  } else {
+    hostname_.string = NULL;
+  }
 }
 }
 
 
-EIP_STATUS
-setAttributeSingleTCP(S_CIP_Instance *pa_pstObjectInstance,
-    S_CIP_MR_Request *pa_pstMRRequest, S_CIP_MR_Response *pa_pstMRResponse)
-{
-  S_CIP_attribute_struct *pAttribute = getAttribute(pa_pstObjectInstance,
-      pa_pstMRRequest->RequestPath.AttributNr);
-  (void) pa_pstObjectInstance; /*Suppress compiler warning */
-
-  if (0 != pAttribute)
-    {
-      /* 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 */
-      /* TODO: check for flags associated with attributes */
-      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;
+EipStatus setAttributeSingleTcp(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response) {
+  CipAttributeStruct *attribute = GetCipAttribute(
+      instance, message_router_request->request_path.attribute_number);
+  (void) instance; /*Suppress compiler warning */
+
+  if (0 != attribute) {
+    /* 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 */
+    /* TODO: check for flags associated with attributes */
+    message_router_response->general_status = kCipErrorAttributeNotSetable;
+  } else {
+    /* we don't have this attribute */
+    message_router_response->general_status = kCipErrorAttributeNotSupported;
+  }
+
+  message_router_response->size_of_additional_status = 0;
+  message_router_response->data_length = 0;
+  message_router_response->reply_service = (0x80
+      | message_router_request->service);
+  return kEipStatusOkSend;
 }
 }
 
 
-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*/
-  8, /* # instance attributes*/
-  0xffffffff, /* instance getAttributeAll mask*/
-  1, /* # instance services*/
-  1, /* # instances*/
-  "TCP/IP interface", 3)) == 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, CIP_ATTRIB_GETABLE);
-  insertAttribute(pstInstance, 2, CIP_DWORD,
-      (void *) &Configuration_Capability, CIP_ATTRIB_GETABLE);
-  insertAttribute(pstInstance, 3, CIP_DWORD, (void *) &Configuration_Control, CIP_ATTRIB_GETABLE);
-  insertAttribute(pstInstance, 4, CIP_EPATH, &Physical_Link_Object, CIP_ATTRIB_GETABLE);
-  insertAttribute(pstInstance, 5, CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING,
-      &Interface_Configuration, CIP_ATTRIB_GETABLE);
-  insertAttribute(pstInstance, 6, CIP_STRING, (void *) &Hostname, CIP_ATTRIB_GETABLE);
-
-  insertAttribute(pstInstance, 8, CIP_USINT, (void *) &g_unTTLValue, CIP_ATTRIB_GETABLE);
-  insertAttribute(pstInstance, 9, CIP_ANY, (void *) &g_stMultiCastconfig, CIP_ATTRIB_GETABLE);
-
-  insertService(p_stTCPIPClass, CIP_GET_ATTRIBUTE_SINGLE,
-      &getAttributeSingleTCPIPInterface, "GetAttributeSingleTCPIPInterface");
-
-  insertService(p_stTCPIPClass, CIP_GET_ATTRIBUTE_ALL,
-      &getAttributeAllTCPIPInterface, "GetAttributeAllTCPIPInterface");
-
-  insertService(p_stTCPIPClass, CIP_SET_ATTRIBUTE_SINGLE,
-      &setAttributeSingleTCP, "SetAttributeSingle");
-
-  return EIP_OK;
+EipStatus CipTcpIpInterfaceInit() {
+  CipClass *p_stTCPIPClass;
+  CipInstance *pstInstance;
+
+  if ((p_stTCPIPClass = CreateCipClass(kCipTcpIpInterfaceClassCode, 0, /* # class attributes*/
+                                       0xffffffff, /* class getAttributeAll mask*/
+                                       0, /* # class services*/
+                                       8, /* # instance attributes*/
+                                       0xffffffff, /* instance getAttributeAll mask*/
+                                       1, /* # instance services*/
+                                       1, /* # instances*/
+                                       "TCP/IP interface", 3)) == 0) {
+    return kEipStatusError;
+  }
+  pstInstance = GetCipInstance(p_stTCPIPClass, 1); /* bind attributes to the instance #1 that was created above*/
+
+  InsertAttribute(pstInstance, 1, kCipDword, (void *) &tcp_status_,
+                  kGetableSingleAndAll);
+  InsertAttribute(pstInstance, 2, kCipDword,
+                  (void *) &configuration_capability_, kGetableSingleAndAll);
+  InsertAttribute(pstInstance, 3, kCipDword, (void *) &configuration_control_,
+                  kGetableSingleAndAll);
+  InsertAttribute(pstInstance, 4, kCipEpath, &physical_link_object_,
+                  kGetableSingleAndAll);
+  InsertAttribute(pstInstance, 5, kCipUdintUdintUdintUdintUdintString,
+                  &interface_configuration_, kGetableSingleAndAll);
+  InsertAttribute(pstInstance, 6, kCipString, (void *) &hostname_,
+                  kGetableSingleAndAll);
+
+  InsertAttribute(pstInstance, 8, kCipUsint, (void *) &g_time_to_live_value,
+                  kGetableSingleAndAll);
+  InsertAttribute(pstInstance, 9, kCipAny, (void *) &g_multicast_configuration,
+                  kGetableSingleAndAll);
+
+  InsertService(p_stTCPIPClass, kGetAttributeSingle,
+                &GetAttributeSingleTcpIpInterface,
+                "GetAttributeSingleTCPIPInterface");
+
+  InsertService(p_stTCPIPClass, kGetAttributeAll,
+                &GetAttributeAllTcpIpInterface,
+                "GetAttributeAllTCPIPInterface");
+
+  InsertService(p_stTCPIPClass, kSetAttributeSingle, &setAttributeSingleTcp,
+                "SetAttributeSingle");
+
+  return kEipStatusOk;
 }
 }
 
 
-void
-shutdownTCPIP_Interface(void)
-{
+void ShutdownTcpIpInterface(void) {
   /*Only free the resources if they are initialized */
   /*Only free the resources if they are initialized */
-  if (NULL != Hostname.String)
-    {
-      IApp_CipFree(Hostname.String);
-      Hostname.String = NULL;
-    }
-
-  if (NULL != Interface_Configuration.DomainName.String)
-    {
-      IApp_CipFree(Interface_Configuration.DomainName.String);
-      Interface_Configuration.DomainName.String = NULL;
-    }
+  if (NULL != hostname_.string) {
+    CipFree(hostname_.string);
+    hostname_.string = NULL;
+  }
+
+  if (NULL != interface_configuration_.domain_name.string) {
+    CipFree(interface_configuration_.domain_name.string);
+    interface_configuration_.domain_name.string = NULL;
+  }
 }
 }
 
 
-EIP_STATUS
-getAttributeSingleTCPIPInterface(S_CIP_Instance *pa_pstInstance,
-    S_CIP_MR_Request *pa_pstMRRequest, S_CIP_MR_Response *pa_pstMRResponse)
-{
-  EIP_STATUS nRetVal = EIP_OK_SEND;
-  EIP_BYTE *paMsg = pa_pstMRResponse->Data;
-  EIP_UINT32 unMultiCastAddr;
-
-  if (9 == pa_pstMRRequest->RequestPath.AttributNr)
-    { /* attribute 9 can not be easily handled with the default mechanism therefore we will do it by hand */
-      pa_pstMRResponse->DataLength = 0;
-      pa_pstMRResponse->ReplyService = (0x80 | pa_pstMRRequest->Service);
-      pa_pstMRResponse->GeneralStatus = CIP_ERROR_SUCCESS;
-      pa_pstMRResponse->SizeofAdditionalStatus = 0;
-
-      pa_pstMRResponse->DataLength += encodeData(CIP_USINT,
-          &(g_stMultiCastconfig.m_unAllocControl), &paMsg);
-      pa_pstMRResponse->DataLength += encodeData(CIP_USINT,
-          &(g_stMultiCastconfig.m_unReserved), &paMsg);
-      pa_pstMRResponse->DataLength += encodeData(CIP_UINT,
-          &(g_stMultiCastconfig.m_unNumMcast), &paMsg);
-
-      unMultiCastAddr = ntohl(
-          g_stMultiCastconfig.m_unMcastStartAddr);
-
-      pa_pstMRResponse->DataLength += encodeData(CIP_UDINT, &unMultiCastAddr,
-          &paMsg);
-    }
-  else
-    {
-      nRetVal = getAttributeSingle(pa_pstInstance, pa_pstMRRequest,
-          pa_pstMRResponse);
-    }
+EipStatus GetAttributeSingleTcpIpInterface(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response) {
+  EipStatus nRetVal = kEipStatusOkSend;
+  EipByte *paMsg = message_router_response->data;
+  EipUint32 unMultiCastAddr;
+
+  if (9 == message_router_request->request_path.attribute_number) { /* attribute 9 can not be easily handled with the default mechanism therefore we will do it by hand */
+    message_router_response->data_length = 0;
+    message_router_response->reply_service = (0x80
+        | message_router_request->service);
+    message_router_response->general_status = kCipErrorSuccess;
+    message_router_response->size_of_additional_status = 0;
+
+    message_router_response->data_length += EncodeData(
+        kCipUsint, &(g_multicast_configuration.alloc_control), &paMsg);
+    message_router_response->data_length += EncodeData(
+        kCipUsint, &(g_multicast_configuration.reserved_shall_be_zero), &paMsg);
+    message_router_response->data_length += EncodeData(
+        kCipUint,
+        &(g_multicast_configuration.number_of_allocated_multicast_addresses),
+        &paMsg);
+
+    unMultiCastAddr = ntohl(
+        g_multicast_configuration.starting_multicast_address);
+
+    message_router_response->data_length += EncodeData(kCipUdint,
+                                                       &unMultiCastAddr,
+                                                       &paMsg);
+  } else {
+    nRetVal = GetAttributeSingle(instance, message_router_request,
+                                 message_router_response);
+  }
   return nRetVal;
   return nRetVal;
 }
 }
 
 
-EIP_STATUS
-getAttributeAllTCPIPInterface(S_CIP_Instance * pa_pstInstance,
-    S_CIP_MR_Request * pa_stMRRequest, S_CIP_MR_Response * pa_stMRResponse)
-{
+EipStatus GetAttributeAllTcpIpInterface(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response) {
 
 
   int j;
   int j;
-  EIP_UINT8 *ptmp;
-  int nAttrNum;
-  S_CIP_attribute_struct *pstAttribute;
-
-  ptmp = pa_stMRResponse->Data; /* pointer into the reply */
-  pstAttribute = pa_pstInstance->pstAttributes;
-
-  for (j = 0; j < pa_pstInstance->pstClass->nNr_of_Attributes; j++) /* for each instance attribute of this class */
-    {
-      nAttrNum = pstAttribute->CIP_AttributNr;
-      if (nAttrNum < 32
-          && (pa_pstInstance->pstClass->nGetAttrAllMask & 1 << nAttrNum)) /* only return attributes that are flagged as being part of GetAttributeALl */
+  int attribute_number;
+
+  EipUint8 *response = message_router_response->data; /* pointer into the reply */
+  CipAttributeStruct *attribute = instance->attributes;
+
+  for (j = 0; j < instance->cip_class->number_of_attributes; j++) /* for each instance attribute of this class */
+  {
+    attribute_number = attribute->attribute_number;
+    if (attribute_number < 32
+        && (instance->cip_class->get_attribute_all_mask & 1 << attribute_number)) /* only return attributes that are flagged as being part of GetAttributeALl */
         {
         {
-          pa_stMRRequest->RequestPath.AttributNr = nAttrNum;
-
-          if (8 == nAttrNum)
-            { /* insert 6 zeros for the required empty safety network number according to Table 5-3.10 */
-              memset(pa_stMRResponse->Data, 0, 6);
-              pa_stMRResponse->Data += 6;
-            }
-
-          if (EIP_OK_SEND
-              != getAttributeSingleTCPIPInterface(pa_pstInstance,
-                  pa_stMRRequest, pa_stMRResponse))
-            {
-              pa_stMRResponse->Data = ptmp;
-              return EIP_ERROR;
-            }
-          pa_stMRResponse->Data += pa_stMRResponse->DataLength;
-        }
-      pstAttribute++;
+      message_router_request->request_path.attribute_number = attribute_number;
+
+      if (8 == attribute_number) { /* insert 6 zeros for the required empty safety network number according to Table 5-3.10 */
+        memset(message_router_response->data, 0, 6);
+        message_router_response->data += 6;
+      }
+
+      if (kEipStatusOkSend
+          != GetAttributeSingleTcpIpInterface(instance, message_router_request,
+                                              message_router_response)) {
+        message_router_response->data = response;
+        return kEipStatusError;
+      }
+      message_router_response->data += message_router_response->data_length;
     }
     }
-  pa_stMRResponse->DataLength = pa_stMRResponse->Data - ptmp;
-  pa_stMRResponse->Data = ptmp;
+    attribute++;
+  }
+  message_router_response->data_length = message_router_response->data
+      - response;
+  message_router_response->data = response;
 
 
-  return EIP_OK_SEND;
+  return kEipStatusOkSend;
 }
 }

+ 23 - 17
source/src/cip/ciptcpipinterface.h

@@ -6,35 +6,41 @@
 #ifndef CIPTCPIPINTERFACE_H_
 #ifndef CIPTCPIPINTERFACE_H_
 #define CIPTCPIPINTERFACE_H_
 #define CIPTCPIPINTERFACE_H_
 
 
+/** @file ciptcpipinterface.h
+ * @brief Public interface of the TCP/IP Interface Object
+ *
+ */
+
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
 
 
-#define CIP_TCPIPINTERFACE_CLASS_CODE 0xF5
+static const EipUint16 kCipTcpIpInterfaceClassCode = 0xF5; /**< TCP/IP Interface Object class code */
 
 
-typedef struct
-{
-  EIP_UINT8  m_unAllocControl;
-  EIP_UINT8  m_unReserved; /*!< shall be zereo */
-  EIP_UINT16 m_unNumMcast;
-  EIP_UINT32 m_unMcastStartAddr;
-}SMcastConfig;
+/** @brief Multicast Configuration struct, called Mcast config
+ *
+ */
+typedef struct multicast_address_configuration {
+  CipUsint alloc_control; /**< 0 for default multicast address generation algorithm; 1 for multicast addresses according to Num MCast and MCast Start Addr */
+  CipUsint reserved_shall_be_zero; /**< shall be zero */
+  CipUint number_of_allocated_multicast_addresses; /**< Number of IP multicast addresses allocated */
+  CipUdint starting_multicast_address; /**< Starting multicast address from which Num Mcast addresses are allocated */
+} MulticastAddressConfiguration;
 
 
 /* global public variables */
 /* global public variables */
-extern EIP_UINT8 g_unTTLValue;
-
-extern SMcastConfig g_stMultiCastconfig;
+extern CipUsint g_time_to_live_value; /**< Time-to-live value for IP multicast packets. Default is 1; Minimum is 1; Maximum is 255 */
 
 
+extern MulticastAddressConfiguration g_multicast_configuration; /**< Multicast configuration */
 
 
 /* public functions */
 /* public functions */
-/*!Initializing the data structures of the TCPIP interface object 
- */ 
-EIP_STATUS CIP_TCPIP_Interface_Init(void);
-/*!\brief Clean up the allocated data of the TCPIP interface object.
+/** @brief Initializing the data structures of the TCP/IP interface object
+ */
+EipStatus CipTcpIpInterfaceInit(void);
+
+/** @brief Clean up the allocated data of the TCP/IP interface object.
  *
  *
  * Currently this is the host name string and the domain name string.
  * Currently this is the host name string and the domain name string.
  *
  *
  */
  */
-void shutdownTCPIP_Interface(void);
-
+void ShutdownTcpIpInterface(void);
 
 
 #endif /*CIPTCPIPINTERFACE_H_*/
 #endif /*CIPTCPIPINTERFACE_H_*/

+ 352 - 348
source/src/cip/ciptypes.h

@@ -1,381 +1,385 @@
 /*******************************************************************************
 /*******************************************************************************
  * Copyright (c) 2009, Rockwell Automation, Inc.
  * Copyright (c) 2009, Rockwell Automation, Inc.
- * All rights reserved. 
+ * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIPTYPES_H_
-#define CIPTYPES_H_
+#ifndef OPENER_CIPTYPES_H_
+#define OPENER_CIPTYPES_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 
 
-/* TODO -- find some portable way of defining all these with Enums rather than #defines so that the names rather than hex number are displayed in the debugger*/
-#ifdef __GNUC__
 /** @brief Segment type Enum
 /** @brief Segment type Enum
  *
  *
  * Bits 7-5 in the Segment Type/Format byte
  * Bits 7-5 in the Segment Type/Format byte
  *
  *
  */
  */
-typedef enum SegmentType {
-	/* Segments */
-	SEG_PORT = 0x00, /**< Port segment */
-	SEG_LOGICAL = 0x20, /**< Logical segment */
-	SEG_NETWORK = 0x40, /**< Network segment */
-	SEG_SYMBOLIC = 0x60, /**< Symbolic segment */
-	SEG_DATA_SEGMENT = 0x80, /**< Data segment */
-	SEG_DATA_TYPE_CONSTRUCTED = 0xA0, /**< Data type constructed */
-	SEG_DATA_TYPE_ELEMENTARY = 0xC0, /**< Data type elementary */
-
-	/* Port segments */
-	SEG_EXTPORT = 0x10, /**< Extended Link Address Size flag, Port segment */
-
-	/* Logical Segments Segments */
-	SEG_CLASS = 0x20, /**< Class ID, Logical Segment */
-	SEG_INSTANCE = 0x25, /**< Instance ID, Logical Segment */
-	SEG_MEMBER = 0x2A, /**< Member ID, Logical Segment */
-	SEG_ATTRIBUTE = 0x30,  /**< Attribute ID, Logical Segment */
-	SEG_SPECIAL = 0x34, /**< Special, Logical Segment */
-	SEG_SERVICE = 0x38, /**< Service ID, Logical Segment */
-	SEG_EXTENDED_LOGICAL = 0x3C /**< Extended Logical, Logical Segment */
-
-} ESegmentType;
-
-#else
-
-#define SEG_PORT  0x00
-#define SEG_EXTPORT 0x10
-#define SEG_CLASS 0x20
-#define SEG_INSTANCE  0x24
-#define SEG_ATTRIBUTE 0x30
-#define SEG_NETWORK 0x40
-
-#endif
-
-#ifdef __GNUC__
-/** definition of CIP basic data types */
-typedef enum CIPDataTypes {
-	CIP_ANY = 0x00, /**< data type that can not be directly encoded */
-	CIP_BOOL = 0xC1, /**< boolean data type */
-	CIP_SINT = 0xC2, /**< 8-bit signed integer */
-	CIP_INT = 0xC3, /**< 16-bit signed integer */
-	CIP_DINT = 0xC4, /**< 32-bit signed integer */
-	CIP_LINT = 0xC5, /**< 64-bit signed integer */
-	CIP_USINT = 0xC6, /**< 8-bit unsigned integer */
-	CIP_UINT = 0xC7, /**< 16-bit unsigned integer */
-	CIP_UDINT = 0xC8, /**< 32-bit unsigned integer */
-	CIP_ULINT = 0xC9, /**< 64-bit unsigned integer */
-	CIP_REAL = 0xCA, /**< Single precision floating point */
-	CIP_LREAL = 0xCB, /**< Double precision floating point*/
-	CIP_STIME = 0xCC, /**< Synchronous time information*, type of DINT */
-	CIP_DATE = 0xCD, /**< Date only*/
-	CIP_TIME_OF_DAY = 0xCE, /**< Time of day */
-	CIP_DATE_AND_TIME = 0xCF, /**< Date and time of day */
-	CIP_STRING = 0xD0, /**< Character string, 1 byte per character */
-	CIP_BYTE = 0xD1, /**< 8-bit bit string */
-	CIP_WORD = 0xD2, /**< 16-bit bit string */
-	CIP_DWORD = 0xD3, /**< 32-bit bit string */
-	CIP_LWORD = 0xD4, /**< 64-bit bit string */
-	CIP_STRING2 = 0xD5, /**< Character string, 2 byte per character */
-	CIP_FTIME = 0xD6, /**< Duration in micro-seconds, high resolution; range of DINT */
-	CIP_LTIME = 0xD7, /**< Duration in micro-seconds, high resolution, range of LINT */
-	CIP_ITIME = 0xD8, /**< Duration in milli-seconds, short; range of INT*/
-	CIP_STRINGN = 0xD9, /**< Character string, N byte per character */
-	CIP_SHORT_STRING = 0xDA, /**< Character string, 1 byte per character, 1 byte length indicator */
-	CIP_TIME = 0xDB, /**< Duration in milli-seconds; range of DINT */
-	CIP_EPATH = 0xDC, /**< CIP path segments*/
-	CIP_ENGUNIT = 0xDD, /**< Engineering Units*/
-	/* definition of some CIP structs */
-	/* need to be validated in IEC 61131-3 subclause 2.3.3 */
-	CIP_USINT_USINT = 0xA0, /**< */
-	CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING = 0xA1, /**< TCP/IP attribute 5 - IP address, subnet mask, gateway, IP name server 1, IP name server 2, domain name*/
-	CIP_6USINT = 0xA2, /**< Struct for MAC Address (six USINTs)*/
-	CIP_MEMBER_LIST = 0xA3, /**< */
-	CIP_BYTE_ARRAY = 0xA4, /**< */
-	INTERNAL_UINT16_6 = 0xF0 /**< bogus hack, for port class attribute 9, TODO figure out the right way to handle it */
-
-} ECIPDataTypes;
-
-#else
-
-#define CIP_ANY                         0x00  /*data type that can not be directly encoded */
-#define CIP_BOOL 			0xC1
-#define CIP_SINT 			0xC2
-#define CIP_INT 			0xC3
-#define CIP_DINT 			0xC4
-#define CIP_LINT 			0xC5
-#define CIP_USINT 			0xC6
-#define CIP_UINT 			0xC7
-#define CIP_UDINT 			0xC8
-#define CIP_ULINT 			0xC9
-#define CIP_REAL 			0xCA
-#define CIP_LREAL 			0xCB
-#define CIP_STIME 			0xCC
-#define CIP_DATE 			0xCD
-#define CIP_TIME_OF_DAY 		0xCE
-#define CIP_DATE_AND_TIME 		0xCF
-#define CIP_STRING 			0xD0
-#define CIP_BYTE 			0xD1
-#define CIP_WORD 			0xD2
-#define CIP_DWORD 			0xD3
-#define CIP_LWORD 			0xD4
-#define CIP_STRING2 			0xD5
-#define CIP_FTIME 			0xD6
-#define CIP_LTIME 			0xD7
-#define CIP_ITIME 			0xD8
-#define CIP_STRINGN 			0xD9
-#define CIP_SHORT_STRING 		0xDA
-#define CIP_TIME 			0xDB
-#define CIP_EPATH 			0xDC
-#define CIP_ENGUNIT 			0xDD
-
-/* definition of some CIP structs */
-/* need to be validated in IEC 1131-3 subclause 2.3.3 */
-#define CIP_USINT_USINT 		0xA0
-#define CIP_UDINT_UDINT_UDINT_UDINT_UDINT_STRING 0xA1
-#define CIP_6USINT			0xA2 /* for MAC Address*/
-#define CIP_MEMBER_LIST			0xA3
-#define CIP_BYTE_ARRAY			0xA4
-
-#define INTERNAL_UINT16_6		0xF0				/* bogus hack, for port class attribute 9, TODO figure out the right way to handle it */
-
-#endif
-
-
-#ifdef __GNUC__
+typedef enum {
+  /* Segments */
+  kPortSegment = 0x00, /**< Port segment */
+  kLogicalSegment = 0x20, /**< Logical segment */
+  kNetworkSegment = 0x40, /**< Network segment */
+  kSymbolicSegment = 0x60, /**< Symbolic segment */
+  kDataSegment = 0x80, /**< Data segment */
+  kDataTypeConstructed = 0xA0, /**< Data type constructed */
+  kDataTypeElementary = 0xC0, /**< Data type elementary */
+  kSegmentTypeReserved = 0xE0
+} SegmentType;
+
+/** @brief Port Segment flags */
+typedef enum {
+  kExtendedLinkAddressSize = 0x10 /**< Extended Link Address Size flag, Port segment */
+} PortSegmentFlags;
+
+/** @brief Enum containing values which kind of logical segment is encoded */
+typedef enum {
+  kClassId = 0x00, /**< Class ID */
+  kInstanceId = 0x04, /**< Instance ID */
+  kMemberId = 0x08, /**< Member ID */
+  kConnectionPoint = 0x0C, /**< Connection Point */
+  kAttributeId = 0x10, /**< Attribute ID */
+  kSpecial = 0x14, /**< Special */
+  kService = 0x18, /**< Service ID */
+  kExtendedLogical = 0x1C /**< Extended Logical */
+} LogicalSegmentLogicalType;
+
+/** @brief Enum containing values how long the encoded value will be (8, 16, or
+ * 32 bit) */
+typedef enum {
+  kEightBitValue = 0x00,
+  kSixteenBitValue = 0x01,
+  kThirtyTwoBitValue = 0x02
+} LogicalSegmentLogicalFormat;
+
+typedef enum {
+  kProductionTimeInhibitTimeNetworkSegment = 0x43 /**< identifier indicating a production inhibit time network segment */
+} NetworkSegmentSubType;
+
+/** @brief Enum containing the encoding values for CIP data types for CIP
+ * Messages */
+typedef enum cip_data_types {
+  kCipAny = 0x00, /**< data type that can not be directly encoded */
+  kCipBool = 0xC1, /**< boolean data type */
+  kCipSint = 0xC2, /**< 8-bit signed integer */
+  kCipInt = 0xC3, /**< 16-bit signed integer */
+  kCipDint = 0xC4, /**< 32-bit signed integer */
+  kCipLint = 0xC5, /**< 64-bit signed integer */
+  kCipUsint = 0xC6, /**< 8-bit unsigned integer */
+  kCipUint = 0xC7, /**< 16-bit unsigned integer */
+  kCipUdint = 0xC8, /**< 32-bit unsigned integer */
+  kCipUlint = 0xC9, /**< 64-bit unsigned integer */
+  kCipReal = 0xCA, /**< Single precision floating point */
+  kCipLreal = 0xCB, /**< Double precision floating point*/
+  kCipStime = 0xCC, /**< Synchronous time information*, type of DINT */
+  kCipDate = 0xCD, /**< Date only*/
+  kCipTimeOfDay = 0xCE, /**< Time of day */
+  kCipDateAndTime = 0xCF, /**< Date and time of day */
+  kCipString = 0xD0, /**< Character string, 1 byte per character */
+  kCipByte = 0xD1, /**< 8-bit bit string */
+  kCipWord = 0xD2, /**< 16-bit bit string */
+  kCipDword = 0xD3, /**< 32-bit bit string */
+  kCipLword = 0xD4, /**< 64-bit bit string */
+  kCipString2 = 0xD5, /**< Character string, 2 byte per character */
+  kCipFtime = 0xD6, /**< Duration in micro-seconds, high resolution; range of DINT */
+  kCipLtime = 0xD7, /**< Duration in micro-seconds, high resolution, range of LINT */
+  kCipItime = 0xD8, /**< Duration in milli-seconds, short; range of INT*/
+  kCipStringN = 0xD9, /**< Character string, N byte per character */
+  kCipShortString = 0xDA, /**< Character string, 1 byte per character, 1 byte
+   length indicator */
+  kCipTime = 0xDB, /**< Duration in milli-seconds; range of DINT */
+  kCipEpath = 0xDC, /**< CIP path segments*/
+  kCipEngUnit = 0xDD, /**< Engineering Units*/
+  /* definition of some CIP structs */
+  /* need to be validated in IEC 61131-3 subclause 2.3.3 */
+  /* TODO: Check these codes */
+  kCipUsintUsint = 0xA0, /**< Used for CIP Identity attribute 4 Revision*/
+  kCipUdintUdintUdintUdintUdintString = 0xA1, /**< TCP/IP attribute 5 - IP address, subnet mask, gateway, IP name
+   server 1, IP name server 2, domain name*/
+  kCip6Usint = 0xA2, /**< Struct for MAC Address (six USINTs)*/
+  kCipMemberList = 0xA3, /**< */
+  kCipByteArray = 0xA4, /**< */
+  kInternalUint6 = 0xF0 /**< bogus hack, for port class attribute 9, TODO
+   figure out the right way to handle it */
+} CipDataTypes;
+
 /** @brief Definition of CIP service codes
 /** @brief Definition of CIP service codes
  *
  *
- * An Enum with all CIP service codes. Common services codes range from 0x01 to 0x1C
- * */
+ * An Enum with all CIP service codes. Common services codes range from 0x01 to
+ *0x1C
+ *
+ */
 typedef enum CIPServiceCodes {
 typedef enum CIPServiceCodes {
-	/* Start CIP common services */
-	CIP_GET_ATTRIBUTE_ALL = 0x01,
-	CIP_SET_ATTRIUBTE_ALL = 0x02,
-	CIP_GET_ATTRIBUTE_LIST = 0x03,
-	CIP_SET_ATTRIBUTE_LIST = 0x04,
-	CIP_RESET = 0x05,
-	CIP_START = 0x06,
-	CIP_STOP = 0x07,
-	CIP_CREATE = 0x08,
-	CIP_DELETE = 0x09,
-	CIP_MULTIPLE_SERVICE_PACKET = 0x0A,
-	CIP_APPLY_ATTRIBUTES = 0x0D,
-	CIP_GET_ATTRIBUTE_SINGLE = 0x0E,
-	CIP_SET_ATTRIBUTE_SINGLE = 0x10,
-	CIP_FIND_NEXT_OBJECT_INSTANCE = 0x11,
-	CIP_RESTORE = 0x15,
-	CIP_SAVE = 0x16,
-	CIP_NO_OPERATION = 0x17,
-	CIP_GET_MEMBER = 0x18,
-	CIP_SET_MEMBER = 0x19,
-	CIP_INSERT_MEMBER = 0x1A,
-	CIP_REMOVE_MEMBER = 0x1B,
-	CIP_GROUP_SYNC = 0x1C,
-	/* End CIP common services */
-
-	/* Start CIP object-specific services */
-	CIP_FORWARD_OPEN = 0x54,
-	CIP_FORWARD_CLOSE = 0x4E,
-	CIP_UNCONNECTED_SEND = 0x52,
-	CIP_GET_CONNECTION_OWNER = 0x5A
-	/* End CIP object-specific services */
+  /* Start CIP common services */
+  kGetAttributeAll = 0x01,
+  kSetAttributeAll = 0x02,
+  kGetAttributeList = 0x03,
+  kSetAttributeList = 0x04,
+  kReset = 0x05,
+  kStart = 0x06,
+  kStop = 0x07,
+  kCreate = 0x08,
+  kDelete = 0x09,
+  kMultipleServicePacket = 0x0A,
+  kApplyAttributes = 0x0D,
+  kGetAttributeSingle = 0x0E,
+  kSetAttributeSingle = 0x10,
+  kFindNextObjectInstance = 0x11,
+  kRestore = 0x15,
+  kSave = 0x16,
+  kNoOperation = 0x17,
+  kGetMember = 0x18,
+  kSetMember = 0x19,
+  kInsertMember = 0x1A,
+  kRemoveMember = 0x1B,
+  kGroupSync = 0x1C,
+  /* End CIP common services */
+
+  /* Start CIP object-specific services */
+  kForwardOpen = 0x54,
+  kForwardClose = 0x4E,
+  kUnconnectedSend = 0x52,
+  kGetConnectionOwner = 0x5A
+/* End CIP object-specific services */
 } ECIPServiceCodes;
 } ECIPServiceCodes;
 
 
-#else
-#define CIP_GET_ATTRIBUTE_SINGLE	0x0E
-#define CIP_SET_ATTRIBUTE_SINGLE	0x10
-#define CIP_RESET			0x05
-#define CIP_CREATE                      0x08
-#define CIP_GET_ATTRIBUTE_ALL		0x01
-#define CIP_FORWARD_OPEN		0x54
-#define CIP_FORWARD_CLOSE		0x4E
-#define CIP_UNCONNECTED_SEND		0x52
-#define CIP_GET_CONNECTION_OWNER	0x5A
-#endif
-
-
-#ifdef __GNUC__
-/** Definition of Get and Set Flags for CIP Attributes */
-typedef enum ECIPAttributeFlags { //TODO: Rework
-	CIP_ATTRIB_NONE = 0x00, /**< Neither set-able nor get-able */
-	CIP_ATTRIB_GETABLEALL = 0x01, /**< Get-able, also part of Get Attribute All service */
-	CIP_ATTRIB_GETABLESINGLE = 0x02, /**< Get-able via Get Attribute */
-	CIP_ATTRIB_SETABLE = 0x04, /**< Set-able via Set Attribute */
-	/* combined for convenience */
-	CIP_ATTRIB_SETGETABLE = 0x07, /**< both set and get-able */
-	CIP_ATTRIB_GETABLE = 0x03 /* both single and all */
-
+/** @brief Definition of Get and Set Flags for CIP Attributes */
+typedef enum ECIPAttributeFlags {  /* TODO: Rework */
+  KNotSetOrGetable = 0x00, /**< Neither set-able nor get-able */
+  kGetableAll = 0x01, /**< Get-able, also part of Get Attribute All service */
+  kGetableSingle = 0x02, /**< Get-able via Get Attribute */
+  kSetable = 0x04, /**< Set-able via Set Attribute */
+  /* combined for convenience */
+  kSetAndGetAble = 0x07, /**< both set and get-able */
+  kGetableSingleAndAll = 0x03 /**< both single and all */
 } CIPAttributeFlags;
 } CIPAttributeFlags;
-#else
-#define CIP_ATTRIB_NONE                 0x00
-#define CIP_ATTRIB_GETABLEALL           0x01
-#define CIP_ATTRIB_GETABLESINGLE        0x02
-#define CIP_ATTRIB_SETABLE              0x04
-/*combined for convenience */
-#define CIP_ATTRIB_SETGETABLE           0x07   /* both set- and get-able */
-#define CIP_ATTRIB_GETABLE              0x03   /* both single and all */
-#endif
-
-typedef enum IOConnectionEvent {
-	enOpened, enTimedOut, enClosed
-} EIOConnectionEvent;
-
-typedef struct CIPByteArray {
-	EIP_UINT16 Length;
-	EIP_BYTE *Data;
-} S_CIP_Byte_Array;
-
-typedef struct CIPShortString {
-	EIP_UINT8 Length;
-	EIP_BYTE *String;
-} S_CIP_Short_String;
-
-typedef struct CIPString {
-	EIP_UINT16 Length;
-	EIP_BYTE *String;
-} S_CIP_String;
-
-typedef struct CIPEPath {
-	EIP_UINT8 PathSize;
-	EIP_UINT16 ClassID;
-	EIP_UINT16 InstanceNr;
-	EIP_UINT16 AttributNr;
-} S_CIP_EPATH;
-
-typedef struct CIPConnectionPath {
-	EIP_UINT8 PathSize;
-	EIP_UINT32 ClassID;
-	EIP_UINT32 ConnectionPoint[3];
-	EIP_UINT8 DataSegment;
-	EIP_UINT8 *SegmentData;
-} S_CIP_ConnectionPath;
-
-typedef struct CIPKeyData {
-	EIP_UINT16 VendorID;
-	EIP_UINT16 DeviceType;
-	EIP_UINT16 ProductCode;
-	EIP_BYTE MajorRevision;
-	EIP_UINT8 MinorRevision;
-} S_CIP_KeyData;
-
-typedef struct CIPRevision {
-	EIP_UINT8 MajorRevision;
-	EIP_UINT8 MinorRevision;
-} S_CIP_Revision;
-
-typedef struct CIPElectronicKey {
-	EIP_UINT8 SegmentType;
-	EIP_UINT8 KeyFormat;
-	S_CIP_KeyData KeyData;
-} S_CIP_ElectronicKey;
-
-typedef struct {
-	EIP_UINT8 Service;
-	S_CIP_EPATH RequestPath;
-	EIP_INT16 DataLength;
-	EIP_UINT8 *Data;
-} S_CIP_MR_Request;
-
-#define MAX_SIZE_OF_ADD_STATUS 2 /* for now we support extended status codes up to 2 16bit values 
-									there is mostly only one 16bit value used */
-typedef struct {
-	EIP_UINT8 ReplyService;
-	EIP_UINT8 Reserved;
-	EIP_UINT8 GeneralStatus;
-	EIP_UINT8 SizeofAdditionalStatus;
-	EIP_UINT16 AdditionalStatus[MAX_SIZE_OF_ADD_STATUS];
-	EIP_INT16 DataLength;
-	EIP_UINT8 *Data;
-} S_CIP_MR_Response;
-
-typedef struct CIPAttributeStruct {
-	EIP_UINT16 CIP_AttributNr;
-	EIP_UINT8 CIP_Type;
-	EIP_BYTE CIP_AttributeFlags; /*< 0 => getable_all, 1 => getable_single; 2 => setable_single; 3 => get and setable; all other values reserved */
-	void *pt2data;
-} S_CIP_attribute_struct;
+
+typedef enum {
+  kOpenedEvent,
+  kTimedOutEvent,
+  kClosedEvent
+} IoConnectionEvents;
+
+/** @brief CIP Byte Array
+ *
+ */
+typedef struct cip_byte_array {
+  EipUint16 length; /**< Length of the Byte Array */
+  EipByte *data; /**< Pointer to the data */
+} CipByteArray;
+
+/** @brief CIP Short String
+ *
+ */
+typedef struct cip_short_string {
+  EipUint8 length; /**< Length of the String (8 bit value) */
+  EipByte *string; /**< Pointer to the string data */
+} CipShortString;
+
+/** @brief CIP String
+ *
+ */
+typedef struct cip_string {
+  EipUint16 length; /**< Length of the String (16 bit value) */
+  EipByte *string; /**< Pointer to the string data */
+} CipString;
+
+/** @brief Struct for padded EPATHs
+ *
+ */
+typedef struct cip_epath {
+  EipUint8 path_size;
+  /**< Size of the Path in 16-bit words */  /* TODO: Fix, should be UINT
+                                             (EIP_UINT16) */
+  EipUint16 class_id; /**< Class ID of the linked object */
+  EipUint16 instance_number; /**< Requested Instance Number of the linked object */
+  EipUint16 attribute_number; /**< Requested Attribute Number of the linked object */
+} CipEpath;
+
+/** @brief CIP Connection Path
+ *
+ */
+typedef struct cip_connection_path {
+  EipUint8 path_size;
+  /**< Size of the Path in 16-bit words */  /* TODO: Fix, should be UINT
+                                             (EIP_UINT16) */
+  EipUint32 class_id; /**< Class ID of the linked object */
+  EipUint32 connection_point[3];  /* TODO:  Why array length 3? */
+  EipUint8 data_segment;
+  EipUint8 *segment_data;
+} CipConnectionPath;
+
+/** @brief Struct representing the key data format of the electronic key segment
+ *
+ */
+typedef struct cip_key_data {
+  CipUint vendor_id; /**< Vendor ID */
+  CipUint device_type; /**< Device Type */
+  CipUint product_code; /**< Product Code */
+  CipByte major_revision; /**< Major Revision and Compatibility (Bit 0-6 = Major
+   Revision) Bit 7 = Compatibility */
+  CipUsint minor_revision; /**< Minor Revision */
+} CipKeyData;
+
+typedef struct cip_revision {
+  EipUint8 major_revision;
+  EipUint8 minor_revision;
+} CipRevision;
+
+/** @brief CIP Electronic Key Segment struct
+ *
+ */
+typedef struct cip_electronic_key {
+  CipUsint segment_type; /**< Specifies the Segment Type */
+  CipUsint key_format; /**< Key Format 0-3 reserved, 4 = see Key Format Table,
+   5-255 = Reserved */
+  CipKeyData key_data; /**< Depends on key format used, usually Key Format 4 as
+   specified in CIP Specification, Volume 1*/
+} CipElectronicKey;
+
+/** @brief CIP Message Router Request
+ *
+ */
+typedef struct cip_message_router_request {
+  EipUint8 service;
+  CipEpath request_path;
+  EipInt16 data_length;
+  EipUint8 *data;
+} CipMessageRouterRequest;
+
+#define MAX_SIZE_OF_ADD_STATUS                                            \
+  2 /* for now we support extended status codes up to 2 16bit values      \
+                                           there is mostly only one 16bit \
+       value used */
+
+/** @brief CIP Message Router Response
+ *
+ */
+typedef struct cip_message_router_response {
+  CipUsint reply_service; /**< Reply service code, the requested service code +
+   0x80 */
+  CipOctet reserved; /**< Reserved; Shall be zero */
+  CipUsint general_status; /**< One of the General Status codes listed in CIP
+   Specification Volume 1, Appendix B */
+  CipUsint size_of_additional_status; /**< Number of additional 16 bit words in
+   Additional Status Array */
+  EipUint16 additional_status[MAX_SIZE_OF_ADD_STATUS]; /**< Array of 16 bit words; Additional status;
+   If SizeOfAdditionalStatus is 0. there is no
+   Additional Status */
+  EipInt16 data_length;  /* TODO: Check if this is correct */
+  CipOctet *data; /**< Array of octet; Response data per object definition from
+   request */
+} CipMessageRouterResponse;
+
+typedef struct cip_attribute_struct {
+  EipUint16 attribute_number;
+  EipUint8 type;
+  EipByte attribute_flags; /*< 0 => getable_all, 1 => getable_single; 2 =>
+   setable_single; 3 => get and setable; all other
+   values reserved */
+  void *data;
+} CipAttributeStruct;
 
 
 /* type definition of CIP service structure */
 /* type definition of CIP service structure */
 
 
 /* instances are stored in a linked list*/
 /* instances are stored in a linked list*/
-typedef struct CIP_Instance {
-	EIP_UINT32 nInstanceNr; /**< this instance's number (unique within the class) */
-	S_CIP_attribute_struct *pstAttributes; /**< pointer to an array of attributes which is unique to this instance */
-	struct CIP_Class *pstClass; /**< class the instance belongs to */
-	struct CIP_Instance *pstNext; /**< next instance, all instances of a class live in a linked list */
-} S_CIP_Instance;
+typedef struct cip_instance {
+  EipUint32 instance_number; /**< this instance's number (unique within the class) */
+  CipAttributeStruct *attributes; /**< pointer to an array of attributes which
+   is unique to this instance */
+  struct cip_class *cip_class; /**< class the instance belongs to */
+  struct cip_instance *next; /**< next instance, all instances of a class live
+   in a linked list */
+} CipInstance;
 
 
 /** @brief Class is a subclass of Instance */
 /** @brief Class is a subclass of Instance */
-typedef struct CIP_Class {
-	S_CIP_Instance m_stSuper;
-
-	/* the rest of these are specific to the Class class only. */
-	EIP_UINT32 nClassID; /**< class ID */
-	EIP_UINT16 nRevision; /**< class revision*/
-	EIP_UINT16 nNr_of_Instances; /**< number of instances in the class (not including instance 0)*/
-	EIP_UINT16 nNr_of_Attributes; /**< number of attributes of each instance*/
-	EIP_UINT16 nMaxAttribute; /**< highest defined attribute number (attribute numbers are not necessarily consecutive)*/
-	EIP_UINT32 nGetAttrAllMask; /**< mask indicating which attributes are returned by getAttributeAll*/
-	EIP_UINT16 nNr_of_Services; /**< number of services supported*/
-	S_CIP_Instance *pstInstances; /**< pointer to the list of instances*/
-	struct CIP_service_struct *pstServices; /**< pointer to the array of services*/
-	char *acName; /**< class name */
-} S_CIP_Class;
+typedef struct cip_class {
+  CipInstance m_stSuper;
+
+  /* the rest of these are specific to the Class class only. */
+  EipUint32 class_id; /**< class ID */
+  EipUint16 revision; /**< class revision*/
+  EipUint16 number_of_instances; /**< number of instances in the class (not
+   including instance 0)*/
+  EipUint16 number_of_attributes; /**< number of attributes of each instance*/
+  EipUint16 highest_attribute_number; /**< highest defined attribute number
+   (attribute numbers are not necessarily
+   consecutive)*/
+  EipUint32 get_attribute_all_mask; /**< mask indicating which attributes are
+   returned by getAttributeAll*/
+  EipUint16 number_of_services; /**< number of services supported*/
+  CipInstance *instances; /**< pointer to the list of instances*/
+  struct cip_service_struct *services; /**< pointer to the array of services*/
+  char *class_name; /**< class name */
+} CipClass;
 
 
 /** @ingroup CIP_API
 /** @ingroup CIP_API
- *  @typedef  EIP_STATUS (*TCIPServiceFunc)(S_CIP_Instance *pa_pstInstance, S_CIP_MR_Request *pa_MRRequest, S_CIP_MR_Response *pa_MRResponse)
+ *  @typedef  EIP_STATUS (*TCIPServiceFunc)(S_CIP_Instance *pa_pstInstance,
+ *S_CIP_MR_Request *pa_MRRequest, S_CIP_MR_Response *pa_MRResponse)
  *  @brief Signature definition for the implementation of CIP services.
  *  @brief Signature definition for the implementation of CIP services.
  *
  *
- *  CIP services have to follow this signature in order to be handled correctly by the stack.
- *  @param pa_pstInstance the instance which was referenced in the service request
+ *  CIP services have to follow this signature in order to be handled correctly
+ *by the stack.
+ *  @param pa_pstInstance the instance which was referenced in the service
+ *request
  *  @param pa_MRRequest request data
  *  @param pa_MRRequest request data
- *  @param pa_MRResponse storage for the response data, including a buffer for extended data
- *  @return EIP_OK_SEND if service could be executed successfully and a response should be sent
+ *  @param pa_MRResponse storage for the response data, including a buffer for
+ *extended data
+ *  @return EIP_OK_SEND if service could be executed successfully and a response
+ *should be sent
+ */
+typedef EipStatus (*CipServiceFunction)(
+    CipInstance *instance, CipMessageRouterRequest *message_router_request,
+    CipMessageRouterResponse *message_router_response);
+
+/** @brief Service descriptor. These are stored in an array */
+typedef struct cip_service_struct {
+  EipUint8 service_number; /**< service number*/
+  CipServiceFunction service_function; /**< pointer to a function call*/
+  char *name; /**< name of the service */
+} CipServiceStruct;
+
+/**
+ * @brief Struct for saving TCP/IP interface information
  */
  */
-typedef EIP_STATUS
-(*TCIPServiceFunc)(S_CIP_Instance *pa_pstInstance,
-		S_CIP_MR_Request *pa_MRRequest, S_CIP_MR_Response *pa_MRResponse);
-
-/** @brief service descriptor. These are stored in an array*/
-typedef struct CIP_service_struct {
-	EIP_UINT8 CIP_ServiceNr; /**< service number*/
-	TCIPServiceFunc m_ptfuncService; /**< pointer to a function call*/
-	char *name; /**< name of the service */
-} S_CIP_service_struct;
-
-typedef struct CIPTCPIPNetworkInterfaceConfiguration {
-	EIP_UINT32 IPAddress;
-	EIP_UINT32 NetworkMask;
-	EIP_UINT32 Gateway;
-	EIP_UINT32 NameServer;
-	EIP_UINT32 NameServer2;
-	S_CIP_String DomainName;
-} S_CIP_TCPIPNetworkInterfaceConfiguration;
-
-typedef struct CIPRPath {
-	EIP_UINT8 PathSize;
-	EIP_UINT32 Port; /* support up to 32 bit path*/
-	EIP_UINT32 Address;
-} S_CIP_RPATH;
-
-typedef struct CIPUnconnectedSendParam {
-	EIP_BYTE Priority;
-	EIP_UINT8 Timeout_Ticks;
-	EIP_UINT16 Message_Request_Size;
-	S_CIP_MR_Request Message_Request;
-	S_CIP_MR_Response *Message_Response;
-	EIP_UINT8 Reserved;
-	S_CIP_RPATH Route_Path;
-	void *CPFdata;
-} S_CIP_UnconnectedSend_Param_Struct;
+typedef struct cip_tcp_ip_network_interface_configuration {
+  CipUdint ip_address;
+  CipUdint network_mask;
+  CipUdint gateway;
+  CipUdint name_server;
+  CipUdint name_server_2;
+  CipString domain_name;
+} CipTcpIpNetworkInterfaceConfiguration;
+
+typedef struct cip_route_path {
+  EipUint8 path_size;
+  EipUint32 port; /* support up to 32 bit path*/
+  EipUint32 address;
+} CipRoutePath;
+
+typedef struct cip_unconnected_send_parameter {
+  EipByte priority;
+  EipUint8 timeout_ticks;
+  EipUint16 message_request_size;
+  CipMessageRouterRequest message_request;
+  CipMessageRouterResponse *message_response;
+  EipUint8 reserved;
+  CipRoutePath route_path;
+  void *data;
+} CipUnconnectedSendParameter;
 
 
 /* these are used for creating the getAttributeAll masks
 /* these are used for creating the getAttributeAll masks
  TODO there might be a way simplifying this using __VARARGS__ in #define */
  TODO there might be a way simplifying this using __VARARGS__ in #define */
-#define MASK1(a)               (1<<(a))
-#define MASK2(a,b)             (1<<(a) | 1<<(b))
-#define MASK3(a,b,c)           (1<<(a) | 1<<(b) | 1<<(c))
-#define MASK4(a,b,c,d)         (1<<(a) | 1<<(b) | 1<<(c) | 1<<(d))
-#define MASK5(a,b,c,d,e)       (1<<(a) | 1<<(b) | 1<<(c) | 1<<(d) | 1<<(e))
-#define MASK6(a,b,c,d,e,f)     (1<<(a) | 1<<(b) | 1<<(c) | 1<<(d) | 1<<(e) | 1<<(f))
-#define MASK7(a,b,c,d,e,f,g)   (1<<(a) | 1<<(b) | 1<<(c) | 1<<(d) | 1<<(e) | 1<<(f) | 1<<(g))
-#define MASK8(a,b,c,d,e,f,g,h) (1<<(a) | 1<<(b) | 1<<(c) | 1<<(d) | 1<<(e) | 1<<(f) | 1<<(g) | 1<<(h))
-
-#endif /*CIPTYPES_H_*/
+#define MASK1(a) (1 << (a))
+#define MASK2(a, b) (1 << (a) | 1 << (b))
+#define MASK3(a, b, c) (1 << (a) | 1 << (b) | 1 << (c))
+#define MASK4(a, b, c, d) (1 << (a) | 1 << (b) | 1 << (c) | 1 << (d))
+#define MASK5(a, b, c, d, e) \
+  (1 << (a) | 1 << (b) | 1 << (c) | 1 << (d) | 1 << (e))
+#define MASK6(a, b, c, d, e, f) \
+  (1 << (a) | 1 << (b) | 1 << (c) | 1 << (d) | 1 << (e) | 1 << (f))
+#define MASK7(a, b, c, d, e, f, g) \
+  (1 << (a) | 1 << (b) | 1 << (c) | 1 << (d) | 1 << (e) | 1 << (f) | 1 << (g))
+#define MASK8(a, b, c, d, e, f, g, h)                                \
+  (1 << (a) | 1 << (b) | 1 << (c) | 1 << (d) | 1 << (e) | 1 << (f) | \
+   1 << (g) | 1 << (h))
+
+#endif /* OPENER_CIPTYPES_H_ */

+ 269 - 280
source/src/enet_encap/cpf.c

@@ -14,116 +14,103 @@
 #include <string.h>
 #include <string.h>
 
 
 /* CPF global data items */
 /* CPF global data items */
-S_CIP_CPF_Data g_stCPFDataItem;
+CipCommonPacketFormatData g_common_packet_format_data_item;
 
 
-int
-notifyCPF(struct S_Encapsulation_Data * pa_stReceiveData, /* recieved encap data*/
-EIP_UINT8 * pa_acReplyBuf) /* reply buffer*/
-{
-  int nRetVal;
+int NotifyCommonPacketFormat(EncapsulationData *receive_data,
+                             EipUint8 *reply_buffer) {
+  int return_value;
 
 
-  if ((nRetVal = createCPFstructure(pa_stReceiveData->m_acCurrentCommBufferPos,
-      pa_stReceiveData->nData_length, &g_stCPFDataItem)) == EIP_ERROR)
-    {
-      OPENER_TRACE_ERR("notifyCPF: error from createCPFstructure\n");
-    }
-  else
-    {
-      nRetVal = EIP_OK; /* In cases of errors we normaly need to send an error response */
-      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*/
-              nRetVal = notifyMR(g_stCPFDataItem.stDataI_Item.Data,
-                  g_stCPFDataItem.stDataI_Item.Length);
-              if (nRetVal != EIP_ERROR)
-                {
-                  nRetVal = assembleLinearMsg(&gMRResponse, &g_stCPFDataItem,
-                      pa_acReplyBuf);
-                }
-            }
-          else
-            {
-              /* wrong data item detected*/
-              OPENER_TRACE_ERR(
-                  "notifyCPF: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
-              pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INCORRECT_DATA;
-            }
-        }
-      else
-        {
-          OPENER_TRACE_ERR("notifyCPF: got something besides the expected CIP_ITEM_ID_NULL\n");
-          pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INCORRECT_DATA;
+  if ((return_value = CreateCommonPacketFormatStructure(
+      receive_data->current_communication_buffer_position,
+      receive_data->data_length, &g_common_packet_format_data_item))
+      == kEipStatusError) {
+    OPENER_TRACE_ERR("notifyCPF: error from createCPFstructure\n");
+  } else {
+    return_value = kEipStatusOk; /* In cases of errors we normally need to send an error response */
+    if (g_common_packet_format_data_item.address_item.type_id == kNullAddressId) /* check if NullAddressItem received, otherwise it is no unconnected message and should not be here*/
+    { /* found null address item*/
+      if (g_common_packet_format_data_item.data_item.type_id
+          == kUnconnectedMessageId) { /* unconnected data item received*/
+        return_value = NotifyMR(
+            g_common_packet_format_data_item.data_item.data,
+            g_common_packet_format_data_item.data_item.length);
+        if (return_value != kEipStatusError) {
+          return_value = AssembleLinearMessage(
+              &g_message_router_response, &g_common_packet_format_data_item,
+              reply_buffer);
         }
         }
+      } else {
+        /* wrong data item detected*/
+        OPENER_TRACE_ERR(
+            "notifyCPF: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
+        receive_data->status = kEncapsulationProtocolIncorrectData;
+      }
+    } else {
+      OPENER_TRACE_ERR(
+          "notifyCPF: got something besides the expected CIP_ITEM_ID_NULL\n");
+      receive_data->status = kEncapsulationProtocolIncorrectData;
     }
     }
-  return nRetVal;
+  }
+  return return_value;
 }
 }
 
 
-int
-notifyConnectedCPF(struct S_Encapsulation_Data * pa_stReceiveData, /* recieved encap data*/
-EIP_UINT8 * pa_acReplyBuf) /* reply buffer*/
-{
-  int nRetVal;
-  S_CIP_ConnectionObject *pstConnectionObject;
+int NotifyConnectedCommonPacketFormat(EncapsulationData *received_data,
+                                      EipUint8 *reply_buffer) {
+  int return_value;
+  ConnectionObject *connection_object;
 
 
-  nRetVal = createCPFstructure(pa_stReceiveData->m_acCurrentCommBufferPos,
-      pa_stReceiveData->nData_length, &g_stCPFDataItem);
+  return_value = CreateCommonPacketFormatStructure(
+      received_data->current_communication_buffer_position,
+      received_data->data_length, &g_common_packet_format_data_item);
 
 
-  if (EIP_ERROR == nRetVal)
-    {
-      OPENER_TRACE_ERR("notifyConnectedCPF: error from createCPFstructure\n");
-    }
-  else
-    {
-      nRetVal = EIP_ERROR; /* For connected explicit messages status always has to be 0*/
-      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*/
+  if (kEipStatusError == return_value) {
+    OPENER_TRACE_ERR("notifyConnectedCPF: error from createCPFstructure\n");
+  } else {
+    return_value = kEipStatusError; /* For connected explicit messages status always has to be 0*/
+    if (g_common_packet_format_data_item.address_item.type_id
+        == kConnectionBasedId) /* check if ConnectedAddressItem received, otherwise it is no connected message and should not be here*/
         { /* ConnectedAddressItem item */
         { /* ConnectedAddressItem item */
-          pstConnectionObject = getConnectedObject(
-              g_stCPFDataItem.stAddr_Item.Data.ConnectionIdentifier);
-          if (NULL != pstConnectionObject)
-            {
-              /* reset the watchdog timer */
-              pstConnectionObject->InnacitvityWatchdogTimer =
-                  (pstConnectionObject->O_to_T_RPI / 1000)
-                      << (2 + pstConnectionObject->ConnectionTimeoutMultiplier);
+      connection_object = GetConnectedObject(
+          g_common_packet_format_data_item.address_item.data
+              .connection_identifier);
+      if (NULL != connection_object) {
+        /* reset the watchdog timer */
+        connection_object->inactivity_watchdog_timer = (connection_object
+            ->o_to_t_requested_packet_interval / 1000)
+            << (2 + connection_object->connection_timeout_multiplier);
 
 
-              /*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);
-                  nRetVal = notifyMR(pnBuf,
-                      g_stCPFDataItem.stDataI_Item.Length - 2);
+        /*TODO check connection id  and sequence count    */
+        if (g_common_packet_format_data_item.data_item.type_id
+            == kConnectedTransportPacketId) { /* connected data item received*/
+          EipUint8 *pnBuf = g_common_packet_format_data_item.data_item.data;
+          g_common_packet_format_data_item.address_item.data.sequence_number =
+              (EipUint32) GetIntFromMessage(&pnBuf);
+          return_value = NotifyMR(
+              pnBuf, g_common_packet_format_data_item.data_item.length - 2);
 
 
-                  if (nRetVal != EIP_ERROR)
-                    {
-                      g_stCPFDataItem.stAddr_Item.Data.ConnectionIdentifier =
-                          pstConnectionObject->CIPProducedConnectionID;
-                      nRetVal = assembleLinearMsg(&gMRResponse,
-                          &g_stCPFDataItem, pa_acReplyBuf);
-                    }
-                }
-              else
-                {
-                  /* wrong data item detected*/
-                  OPENER_TRACE_ERR(
-                      "notifyConnectedCPF: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
-                }
-            }
-          else
-            {
-              OPENER_TRACE_ERR("notifyConnectedCPF: connection with given ID could not be found\n");
-            }
-        }
-      else
-        {
-          OPENER_TRACE_ERR("notifyConnectedCPF: got something besides the expected CIP_ITEM_ID_NULL\n");
+          if (return_value != kEipStatusError) {
+            g_common_packet_format_data_item.address_item.data
+                .connection_identifier = connection_object
+                ->produced_connection_id;
+            return_value = AssembleLinearMessage(
+                &g_message_router_response, &g_common_packet_format_data_item,
+                reply_buffer);
+          }
+        } else {
+          /* wrong data item detected*/
+          OPENER_TRACE_ERR(
+              "notifyConnectedCPF: got something besides the expected CIP_ITEM_ID_UNCONNECTEDMESSAGE\n");
         }
         }
+      } else {
+        OPENER_TRACE_ERR(
+            "notifyConnectedCPF: connection with given ID could not be found\n");
+      }
+    } else {
+      OPENER_TRACE_ERR(
+          "notifyConnectedCPF: got something besides the expected CIP_ITEM_ID_NULL\n");
     }
     }
-  return nRetVal;
+  }
+  return return_value;
 }
 }
 
 
 /*   INT16 createCPFstructure(INT8 *pa_Data, INT16 pa_DataLength, S_CIP_CPF_Data *pa_CPF_data)
 /*   INT16 createCPFstructure(INT8 *pa_Data, INT16 pa_DataLength, S_CIP_CPF_Data *pa_CPF_data)
@@ -135,92 +122,85 @@ EIP_UINT8 * pa_acReplyBuf) /* reply buffer*/
  * 		0 .. success
  * 		0 .. success
  * 	       -1 .. error
  * 	       -1 .. error
  */
  */
-EIP_STATUS
-createCPFstructure(EIP_UINT8 * pa_Data, int pa_DataLength,
-    S_CIP_CPF_Data * pa_CPF_data)
-{
+EipStatus CreateCommonPacketFormatStructure(
+    EipUint8 *data, int data_length,
+    CipCommonPacketFormatData *common_packet_format_data) {
   int len_count, i, j;
   int len_count, i, j;
 
 
-  pa_CPF_data->AddrInfo[0].TypeID = 0;
-  pa_CPF_data->AddrInfo[1].TypeID = 0;
+  common_packet_format_data->address_info_item[0].type_id = 0;
+  common_packet_format_data->address_info_item[1].type_id = 0;
 
 
   len_count = 0;
   len_count = 0;
-  pa_CPF_data->ItemCount = ltohs(&pa_Data);
+  common_packet_format_data->item_count = GetIntFromMessage(&data);
   len_count += 2;
   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);
+  if (common_packet_format_data->item_count >= 1) {
+    common_packet_format_data->address_item.type_id = GetIntFromMessage(&data);
+    common_packet_format_data->address_item.length = GetIntFromMessage(&data);
+    len_count += 4;
+    if (common_packet_format_data->address_item.length >= 4) {
+      common_packet_format_data->address_item.data.connection_identifier =
+          GetDintFromMessage(&data);
       len_count += 4;
       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);
-      len_count += 2;
-      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))
-        {
-          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 += 18;
-        }
-      else
-        { /* no sockaddr item found */
-          pa_CPF_data->AddrInfo[j].TypeID = 0; /* mark as not set */
-          pa_Data -= 2;
-        }
+    if (common_packet_format_data->address_item.length == 8) {
+      common_packet_format_data->address_item.data.sequence_number =
+          GetDintFromMessage(&data);
+      len_count += 4;
     }
     }
-  /* 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 (common_packet_format_data->item_count >= 2) {
+    common_packet_format_data->data_item.type_id = GetIntFromMessage(&data);
+    common_packet_format_data->data_item.length = GetIntFromMessage(&data);
+    common_packet_format_data->data_item.data = data;
+    data += common_packet_format_data->data_item.length;
+    len_count += (4 + common_packet_format_data->data_item.length);
+  }
+  for (j = 0; j < (common_packet_format_data->item_count - 2); j++) /* TODO there needs to be a limit check here???*/
+  {
+    common_packet_format_data->address_info_item[j].type_id = GetIntFromMessage(
+        &data);
+    len_count += 2;
+    if ((common_packet_format_data->address_info_item[j].type_id
+        == kSocketAddressInfoOriginatorToTargetId)
+        || (common_packet_format_data->address_info_item[j].type_id
+            == kSocketAddressInfoTargetToOriginatorId)) {
+      common_packet_format_data->address_info_item[j].length =
+          GetIntFromMessage(&data);
+      common_packet_format_data->address_info_item[j].nsin_family =
+          GetIntFromMessage(&data);
+      common_packet_format_data->address_info_item[j].nsin_port =
+          GetIntFromMessage(&data);
+      common_packet_format_data->address_info_item[j].nsin_addr =
+          GetDintFromMessage(&data);
+      for (i = 0; i < 8; i++) {
+        common_packet_format_data->address_info_item[j].nasin_zero[i] = *data;
+        data++;
+      }
+      len_count += 18;
+    } else { /* no sockaddr item found */
+      common_packet_format_data->address_info_item[j].type_id = 0; /* mark as not set */
+      data -= 2;
     }
     }
-  if (len_count == pa_DataLength)
-    { /* length of data is equal to length of Addr and length of Data */
-      return EIP_OK;
+  }
+  /* set the addressInfoItems to not set if they were not received */
+  if (common_packet_format_data->item_count < 4) {
+    common_packet_format_data->address_info_item[1].type_id = 0;
+    if (common_packet_format_data->item_count < 3) {
+      common_packet_format_data->address_info_item[0].type_id = 0;
     }
     }
-  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;
-        }
+  }
+  if (len_count == data_length) { /* length of data is equal to length of Addr and length of Data */
+    return kEipStatusOk;
+  } else {
+    OPENER_TRACE_WARN(
+        "something is wrong with the length in MR @ createCPFstructure\n");
+    if (common_packet_format_data->item_count > 2) {
+      /* there is an optional packet in data stream which is not sockaddr item */
+      return kEipStatusOk;
+    } else { /* something with the length was wrong */
+      return kEipStatusError;
     }
     }
+  }
 }
 }
 
 
 /*   INT8 assembleLinearMsg(S_CIP_MR_Response *pa_MRResponse, S_CIP_CPF_Data *pa_CPFDataItem, INT8 *pa_msg)
 /*   INT8 assembleLinearMsg(S_CIP_MR_Response *pa_MRResponse, S_CIP_CPF_Data *pa_CPFDataItem, INT8 *pa_msg)
@@ -231,134 +211,143 @@ createCPFstructure(EIP_UINT8 * pa_Data, int pa_DataLength,
  *  return length of reply in pa_msg in bytes
  *  return length of reply in pa_msg in bytes
  * 			-1 .. error
  * 			-1 .. error
  */
  */
-int
-assembleLinearMsg(S_CIP_MR_Response * pa_MRResponse,
-    S_CIP_CPF_Data * pa_CPFDataItem, EIP_UINT8 * pa_msg)
-{
-  int i, j, size, type;
+int AssembleLinearMessage(
+    CipMessageRouterResponse *message_router_response,
+    CipCommonPacketFormatData * common_packet_format_data_item,
+    EipUint8 *message) {
+  int i, j, type;
 
 
-  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;
-    }
+  int size = 0;
+  if (message_router_response) {
+    /* add Interface Handle and Timeout = 0 -> only for SendRRData and SendUnitData necessary */
+    AddDintToMessage(0, &message);
+    AddIntToMessage(0, &message);
+    size += 6;
+  }
 
 
-  htols(pa_CPFDataItem->ItemCount, &pa_msg); /* item count */
+  AddIntToMessage(common_packet_format_data_item->item_count, &message); /* item count */
   size += 2;
   size += 2;
   /* process Address Item */
   /* 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;
-    }
+  if (common_packet_format_data_item->address_item.type_id == kNullAddressId) { /* null address item -> address length set to 0 */
+    AddIntToMessage(kNullAddressId, &message);
+    AddIntToMessage(0, &message);
+    size += 4;
+  }
+  if (common_packet_format_data_item->address_item.type_id
+      == kConnectionBasedId) { /* connected data item -> address length set to 4 and copy ConnectionIdentifier */
+    AddIntToMessage(kConnectionBasedId, &message);
+    AddIntToMessage(4, &message);
+    AddDintToMessage(
+        common_packet_format_data_item->address_item.data.connection_identifier,
+        &message);
+    size += 8;
+  }
+  /* sequence number????? */
+  if (common_packet_format_data_item->address_item.type_id
+      == kSequencedAddressItemId) { /* sequenced address item -> address length set to 8 and copy ConnectionIdentifier and SequenceNumber */
+    AddIntToMessage(kSequencedAddressItemId, &message);
+    AddIntToMessage(8, &message);
+    AddDintToMessage(
+        common_packet_format_data_item->address_item.data.connection_identifier,
+        &message);
+    AddDintToMessage(
+        common_packet_format_data_item->address_item.data.sequence_number,
+        &message);
+    size += 12;
+  }
 
 
   /* process Data Item */
   /* 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 ((common_packet_format_data_item->data_item.type_id
+      == kUnconnectedMessageId)
+      || (common_packet_format_data_item->data_item.type_id
+          == kConnectedTransportPacketId)) {
+    if (message_router_response) {
+      AddIntToMessage(common_packet_format_data_item->data_item.type_id,
+                      &message);
 
 
-          if (pa_CPFDataItem->stDataI_Item.TypeID
-              == CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET)
-            {
-              htols(
-                  (EIP_UINT16) (pa_MRResponse->DataLength + 4 + 2
-                      + (2 * pa_MRResponse->SizeofAdditionalStatus)), &pa_msg);
+      if (common_packet_format_data_item->data_item.type_id
+          == kConnectedTransportPacketId) {
+        AddIntToMessage(
+            (EipUint16) (message_router_response->data_length + 4 + 2
+                + (2 * message_router_response->size_of_additional_status)),
+            &message);
 
 
-              htols(
-                  (EIP_UINT16) g_stCPFDataItem.stAddr_Item.Data.SequenceNumber,
-                  &pa_msg);
+        AddIntToMessage(
+            (EipUint16) g_common_packet_format_data_item.address_item.data
+                .sequence_number,
+            &message);
 
 
-              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 + message_router_response->data_length + 4 + 2
+            + (2 * message_router_response->size_of_additional_status));
+      } else {
+        AddIntToMessage(
+            (EipUint16) (message_router_response->data_length + 4
+                + (2 * message_router_response->size_of_additional_status)),
+            &message);
+        size += (4 + message_router_response->data_length + 4
+            + (2 * message_router_response->size_of_additional_status));
+      }
 
 
-          /* 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 message router response into linear memory */
+      *message = message_router_response->reply_service;
+      message++;
+      *message = message_router_response->reserved; /* reserved = 0 */
+      message++;
+      *message = message_router_response->general_status;
+      message++;
+      *message = message_router_response->size_of_additional_status;
+      message++;
+      for (i = 0; i < message_router_response->size_of_additional_status; i++)
+        AddIntToMessage(message_router_response->additional_status[i],
+                        &message);
 
 
-          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);
-        }
+      for (i = 0; i < message_router_response->data_length; i++) {
+        *message = (EipUint8) *(message_router_response->data + i);
+        message++;
+      }
+    } else { /* connected IO Message to send */
+      AddIntToMessage(common_packet_format_data_item->data_item.type_id,
+                      &message);
+      AddIntToMessage(common_packet_format_data_item->data_item.length,
+                      &message);
+      for (i = 0; i < common_packet_format_data_item->data_item.length; i++) {
+        *message = (EipUint8) *(common_packet_format_data_item->data_item.data
+            + i);
+        message++;
+      }
+      size += (common_packet_format_data_item->data_item.length + 4);
     }
     }
+  }
   /* process SockAddr Info Items */
   /* process SockAddr Info Items */
   /* make sure first the O->T and then T->O appears on the wire.
   /* make sure first the O->T and then T->O appears on the wire.
    * EtherNet/IP specification doesn't demand it, but there are EIP
    * EtherNet/IP specification doesn't demand it, but there are EIP
    * devices which depend on CPF items to appear in the order of their
    * devices which depend on CPF items to appear in the order of their
    * ID number */
    * ID number */
-  for (type = CIP_ITEM_ID_SOCKADDRINFO_O_TO_T; type <= CIP_ITEM_ID_SOCKADDRINFO_T_TO_O; type++)
-    {
-      for (j = 0; j < 2; j++)
-        {
-          if (pa_CPFDataItem->AddrInfo[j].TypeID == type)
-            {
-              htols(pa_CPFDataItem->AddrInfo[j].TypeID, &pa_msg);
-              htols(pa_CPFDataItem->AddrInfo[j].Length, &pa_msg);
+  for (type = kSocketAddressInfoOriginatorToTargetId;
+      type <= kSocketAddressInfoTargetToOriginatorId; type++) {
+    for (j = 0; j < 2; j++) {
+      if (common_packet_format_data_item->address_info_item[j].type_id
+          == type) {
+        AddIntToMessage(
+            common_packet_format_data_item->address_info_item[j].type_id,
+            &message);
+        AddIntToMessage(
+            common_packet_format_data_item->address_info_item[j].length,
+            &message);
 
 
-              encapsulateIPAdressCPF(pa_CPFDataItem->AddrInfo[j].nsin_port,
-                  pa_CPFDataItem->AddrInfo[j].nsin_addr, pa_msg);
-              pa_msg += 8;
+        EncapsulateIpAddressCommonPaketFormat(
+            common_packet_format_data_item->address_info_item[j].nsin_port,
+            common_packet_format_data_item->address_info_item[j].nsin_addr,
+            message);
+        message += 8;
 
 
-              memset(pa_msg, 0, 8);
-              pa_msg += 8;
-              size += 20;
-              break;
-           }
-        }
+        memset(message, 0, 8);
+        message += 8;
+        size += 20;
+        break;
+      }
     }
     }
+  }
   return size;
   return size;
 }
 }
 
 

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

@@ -3,8 +3,8 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef _CPF_H
-#define _CPF_H
+#ifndef OPENER_CPF_H_
+#define OPENER_CPF_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
@@ -19,58 +19,55 @@
  <data> := <the number of bytes specified by Length>
  <data> := <the number of bytes specified by Length>
  */
  */
 
 
-/* Definition of Item ID numbers used for address and data items in CPF structures */
-#define CIP_ITEM_ID_NULL                                0x0000  /**< Null Address Item */
-#define CIP_ITEM_ID_LISTIDENTITY_RESPONSE               0x000C
-#define CIP_ITEM_ID_CONNECTIONBASED                     0x00A1  /**< Connected Address Item */
-#define CIP_ITEM_ID_CONNECTIONTRANSPORTPACKET           0x00B1  /**< Connected Data Item */
-#define CIP_ITEM_ID_UNCONNECTEDMESSAGE                  0x00B2  /**< Unconnected Data Item */
-#define CIP_ITEM_ID_LISTSERVICE_RESPONSE                0x0100
-#define CIP_ITEM_ID_SOCKADDRINFO_O_TO_T                 0x8000  /**< Sockaddr info item originator to target (data) */
-#define CIP_ITEM_ID_SOCKADDRINFO_T_TO_O                 0x8001  /**< Sockaddr info item target to originator (data) */
-#define CIP_ITEM_ID_SEQUENCEDADDRESS                    0x8002  /**< Sequenced Address item */
+/** @brief Definition of Item ID numbers used for address and data items in CPF structures */
+typedef enum {
+  kNullAddressId = 0x0000, /**< Type: Address; Indicates that encapsulation routing is not needed. */
+  kListIdentityResponse = 0x000C,
+  kConnectionBasedId = 0x00A1, /**< Type: Address; Connection-based, used for connected messages */
+  kConnectedTransportPacketId = 0x00B1, /**< Type: Data; Connected Transport packet */
+  kUnconnectedMessageId = 0x00B2, /**< Type: Data; Unconnected message */
+  kListServiceResponseId = 0x0100,
+  kSocketAddressInfoOriginatorToTargetId = 0x8000, /**< Type: Data; Sockaddr info item originator to target */
+  kSocketAddressInfoTargetToOriginatorId = 0x8001, /**< Type: Data; Sockaddr info item target to originator */
+  kSequencedAddressItemId = 0x8002 /**< Sequenced Address item */
+} CipItemIds;
 
 
-typedef struct
-{
-  EIP_UINT32 ConnectionIdentifier;
-  EIP_UINT32 SequenceNumber;
-} S_Address_Data;
+typedef struct {
+  EipUint32 connection_identifier;
+  EipUint32 sequence_number;
+} AddressData;
 
 
-typedef struct
-{
-  EIP_UINT16 TypeID;
-  EIP_UINT16 Length;
-  S_Address_Data Data;
-} S_Address_Item;
+typedef struct {
+  EipUint16 type_id;
+  EipUint16 length;
+  AddressData data;
+} AddressItem;
 
 
-typedef struct
-{
-  EIP_UINT16 TypeID;
-  EIP_UINT16 Length;
-  EIP_UINT8 *Data;
+typedef struct {
+  EipUint16 type_id;
+  EipUint16 length;
+  EipUint8 *data;
 } S_Data_Item;
 } S_Data_Item;
 
 
-typedef struct
-{
-  EIP_UINT16 TypeID;
-  EIP_UINT16 Length;
-  EIP_INT16 nsin_family;
-  EIP_UINT16 nsin_port;
-  EIP_UINT32 nsin_addr;
-  EIP_UINT8 nasin_zero[8];
-} S_SockAddrInfo_Item;
+typedef struct {
+  EipUint16 type_id;
+  EipUint16 length;
+  EipInt16 nsin_family;
+  EipUint16 nsin_port;
+  EipUint32 nsin_addr;
+  EipUint8 nasin_zero[8];
+} SocketAddrressInfoItem;
 
 
 /* this one case of a CPF packet is supported:*/
 /* this one case of a CPF packet is supported:*/
 
 
-typedef struct
-{
-  EIP_UINT16 ItemCount;
-  S_Address_Item stAddr_Item;
-  S_Data_Item stDataI_Item;
-  S_SockAddrInfo_Item AddrInfo[2];
-} S_CIP_CPF_Data;
+typedef struct {
+  EipUint16 item_count;
+  AddressItem address_item;
+  S_Data_Item data_item;
+  SocketAddrressInfoItem address_info_item[2];
+} CipCommonPacketFormatData;
 
 
-/*! \ingroup ENCAP
+/** @ingroup ENCAP
  * Parse the CPF data from a received unconnected explicit message and
  * Parse the CPF data from a received unconnected explicit message and
  * hand the data on to the message router 
  * hand the data on to the message router 
  *
  *
@@ -78,10 +75,10 @@ typedef struct
  * @param  pa_acReplyBuf reply buffer
  * @param  pa_acReplyBuf reply buffer
  * @return number of bytes to be sent back. < 0 if nothing should be sent
  * @return number of bytes to be sent back. < 0 if nothing should be sent
  */
  */
-int notifyCPF(struct S_Encapsulation_Data * pa_stReceiveData,
-    EIP_UINT8 * pa_acReplyBuf);
+int NotifyCommonPacketFormat(EncapsulationData *received_data,
+                             EipUint8 *reply_buffer);
 
 
-/*! \ingroup ENCAP
+/** @ingroup ENCAP
  * Parse the CPF data from a received connected explicit message, check
  * Parse the CPF data from a received connected explicit message, check
  * the connection status, update any timers, and hand the data on to 
  * the connection status, update any timers, and hand the data on to 
  * the message router 
  * the message router 
@@ -90,8 +87,8 @@ int notifyCPF(struct S_Encapsulation_Data * pa_stReceiveData,
  * @param  pa_acReplyBuf reply buffer
  * @param  pa_acReplyBuf reply buffer
  * @return number of bytes to be sent back. < 0 if nothing should be sent
  * @return number of bytes to be sent back. < 0 if nothing should be sent
  */
  */
-int notifyConnectedCPF(struct S_Encapsulation_Data * pa_stReceiveData,
-    EIP_UINT8 * pa_acReplyBuf);
+int NotifyConnectedCommonPacketFormat(EncapsulationData *received_data,
+                                      EipUint8 *reply_buffer);
 
 
 /*! \ingroup ENCAP
 /*! \ingroup ENCAP
  *  Create CPF structure out of the received data.
  *  Create CPF structure out of the received data.
@@ -102,8 +99,9 @@ int notifyConnectedCPF(struct S_Encapsulation_Data * pa_stReceiveData,
  * 	       EIP_OK .. success
  * 	       EIP_OK .. success
  * 	       EIP_ERROR .. error
  * 	       EIP_ERROR .. error
  */
  */
-EIP_STATUS createCPFstructure(EIP_UINT8 * pa_Data, int pa_DataLength,
-    S_CIP_CPF_Data * pa_CPF_data);
+EipStatus CreateCommonPacketFormatStructure(
+    EipUint8 *data, int data_length,
+    CipCommonPacketFormatData *common_packet_format_data);
 
 
 /*! \ingroup ENCAP
 /*! \ingroup ENCAP
  * Copy data from MRResponse struct and CPFDataItem into linear memory in pa_msg for transmission over in encapsulation.
  * Copy data from MRResponse struct and CPFDataItem into linear memory in pa_msg for transmission over in encapsulation.
@@ -113,14 +111,16 @@ EIP_STATUS createCPFstructure(EIP_UINT8 * pa_Data, int pa_DataLength,
  * @return length of reply in pa_msg in bytes
  * @return length of reply in pa_msg in bytes
  * 	   EIP_ERROR .. error
  * 	   EIP_ERROR .. error
  */
  */
-int assembleLinearMsg(S_CIP_MR_Response * pa_MRResponse,
-    S_CIP_CPF_Data * pa_CPFDataItem, EIP_UINT8 * pa_msg);
+int AssembleLinearMessage(
+    CipMessageRouterResponse *message_router_response,
+    CipCommonPacketFormatData *common_packet_format_data_item,
+    EipUint8 *message);
 
 
 /*!\ingroup ENCAP 
 /*!\ingroup ENCAP 
- * \brief Data storage for the any cpf data
- * Currently we are single threaded and need only one cpf at the time.
- * For future extensions towards multithreading maybe more cpf data items may be necessary
+ * \brief Data storage for the any CPF data
+ * Currently we are single threaded and need only one CPF at the time.
+ * For future extensions towards multithreading maybe more CPF data items may be necessary
  */
  */
-extern S_CIP_CPF_Data g_stCPFDataItem;
+extern CipCommonPacketFormatData g_common_packet_format_data_item;
 
 
-#endif
+#endif /* OPENER_CPF_H_ */

+ 475 - 560
source/src/enet_encap/encap.c

@@ -15,727 +15,642 @@
 #include "cipidentity.h"
 #include "cipidentity.h"
 
 
 /*Identity data from cipidentity.c*/
 /*Identity data from cipidentity.c*/
-extern EIP_UINT16 VendorID;
-extern EIP_UINT16 DeviceType;
-extern EIP_UINT16 ProductCode;
-extern S_CIP_Revision Revison;
-extern EIP_UINT16 ID_Status;
-extern EIP_UINT32 SerialNumber;
-extern S_CIP_Short_String ProductName;
+extern EipUint16 vendor_id_;
+extern EipUint16 device_type_;
+extern EipUint16 product_code_;
+extern CipRevision revision_;
+extern EipUint16 status_;
+extern EipUint32 serial_number_;
+extern CipShortString product_name_;
 
 
 /*ip address data taken from TCPIPInterfaceObject*/
 /*ip address data taken from TCPIPInterfaceObject*/
-extern S_CIP_TCPIPNetworkInterfaceConfiguration Interface_Configuration;
+extern CipTcpIpNetworkInterfaceConfiguration interface_configuration_;
 
 
 /*** defines ***/
 /*** defines ***/
 
 
 #define ITEM_ID_LISTIDENTITY 0x000C
 #define ITEM_ID_LISTIDENTITY 0x000C
 
 
-#define SUPPORTED_PROTOCOL_VERSION 1
+const int kSupportedProtocolVersion = 1;
 
 
-#define SUPPORTED_OPTIONS_MASK  0x00  /*Mask of which options are supported as of the current CIP specs no other option value as 0 should be supported.*/
+const int kEncapsulationHeaderOptionsFlag = 0x00; /**< Mask of which options are supported as of the current CIP specs no other option value as 0 should be supported.*/
 
 
-#define ENCAPSULATION_HEADER_SESSION_HANDLE_POS 4   /*the position of the session handle within the encapsulation header*/
+const int kEncapsulationHeaderSessionHandlePosition = 4; /**< the position of the session handle within the encapsulation header*/
 
 
-#define INVALID_SESSION -1
+const int kInvalidSession = -1;
 
 
-#define SENDER_CONTEXT_SIZE 8                   /*size of sender context in encapsulation header*/
+const int kSenderContextSize = 8; /**< size of sender context in encapsulation header*/
 
 
 /* definition of known encapsulation commands */
 /* definition of known encapsulation commands */
-#define COMMAND_NOP                     0x0000
-#define COMMAND_LISTSERVICES            0x0004
-#define COMMAND_LISTIDENTITY            0x0063
-#define COMMAND_LISTINTERFACES          0x0064
-#define COMMAND_REGISTERSESSION         0x0065
-#define COMMAND_UNREGISTERSESSION       0x0066
-#define COMMAND_SENDRRDATA              0x006F
-#define COMMAND_SENDUNITDATA            0x0070
+typedef enum {
+  kEncapsulationCommandNoOperation = 0x0000,
+  kEncapsulationCommandListServices = 0x0004,
+  kEncapsulationCommandListIdentity = 0x0063,
+  kEncapsulationCommandListInterfaces = 0x0064,
+  kEncapsulationCommandRegisterSession = 0x0065,
+  kEncapsulationCommandUnregisterSession = 0x0066,
+  kEncapsulationCommandSendRequestReplyData = 0x006F,
+  kEncapsulationCommandSendUnitData = 0x0070
+} EncapsulationCommand;
 
 
 /* definition of capability flags */
 /* definition of capability flags */
-#define SUPPORT_CIP_TCP                 0x0020
-#define SUPPORT_CIP_UDP_CLASS_0_OR_1    0x0100
+typedef enum {
+  kCapabilityFlagsCipTcp = 0x0020,
+  kCapabilityFlagsCipUdpClass0or1 = 0x0100
+} CapabilityFlags;
 
 
 #define ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES 2 /*According to EIP spec at least 2 delayed message requests should be supported */
 #define ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES 2 /*According to EIP spec at least 2 delayed message requests should be supported */
 
 
-#define ENCAP_MAX_DELAYED_ENCAP_MESSAGE_SIZE  (ENCAPSULATION_HEADER_LENGTH + 39 + sizeof(OPENER_DEVICE_NAME)) /* currently we only have the size of an encapsulation message */
+#define ENCAP_MAX_DELAYED_ENCAP_MESSAGE_SIZE (ENCAPSULATION_HEADER_LENGTH + 39 + sizeof(OPENER_DEVICE_NAME)) /* currently we only have the size of an encapsulation message */
 
 
 /* Encapsulation layer data  */
 /* Encapsulation layer data  */
 
 
-struct SDelayedEncapsulationMessage
-{
-  EIP_INT32 m_unTimeOut;
-  int m_nSocket;
+typedef struct delayed_encapsulation_message {
+  EipInt32 time_out;
+  int socket;
   struct sockaddr_in m_stSendToAddr;
   struct sockaddr_in m_stSendToAddr;
-  EIP_BYTE m_anMsg[ENCAP_MAX_DELAYED_ENCAP_MESSAGE_SIZE];
-  unsigned int m_unMessageSize;
-};
+  EipByte message[ENCAP_MAX_DELAYED_ENCAP_MESSAGE_SIZE];
+  unsigned int message_size;
+} DelayedEncapsulationMessage;
 
 
-struct S_Encapsulation_Interface_Information g_stInterfaceInformation;
+EncapsulationInterfaceInformation g_interface_information;
 
 
-int anRegisteredSessions[OPENER_NUMBER_OF_SUPPORTED_SESSIONS];
+int g_registered_sessions[OPENER_NUMBER_OF_SUPPORTED_SESSIONS];
 
 
-struct SDelayedEncapsulationMessage g_stDelayedEncapsulationMessages[ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES];
+DelayedEncapsulationMessage g_delayed_encapsulation_messages[ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES];
 
 
 /*** private functions ***/
 /*** private functions ***/
-void
-handleReceivedListServicesCmd(struct S_Encapsulation_Data *pa_stReceiveData);
-void
-handleReceivedListInterfacesCmd(struct S_Encapsulation_Data *pa_stReceiveData);
-
-void
-handleReceivedListIdentityCmdTCP(struct S_Encapsulation_Data *pa_stReceiveData);
-
-void
-handleReceivedListIdentityCmdUDP(int pa_nSocket,
-    struct sockaddr_in *pa_pstFromAddr,
-    struct S_Encapsulation_Data *pa_stReceiveData);
-
-void
-handleReceivedRegisterSessionCmd(int pa_nSockfd,
-    struct S_Encapsulation_Data *pa_stReceiveData);
-EIP_STATUS
-handleReceivedUnregisterSessionCmd(
-    struct S_Encapsulation_Data *pa_stReceiveData);
-EIP_STATUS
-handleReceivedSendUnitDataCmd(struct S_Encapsulation_Data *pa_stReceiveData);
-EIP_STATUS
-handleReceivedSendRRDataCmd(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(struct S_Encapsulation_Data *pa_S_ReceiveData);
-int
-encapsulate_data(struct S_Encapsulation_Data *pa_S_SendData);
-
-void
-determineDelayTime(EIP_BYTE *pa_acBufferStart,
-    struct SDelayedEncapsulationMessage *pa_pstDelayedMessageBuffer);
-
-int
-encapsulateListIdentyResponseMessage(EIP_BYTE *pa_pacCommBuf);
-
-/*   void encapInit(void)
- *   initialize session list and interface information.
- */
+void HandleReceivedListServicesCommand(EncapsulationData *receive_data);
+
+void HandleReceivedListInterfacesCommand(EncapsulationData *receive_data);
+
+void HandleReceivedListIdentityCommandTcp(EncapsulationData *receive_data);
+
+void HandleReceivedListIdentityCommandUdp(int socket,
+                                          struct sockaddr_in *from_address,
+                                          EncapsulationData *receive_data);
+
+void HandleReceivedRegisterSessionCommand(int socket,
+                                          EncapsulationData *receive_data);
+
+EipStatus HandleReceivedUnregisterSessionCommand(
+    EncapsulationData *receive_data);
+
+EipStatus HandleReceivedSendUnitDataCommand(EncapsulationData *receive_data);
+
+EipStatus HandleReceivedSendRequestResponseDataCommand(
+    EncapsulationData *receive_data);
+
+int GetFreeSessionIndex(void);
+
+EipInt16 CreateEncapsulationStructure(EipUint8 *receive_buffer,
+                                      int receive_buffer_length,
+                                      EncapsulationData *encapsulation_data);
+
+EipStatus CheckRegisteredSessions(EncapsulationData *receive_data);
 
 
-void
-encapInit(void)
-{
+int EncapsulateData(EncapsulationData *send_data);
+
+void DetermineDelayTime(EipByte *buffer_start,
+                        DelayedEncapsulationMessage *delayed_message_buffer);
+
+int EncapsulateListIdentyResponseMessage(EipByte *communication_buffer);
+
+/*   @brief Initializes session list and interface information. */
+void EncapsulationInit(void) {
   unsigned int i;
   unsigned int i;
 
 
-  determineEndianess();
+  DetermineEndianess();
 
 
   /*initialize random numbers for random delayed response message generation
   /*initialize random numbers for random delayed response message generation
    * we use the ip address as seed as suggested in the spec */
    * we use the ip address as seed as suggested in the spec */
-  srand(Interface_Configuration.IPAddress);
+  srand(interface_configuration_.ip_address);
 
 
   /* initialize Sessions to invalid == free session */
   /* initialize Sessions to invalid == free session */
-  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++)
-    {
-      anRegisteredSessions[i] = EIP_INVALID_SOCKET;
-    }
+  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++) {
+    g_registered_sessions[i] = kEipInvalidSocket;
+  }
 
 
-  for (i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++)
-    {
-      g_stDelayedEncapsulationMessages[i].m_nSocket = -1;
-    }
+  for (i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
+    g_delayed_encapsulation_messages[i].socket = -1;
+  }
 
 
   /*TODO make the interface information configurable*/
   /*TODO make the interface information configurable*/
   /* initialize interface information */
   /* 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");
+  g_interface_information.type_code = kListServiceResponseId;
+  g_interface_information.length = sizeof(g_interface_information);
+  g_interface_information.encapsulation_protocol_version = 1;
+  g_interface_information.capability_flags = kCapabilityFlagsCipTcp
+      | kCapabilityFlagsCipUdpClass0or1;
+  strcpy((char *) g_interface_information.name_of_service, "Communications");
 }
 }
 
 
-int
-handleReceivedExplictTCPData(int pa_socket, EIP_UINT8 * pa_buf,
-    unsigned int pa_length, int *pa_nRemainingBytes)
-{
-  int nRetVal = 0;
-  struct S_Encapsulation_Data sEncapData;
+int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
+                                 unsigned int length, int *remaining_bytes) {
+  EipStatus return_value = kEipStatusOk;
+  EncapsulationData encapsulation_data;
   /* eat the encapsulation header*/
   /* eat the encapsulation header*/
   /* the structure contains a pointer to the encapsulated data*/
   /* the structure contains a pointer to the encapsulated data*/
   /* returns how many bytes are left after the encapsulated data*/
   /* returns how many bytes are left after the encapsulated data*/
-  *pa_nRemainingBytes = createEncapsulationStructure(pa_buf, pa_length,
-      &sEncapData);
+  *remaining_bytes = CreateEncapsulationStructure(buffer, length,
+                                                  &encapsulation_data);
 
 
-  if (SUPPORTED_OPTIONS_MASK == sEncapData.nOptions) /*TODO generate appropriate error response*/
+  if (kEncapsulationHeaderOptionsFlag == encapsulation_data.options) /*TODO generate appropriate error response*/
+  {
+    if (*remaining_bytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
     {
     {
-      if (*pa_nRemainingBytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
-        {
-          /* full package or more received */
-          sEncapData.nStatus = OPENER_ENCAP_STATUS_SUCCESS;
-          nRetVal = 1;
-          /* most of these functions need a reply to be send */
-          switch (sEncapData.nCommand_code)
-            {
-          case (COMMAND_NOP):
-            /* NOP needs no reply and does nothing */
-            nRetVal = 0;
-            break;
-
-          case (COMMAND_LISTSERVICES):
-            handleReceivedListServicesCmd(&sEncapData);
-            break;
-
-          case (COMMAND_LISTIDENTITY):
-            handleReceivedListIdentityCmdTCP(&sEncapData);
-            break;
-
-          case (COMMAND_LISTINTERFACES):
-            handleReceivedListInterfacesCmd(&sEncapData);
-            break;
-
-          case (COMMAND_REGISTERSESSION):
-            handleReceivedRegisterSessionCmd(pa_socket, &sEncapData);
-            break;
-
-          case (COMMAND_UNREGISTERSESSION):
-            nRetVal = handleReceivedUnregisterSessionCmd(&sEncapData);
-            break;
-
-          case (COMMAND_SENDRRDATA):
-            nRetVal = handleReceivedSendRRDataCmd(&sEncapData);
-            break;
-
-          case (COMMAND_SENDUNITDATA):
-            nRetVal = handleReceivedSendUnitDataCmd(&sEncapData);
-            break;
-
-          default:
-            sEncapData.nStatus = OPENER_ENCAP_STATUS_INVALID_COMMAND;
-            sEncapData.nData_length = 0;
-            break;
-            }
-          /* if nRetVal is greater then 0 data has to be sent */
-          if (0 < nRetVal)
-            {
-              nRetVal = encapsulate_data(&sEncapData);
-            }
-        }
+      /* full package or more received */
+      encapsulation_data.status = kEncapsulationProtocolSuccess;
+      return_value = kEipStatusOkSend;
+      /* most of these functions need a reply to be send */
+      switch (encapsulation_data.command_code) {
+        case (kEncapsulationCommandNoOperation):
+          /* NOP needs no reply and does nothing */
+          return_value = kEipStatusOk;
+          break;
+
+        case (kEncapsulationCommandListServices):
+          HandleReceivedListServicesCommand(&encapsulation_data);
+          break;
+
+        case (kEncapsulationCommandListIdentity):
+          HandleReceivedListIdentityCommandTcp(&encapsulation_data);
+          break;
+
+        case (kEncapsulationCommandListInterfaces):
+          HandleReceivedListInterfacesCommand(&encapsulation_data);
+          break;
+
+        case (kEncapsulationCommandRegisterSession):
+          HandleReceivedRegisterSessionCommand(socket, &encapsulation_data);
+          break;
+
+        case (kEncapsulationCommandUnregisterSession):
+          return_value = HandleReceivedUnregisterSessionCommand(
+              &encapsulation_data);
+          break;
+
+        case (kEncapsulationCommandSendRequestReplyData):
+          return_value = HandleReceivedSendRequestResponseDataCommand(
+              &encapsulation_data);
+          break;
+
+        case (kEncapsulationCommandSendUnitData):
+          return_value = HandleReceivedSendUnitDataCommand(&encapsulation_data);
+          break;
+
+        default:
+          encapsulation_data.status = kEncapsulationProtocolInvalidCommand;
+          encapsulation_data.data_length = 0;
+          break;
+      }
+      /* if nRetVal is greater then 0 data has to be sent */
+      if (kEipStatusOk < return_value) {
+        return_value = EncapsulateData(&encapsulation_data);
+      }
     }
     }
+  }
 
 
-  return nRetVal;
+  return return_value;
 }
 }
 
 
-int
-handleReceivedExplictUDPData(int pa_socket, struct sockaddr_in *pa_pstFromAddr,
-    EIP_UINT8* pa_buf, unsigned int pa_length, int *pa_nRemainingBytes)
-{
-  int nRetVal = 0;
-  struct S_Encapsulation_Data sEncapData;
+int HandleReceivedExplictUdpData(int socket, struct sockaddr_in *from_address,
+                                 EipUint8 *buffer, unsigned int buffer_length,
+                                 int *number_of_remaining_bytes) {
+  EipStatus nRetVal = kEipStatusOk;
+  EncapsulationData encapsulation_data;
   /* eat the encapsulation header*/
   /* eat the encapsulation header*/
   /* the structure contains a pointer to the encapsulated data*/
   /* the structure contains a pointer to the encapsulated data*/
   /* returns how many bytes are left after the encapsulated data*/
   /* returns how many bytes are left after the encapsulated data*/
-  *pa_nRemainingBytes = createEncapsulationStructure(pa_buf, pa_length,
-      &sEncapData);
+  *number_of_remaining_bytes = CreateEncapsulationStructure(
+      buffer, buffer_length, &encapsulation_data);
 
 
-  if (SUPPORTED_OPTIONS_MASK == sEncapData.nOptions) /*TODO generate appropriate error response*/
+  if (kEncapsulationHeaderOptionsFlag == encapsulation_data.options) /*TODO generate appropriate error response*/
+  {
+    if (*number_of_remaining_bytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
     {
     {
-      if (*pa_nRemainingBytes >= 0) /* check if the message is corrupt: header size + claimed payload size > than what we actually received*/
-        {
-          /* full package or more received */
-          sEncapData.nStatus = OPENER_ENCAP_STATUS_SUCCESS;
-          nRetVal = 1;
-          /* most of these functions need a reply to be send */
-          switch (sEncapData.nCommand_code)
-            {
-          case (COMMAND_LISTSERVICES):
-            handleReceivedListServicesCmd(&sEncapData);
-            break;
-
-          case (COMMAND_LISTIDENTITY):
-            handleReceivedListIdentityCmdUDP(pa_socket, pa_pstFromAddr,
-                &sEncapData);
-            nRetVal = EIP_OK; /* as the response has to be delayed do not send it now */
-            break;
-
-          case (COMMAND_LISTINTERFACES):
-            handleReceivedListInterfacesCmd(&sEncapData);
-            break;
-
-            /* The following commands are not to be sent via UDP */
-          case (COMMAND_NOP):
-          case (COMMAND_REGISTERSESSION):
-          case (COMMAND_UNREGISTERSESSION):
-          case (COMMAND_SENDRRDATA):
-          case (COMMAND_SENDUNITDATA):
-          default:
-            sEncapData.nStatus = OPENER_ENCAP_STATUS_INVALID_COMMAND;
-            sEncapData.nData_length = 0;
-            break;
-            }
-          /* if nRetVal is greater then 0 data has to be sent */
-          if (0 < nRetVal)
-            {
-              nRetVal = encapsulate_data(&sEncapData);
-            }
-        }
-    }
+      /* full package or more received */
+      encapsulation_data.status = kEncapsulationProtocolSuccess;
+      nRetVal = kEipStatusOkSend;
+      /* most of these functions need a reply to be send */
+      switch (encapsulation_data.command_code) {
+        case (kEncapsulationCommandListServices):
+          HandleReceivedListServicesCommand(&encapsulation_data);
+          break;
+
+        case (kEncapsulationCommandListIdentity):
+          HandleReceivedListIdentityCommandUdp(socket, from_address,
+                                               &encapsulation_data);
+          nRetVal = kEipStatusOk; /* as the response has to be delayed do not send it now */
+          break;
 
 
+        case (kEncapsulationCommandListInterfaces):
+          HandleReceivedListInterfacesCommand(&encapsulation_data);
+          break;
+
+          /* The following commands are not to be sent via UDP */
+        case (kEncapsulationCommandNoOperation):
+        case (kEncapsulationCommandRegisterSession):
+        case (kEncapsulationCommandUnregisterSession):
+        case (kEncapsulationCommandSendRequestReplyData):
+        case (kEncapsulationCommandSendUnitData):
+        default:
+          encapsulation_data.status = kEncapsulationProtocolInvalidCommand;
+          encapsulation_data.data_length = 0;
+          break;
+      }
+      /* if nRetVal is greater then 0 data has to be sent */
+      if (0 < nRetVal) {
+        nRetVal = EncapsulateData(&encapsulation_data);
+      }
+    }
+  }
   return nRetVal;
   return nRetVal;
 }
 }
 
 
-int
-encapsulate_data(struct S_Encapsulation_Data *pa_stSendData)
-{
-  EIP_UINT8 *acCommBuf = &(pa_stSendData->m_acCommBufferStart[2]);
+int EncapsulateData(EncapsulationData *send_data) {
+  EipUint8 *communcation_buffer = &(send_data->communication_buffer_start[2]);
   /*htols(pa_stSendData->nCommand_code, &pa_stSendData->pEncapsulation_Data);*/
   /*htols(pa_stSendData->nCommand_code, &pa_stSendData->pEncapsulation_Data);*/
-  htols(pa_stSendData->nData_length, &acCommBuf);
+  AddIntToMessage(send_data->data_length, &communcation_buffer);
   /*the CommBuf should already contain the correct session handle*/
   /*the CommBuf should already contain the correct session handle*/
   /*htoll(pa_stSendData->nSession_handle, &pa_stSendData->pEncapsulation_Data); */
   /*htoll(pa_stSendData->nSession_handle, &pa_stSendData->pEncapsulation_Data); */
-  acCommBuf += 4;
-  htoll(pa_stSendData->nStatus, &acCommBuf);
+  communcation_buffer += 4;
+  AddDintToMessage(send_data->status, &communcation_buffer);
   /*the CommBuf should already contain the correct sender context*/
   /*the CommBuf should already contain the correct sender context*/
   /*memcpy(pa_stSendData->pEncapsulation_Data, pa_stSendData->anSender_context, SENDER_CONTEXT_SIZE);*/
   /*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*/
   /*pa_stSendData->pEncapsulation_Data += SENDER_CONTEXT_SIZE + 2;*//* the plus 2 is for the options value*/
   /*the CommBuf should already contain the correct  options value*/
   /*the CommBuf should already contain the correct  options value*/
   /*htols((EIP_UINT16)pa_stSendData->nOptions, &pa_stSendData->pEncapsulation_Data);*/
   /*htols((EIP_UINT16)pa_stSendData->nOptions, &pa_stSendData->pEncapsulation_Data);*/
 
 
-  return ENCAPSULATION_HEADER_LENGTH + pa_stSendData->nData_length;
+  return ENCAPSULATION_HEADER_LENGTH + send_data->data_length;
 }
 }
 
 
-/*   INT8 ListServices(struct S_Encapsulation_Data *pa_S_ReceiveData)
- *   generate reply with "Communications Services" + compatibility Flags.
- *      pa_S_ReceiveData pointer to structure with received data
+/** @brief generate reply with "Communications Services" + compatibility Flags.
+ *  @param receive_data pointer to structure with received data
  */
  */
-void
-handleReceivedListServicesCmd(struct S_Encapsulation_Data *pa_stReceiveData)
-{
-  EIP_UINT8 *pacCommBuf = pa_stReceiveData->m_acCurrentCommBufferPos;
+void HandleReceivedListServicesCommand(EncapsulationData *receive_data) {
+  EipUint8 *communication_buffer = receive_data
+      ->current_communication_buffer_position;
 
 
-  pa_stReceiveData->nData_length = g_stInterfaceInformation.Length + 2;
+  receive_data->data_length = g_interface_information.length + 2;
 
 
   /* copy Interface data to nmsg for sending */
   /* 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));
+  AddIntToMessage(1, &communication_buffer);
+  AddIntToMessage(g_interface_information.type_code, &communication_buffer);
+  AddIntToMessage((EipUint16) (g_interface_information.length - 4),
+                  &communication_buffer);
+  AddIntToMessage(g_interface_information.encapsulation_protocol_version,
+                  &communication_buffer);
+  AddIntToMessage(g_interface_information.capability_flags,
+                  &communication_buffer);
+  memcpy(communication_buffer, g_interface_information.name_of_service,
+         sizeof(g_interface_information.name_of_service));
 }
 }
 
 
-void
-handleReceivedListInterfacesCmd(struct S_Encapsulation_Data *pa_stReceiveData)
-{
-  EIP_UINT8 *pacCommBuf = pa_stReceiveData->m_acCurrentCommBufferPos;
-  pa_stReceiveData->nData_length = 2;
-  htols(0x0000, &pacCommBuf); /* copy Interface data to nmsg for sending */
+void HandleReceivedListInterfacesCommand(EncapsulationData *receive_data) {
+  EipUint8 *communication_buffer = receive_data
+      ->current_communication_buffer_position;
+  receive_data->data_length = 2;
+  AddIntToMessage(0x0000, &communication_buffer); /* copy Interface data to nmsg for sending */
 }
 }
 
 
-void
-handleReceivedListIdentityCmdTCP(struct S_Encapsulation_Data * pa_stReceiveData)
-{
-  pa_stReceiveData->nData_length = encapsulateListIdentyResponseMessage(
-      pa_stReceiveData->m_acCurrentCommBufferPos);
+void HandleReceivedListIdentityCommandTcp(EncapsulationData * receive_data) {
+  receive_data->data_length = EncapsulateListIdentyResponseMessage(
+      receive_data->current_communication_buffer_position);
 }
 }
 
 
-void
-handleReceivedListIdentityCmdUDP(int pa_nSocket,
-    struct sockaddr_in *pa_pstFromAddr,
-    struct S_Encapsulation_Data *pa_stReceiveData)
-{  
-  struct SDelayedEncapsulationMessage *pstDelayedMessageBuffer = NULL;
+void HandleReceivedListIdentityCommandUdp(int socket,
+                                          struct sockaddr_in *from_address,
+                                          EncapsulationData *receive_data) {
+  DelayedEncapsulationMessage *delayed_message_buffer = NULL;
   unsigned int i;
   unsigned int i;
-  EIP_UINT8 *pacCommBuf;
+  EipUint8 *communication_buffer;
 
 
-  for (i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++)
-    {
-      if (-1 == g_stDelayedEncapsulationMessages[i].m_nSocket)
-        {
-          pstDelayedMessageBuffer = &(g_stDelayedEncapsulationMessages[i]);
-          break;
-        }
+  for (i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
+    if (kEipInvalidSocket == g_delayed_encapsulation_messages[i].socket) {
+      delayed_message_buffer = &(g_delayed_encapsulation_messages[i]);
+      break;
     }
     }
+  }
 
 
-  if (NULL != pstDelayedMessageBuffer)
-    {
-      pstDelayedMessageBuffer->m_nSocket = pa_nSocket;
-      memcpy((&pstDelayedMessageBuffer->m_stSendToAddr), pa_pstFromAddr,
-          sizeof(struct sockaddr_in));
+  if (NULL != delayed_message_buffer) {
+    delayed_message_buffer->socket = socket;
+    memcpy((&delayed_message_buffer->m_stSendToAddr), from_address,
+           sizeof(struct sockaddr_in));
 
 
-      determineDelayTime(pa_stReceiveData->m_acCommBufferStart,
-          pstDelayedMessageBuffer);
+    DetermineDelayTime(receive_data->communication_buffer_start,
+                       delayed_message_buffer);
 
 
-      memcpy(&(pstDelayedMessageBuffer->m_anMsg[0]),
-          pa_stReceiveData->m_acCommBufferStart, ENCAPSULATION_HEADER_LENGTH);
+    memcpy(&(delayed_message_buffer->message[0]),
+           receive_data->communication_buffer_start,
+           ENCAPSULATION_HEADER_LENGTH);
 
 
-      pstDelayedMessageBuffer->m_unMessageSize =
-          encapsulateListIdentyResponseMessage(
-              &(pstDelayedMessageBuffer->m_anMsg[ENCAPSULATION_HEADER_LENGTH]));
+    delayed_message_buffer->message_size = EncapsulateListIdentyResponseMessage(
+        &(delayed_message_buffer->message[ENCAPSULATION_HEADER_LENGTH]));
 
 
-      pacCommBuf = pstDelayedMessageBuffer->m_anMsg + 2;
-      htols(pstDelayedMessageBuffer->m_unMessageSize, &pacCommBuf);
-      pstDelayedMessageBuffer->m_unMessageSize += ENCAPSULATION_HEADER_LENGTH;
-    }
+    communication_buffer = delayed_message_buffer->message + 2;
+    AddIntToMessage(delayed_message_buffer->message_size,
+                    &communication_buffer);
+    delayed_message_buffer->message_size += ENCAPSULATION_HEADER_LENGTH;
+  }
 }
 }
 
 
-int
-encapsulateListIdentyResponseMessage(EIP_BYTE *pa_pacCommBuf)
-{
-  EIP_UINT8 *pacCommBufRunner = pa_pacCommBuf;
-  EIP_BYTE *acIdLenBuf;
+int EncapsulateListIdentyResponseMessage(EipByte *communication_buffer) {
+  EipUint8 *communication_buffer_runner = communication_buffer;
+  EipByte *id_length_buffer;
 
 
-  htols(1, &pacCommBufRunner); /* one item */
-  htols(ITEM_ID_LISTIDENTITY, &pacCommBufRunner);
+  AddIntToMessage(1, &communication_buffer_runner); /* one item */
+  AddIntToMessage(ITEM_ID_LISTIDENTITY, &communication_buffer_runner);
 
 
-  acIdLenBuf = pacCommBufRunner;
-  pacCommBufRunner += 2; /*at this place the real length will be inserted below*/
+  id_length_buffer = communication_buffer_runner;
+  communication_buffer_runner += 2; /*at this place the real length will be inserted below*/
 
 
-  htols(SUPPORTED_PROTOCOL_VERSION, &pacCommBufRunner);
+  AddIntToMessage(kSupportedProtocolVersion, &communication_buffer_runner);
 
 
-  encapsulateIPAdress(OPENER_ETHERNET_PORT, Interface_Configuration.IPAddress,
-      pacCommBufRunner);
-  pacCommBufRunner += 8;
+  EncapsulateIpAddress(OPENER_ETHERNET_PORT,
+                       interface_configuration_.ip_address,
+                       communication_buffer_runner);
+  communication_buffer_runner += 8;
 
 
-  memset(pacCommBufRunner, 0, 8);
-  pacCommBufRunner += 8;
+  memset(communication_buffer_runner, 0, 8);
+  communication_buffer_runner += 8;
 
 
-  htols(VendorID, &pacCommBufRunner);
-  htols(DeviceType, &pacCommBufRunner);
-  htols(ProductCode, &pacCommBufRunner);
-  *(pacCommBufRunner)++ = Revison.MajorRevision;
-  *(pacCommBufRunner)++ = Revison.MinorRevision;
-  htols(ID_Status, &pacCommBufRunner);
-  htoll(SerialNumber, &pacCommBufRunner);
-  *pacCommBufRunner++ = (unsigned char) ProductName.Length;
-  memcpy(pacCommBufRunner, ProductName.String, ProductName.Length);
-  pacCommBufRunner += ProductName.Length;
-  *pacCommBufRunner++ = 0xFF;
+  AddIntToMessage(vendor_id_, &communication_buffer_runner);
+  AddIntToMessage(device_type_, &communication_buffer_runner);
+  AddIntToMessage(product_code_, &communication_buffer_runner);
+  *(communication_buffer_runner)++ = revision_.major_revision;
+  *(communication_buffer_runner)++ = revision_.minor_revision;
+  AddIntToMessage(status_, &communication_buffer_runner);
+  AddDintToMessage(serial_number_, &communication_buffer_runner);
+  *communication_buffer_runner++ = (unsigned char) product_name_.length;
+  memcpy(communication_buffer_runner, product_name_.string,
+         product_name_.length);
+  communication_buffer_runner += product_name_.length;
+  *communication_buffer_runner++ = 0xFF;
 
 
-  htols(pacCommBufRunner - acIdLenBuf - 2, &acIdLenBuf); /* the -2 is for not counting the length field*/
+  AddIntToMessage(communication_buffer_runner - id_length_buffer - 2,
+                  &id_length_buffer); /* the -2 is for not counting the length field*/
 
 
-  return pacCommBufRunner - pa_pacCommBuf;
+  return communication_buffer_runner - communication_buffer;
 }
 }
 
 
-void
-determineDelayTime(EIP_BYTE *pa_acBufferStart,
-    struct SDelayedEncapsulationMessage *pa_pstDelayedMessageBuffer)
-{
-  EIP_UINT16 unMaxDelayTime;
+void DetermineDelayTime(EipByte *buffer_start,
+                        DelayedEncapsulationMessage *delayed_message_buffer) {
+  EipUint16 maximum_delay_time;
 
 
-  pa_acBufferStart += 12; /* start of the sender context */
-  unMaxDelayTime = ltohs(&pa_acBufferStart);
-  if (0 == unMaxDelayTime)
-    {
-      unMaxDelayTime = 2000;
-    }
-  else if (500 > unMaxDelayTime)
-    {
-      unMaxDelayTime = 500;
-    }
+  buffer_start += 12; /* start of the sender context */
+  maximum_delay_time = GetIntFromMessage(&buffer_start);
+  if (0 == maximum_delay_time) {
+    maximum_delay_time = 2000;
+  } else if (500 > maximum_delay_time) {
+    maximum_delay_time = 500;
+  }
 
 
-  /* Limits mayDelayTime to 2000 milliseconds */
-  if (unMaxDelayTime > 2000)
-  {
-     unMaxDelayTime = 2000;
+  /* Limits maximum_delay_time to 2000 milliseconds */
+  if (maximum_delay_time > 2000) {
+    maximum_delay_time = 2000;
   }
   }
 
 
-  pa_pstDelayedMessageBuffer->m_unTimeOut = (unMaxDelayTime * rand()) / RAND_MAX
+  delayed_message_buffer->time_out = (maximum_delay_time * rand()) / RAND_MAX
       + 1;
       + 1;
 }
 }
 
 
-/*   void RegisterSession(struct S_Encapsulation_Data *pa_S_ReceiveData)
- *   Check supported protocol, generate session handle, send replay back to originator.
- *      pa_nSockfd       socket this request is associated to. Needed for double register check
- *      pa_S_ReceiveData pointer to received data with request/response.
+/* @brief Check supported protocol, generate session handle, send replay back to originator.
+ * @param socket Socket this request is associated to. Needed for double register check
+ * @param receive_data Pointer to received data with request/response.
  */
  */
-void
-handleReceivedRegisterSessionCmd(int pa_nSockfd,
-    struct S_Encapsulation_Data * pa_stReceiveData)
-{
+void HandleReceivedRegisterSessionCommand(int socket,
+                                          EncapsulationData *receive_data) {
   int i;
   int i;
-  int nSessionIndex = 0;
-  EIP_UINT8 *pacBuf;
-  EIP_UINT16 nProtocolVersion = ltohs(
-      &pa_stReceiveData->m_acCurrentCommBufferPos);
-  EIP_UINT16 nOptionFlag = ltohs(&pa_stReceiveData->m_acCurrentCommBufferPos);
+  int session_index = 0;
+  EipUint8 *receive_data_buffer;
+  EipUint16 protocol_version = GetIntFromMessage(
+      &receive_data->current_communication_buffer_position);
+  EipUint16 nOptionFlag = GetIntFromMessage(
+      &receive_data->current_communication_buffer_position);
 
 
   /* check if requested protocol version is supported and the register session option flag is zero*/
   /* check if requested protocol version is supported and the register session option flag is zero*/
-  if ((0 < 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_INVALID_COMMAND;
-              nSessionIndex = INVALID_SESSION;
-              pacBuf =
-                  &pa_stReceiveData->m_acCommBufferStart[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 =
-                  &pa_stReceiveData->m_acCommBufferStart[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*/
-            }
-        }
+  if ((0 < protocol_version) && (protocol_version <= kSupportedProtocolVersion)
+      && (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 (g_registered_sessions[i] == socket) {
+        /* the socket has already registered a session this is not allowed*/
+        receive_data->session_handle = i + 1; /*return the already assigned session back, the cip spec is not clear about this needs to be tested*/
+        receive_data->status = kEncapsulationProtocolInvalidCommand;
+        session_index = kInvalidSession;
+        receive_data_buffer =
+            &receive_data->communication_buffer_start[kEncapsulationHeaderSessionHandlePosition];
+        AddDintToMessage(receive_data->session_handle, &receive_data_buffer); /*EncapsulateData will not update the session handle so we have to do it here by hand*/
+        break;
+      }
     }
     }
-  else
-    { /* protocol not supported */
-      pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_UNSUPPORTED_PROTOCOL;
+
+    if (kInvalidSession != session_index) {
+      session_index = GetFreeSessionIndex();
+      if (kInvalidSession == session_index) /* no more sessions available */
+      {
+        receive_data->status = kEncapsulationProtocolInsufficientMemory;
+      } else { /* successful session registered */
+        g_registered_sessions[session_index] = socket; /* store associated socket */
+        receive_data->session_handle = session_index + 1;
+        receive_data->status = kEncapsulationProtocolSuccess;
+        receive_data_buffer =
+            &receive_data->communication_buffer_start[kEncapsulationHeaderSessionHandlePosition];
+        AddDintToMessage(receive_data->session_handle, &receive_data_buffer); /*EncapsulateData will not update the session handle so we have to do it here by hand*/
+      }
     }
     }
+  } else { /* protocol not supported */
+    receive_data->status = kEncapsulationProtocolUnsupportedProtocol;
+  }
 
 
-  pa_stReceiveData->nData_length = 4;
+  receive_data->data_length = 4;
 }
 }
 
 
 /*   INT8 UnregisterSession(struct S_Encapsulation_Data *pa_S_ReceiveData)
 /*   INT8 UnregisterSession(struct S_Encapsulation_Data *pa_S_ReceiveData)
  *   close all corresponding TCP connections and delete session handle.
  *   close all corresponding TCP connections and delete session handle.
  *      pa_S_ReceiveData pointer to unregister session request with corresponding socket handle.
  *      pa_S_ReceiveData pointer to unregister session request with corresponding socket handle.
  */
  */
-EIP_STATUS
-handleReceivedUnregisterSessionCmd(
-    struct S_Encapsulation_Data * pa_stReceiveData)
-{
+EipStatus HandleReceivedUnregisterSessionCommand(
+    EncapsulationData *receive_data) {
   int i;
   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_tcp(anRegisteredSessions[i]);
-          anRegisteredSessions[i] = EIP_INVALID_SOCKET;
-          return EIP_OK;
-        }
+  if ((0 < receive_data->session_handle)
+      && (receive_data->session_handle <= OPENER_NUMBER_OF_SUPPORTED_SESSIONS)) {
+    i = receive_data->session_handle - 1;
+    if (kEipInvalidSocket != g_registered_sessions[i]) {
+      IApp_CloseSocket_tcp(g_registered_sessions[i]);
+      g_registered_sessions[i] = kEipInvalidSocket;
+      return kEipStatusOk;
     }
     }
+  }
 
 
   /* no such session registered */
   /* no such session registered */
-  pa_stReceiveData->nData_length = 0;
-  pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
-  return EIP_OK_SEND;
+  receive_data->data_length = 0;
+  receive_data->status = kEncapsulationProtocolInvalidSessionHandle;
+  return kEipStatusOkSend;
 }
 }
 
 
-/*   INT8 SendUnitData(struct S_Encapsulation_Data *pa_S_ReceiveData)
- *   Call Connection Manager.
- *      pa_S_ReceiveData pointer to structure with data and header information.
+/** @brief Call Connection Manager.
+ *  @param receive_data Pointer to structure with data and header information.
  */
  */
-EIP_STATUS
-handleReceivedSendUnitDataCmd(struct S_Encapsulation_Data * pa_stReceiveData)
-{
-  EIP_INT16 nSendSize;
-  EIP_STATUS eRetVal = EIP_OK_SEND;
-
-  if (pa_stReceiveData->nData_length >= 6)
+EipStatus HandleReceivedSendUnitDataCommand(EncapsulationData *receive_data) {
+  EipInt16 send_size;
+  EipStatus return_value = kEipStatusOkSend;
+
+  if (receive_data->data_length >= 6) {
+    /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
+    /* don't use the data yet */
+    GetDintFromMessage(&receive_data->current_communication_buffer_position); /* skip over null interface handle*/
+    GetIntFromMessage(&receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
+    receive_data->data_length -= 6; /* the rest is in CPF format*/
+
+    if (kEipStatusError != CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
     {
     {
-      /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
-      /* don't use the data yet */
-      ltohl(&pa_stReceiveData->m_acCurrentCommBufferPos); /* skip over null interface handle*/
-      ltohs(&pa_stReceiveData->m_acCurrentCommBufferPos); /* skip over unused timeout value*/
-      pa_stReceiveData->nData_length -= 6; /* the rest is in CPF format*/
-
-      if (EIP_ERROR != checkRegisteredSessions(pa_stReceiveData)) /* see if the EIP session is registered*/
-        {
-          nSendSize =
-              notifyConnectedCPF(pa_stReceiveData,
-                  &pa_stReceiveData->m_acCommBufferStart[ENCAPSULATION_HEADER_LENGTH]);
-
-          if (0 < nSendSize)
-            { /* need to send reply */
-              pa_stReceiveData->nData_length = nSendSize;
-            }
-          else
-            {
-              eRetVal = EIP_ERROR;
-            }
-        }
-      else
-        { /* received a package with non registered session handle */
-          pa_stReceiveData->nData_length = 0;
-          pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
-        }
+      send_size =
+          NotifyConnectedCommonPacketFormat(
+              receive_data,
+              &receive_data->communication_buffer_start[ENCAPSULATION_HEADER_LENGTH]);
+
+      if (0 < send_size) { /* need to send reply */
+        receive_data->data_length = send_size;
+      } else {
+        return_value = kEipStatusError;
+      }
+    } else { /* received a package with non registered session handle */
+      receive_data->data_length = 0;
+      receive_data->status = kEncapsulationProtocolInvalidSessionHandle;
     }
     }
-  return eRetVal;
+  }
+  return return_value;
 }
 }
 
 
-/*   INT8 SendRRData(struct S_Encapsulation_Data *pa_stReceiveData)
- *   Call UCMM or Message Router if UCMM not implemented.
- *      pa_stReceiveData pointer to structure with data and header information.
- *  return status 	0 .. success.
+/** @brief Call UCMM or Message Router if UCMM not implemented.
+ *  @param receive_data Pointer to structure with data and header information.
+ *  @return status 	0 .. success.
  * 					-1 .. error
  * 					-1 .. error
  */
  */
-EIP_STATUS
-handleReceivedSendRRDataCmd(struct S_Encapsulation_Data * pa_stReceiveData)
-{
-  EIP_INT16 nSendSize;
-  EIP_STATUS eRetVal = EIP_OK_SEND;
-
-  if (pa_stReceiveData->nData_length >= 6)
+EipStatus HandleReceivedSendRequestResponseDataCommand(
+    EncapsulationData *receive_data) {
+  EipInt16 send_size;
+  EipStatus return_value = kEipStatusOkSend;
+
+  if (receive_data->data_length >= 6) {
+    /* Command specific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
+    /* don't use the data yet */
+    GetDintFromMessage(&receive_data->current_communication_buffer_position); /* skip over null interface handle*/
+    GetIntFromMessage(&receive_data->current_communication_buffer_position); /* skip over unused timeout value*/
+    receive_data->data_length -= 6; /* the rest is in CPF format*/
+
+    if (kEipStatusError != CheckRegisteredSessions(receive_data)) /* see if the EIP session is registered*/
     {
     {
-      /* Commandspecific data UDINT .. Interface Handle, UINT .. Timeout, CPF packets */
-      /* don't use the data yet */
-      ltohl(&pa_stReceiveData->m_acCurrentCommBufferPos); /* skip over null interface handle*/
-      ltohs(&pa_stReceiveData->m_acCurrentCommBufferPos); /* skip over unused timeout value*/
-      pa_stReceiveData->nData_length -= 6; /* the rest is in CPF format*/
-
-      if (EIP_ERROR != checkRegisteredSessions(pa_stReceiveData)) /* see if the EIP session is registered*/
-        {
-          nSendSize =
-              notifyCPF(pa_stReceiveData,
-                  &pa_stReceiveData->m_acCommBufferStart[ENCAPSULATION_HEADER_LENGTH]);
-
-          if (nSendSize >= 0)
-            { /* need to send reply */
-              pa_stReceiveData->nData_length = nSendSize;
-            }
-          else
-            {
-              eRetVal = EIP_ERROR;
-            }
-        }
-      else
-        { /* received a package with non registered session handle */
-          pa_stReceiveData->nData_length = 0;
-          pa_stReceiveData->nStatus = OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE;
-        }
+      send_size =
+          NotifyCommonPacketFormat(
+              receive_data,
+              &receive_data->communication_buffer_start[ENCAPSULATION_HEADER_LENGTH]);
+
+      if (send_size >= 0) { /* need to send reply */
+        receive_data->data_length = send_size;
+      } else {
+        return_value = kEipStatusError;
+      }
+    } else { /* received a package with non registered session handle */
+      receive_data->data_length = 0;
+      receive_data->status = kEncapsulationProtocolInvalidSessionHandle;
     }
     }
-  return eRetVal;
+  }
+  return return_value;
 }
 }
 
 
-/*   INT8 getFreeSessionIndex()
- *   search for available sessions an return index.
- *  return index of free session in anRegisteredSessions.
- * 			-1 .. no free session available
+/** @brief search for available sessions an return index.
+ *  @return return index of free session in anRegisteredSessions.
+ * 			kInvalidSession .. no free session available
  */
  */
-int
-getFreeSessionIndex(void)
-{
+int GetFreeSessionIndex(void) {
   int i;
   int i;
-  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++)
-    {
-      if (EIP_INVALID_SOCKET == anRegisteredSessions[i])
-        {
-          return i;
-        }
+  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; i++) {
+    if (kEipInvalidSocket == g_registered_sessions[i]) {
+      return i;
     }
     }
-  return -1;
+  }
+  return kInvalidSession;
 }
 }
 
 
-/*   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.
- *      pa_length	length of the data in pa_buf.
- *      pa_S_Data	structure to which data shall be copied
- *  return difference between bytes in pa_buf an data_length
+/** @brief copy data from pa_buf in little endian to host in structure.
+ * @param receive_buffer
+ * @param length Length of the data in receive_buffer. Might be more than one message
+ * @param encapsulation_data	structure to which data shall be copied
+ * @return return difference between bytes in pa_buf an data_length
  *  		0 .. full package received
  *  		0 .. full package received
  * 			>0 .. more than one packet received
  * 			>0 .. more than one packet received
  * 			<0 .. only fragment of data portion received
  * 			<0 .. only fragment of data portion received
- */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->m_acCommBufferStart = pa_buf;
-  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->m_acCurrentCommBufferPos = pa_buf;
-  return (pa_length - ENCAPSULATION_HEADER_LENGTH - pa_stData->nData_length);
+ */
+EipInt16 CreateEncapsulationStructure(EipUint8 *receive_buffer,
+                                      int receive_buffer_length,
+                                      EncapsulationData *encapsulation_data) {
+  encapsulation_data->communication_buffer_start = receive_buffer;
+  encapsulation_data->command_code = GetIntFromMessage(&receive_buffer);
+  encapsulation_data->data_length = GetIntFromMessage(&receive_buffer);
+  encapsulation_data->session_handle = GetDintFromMessage(&receive_buffer);
+  encapsulation_data->status = GetDintFromMessage(&receive_buffer);
+  /*memcpy(encapsulation_data->anSender_context, pa_buf, SENDER_CONTEXT_SIZE);*/
+  receive_buffer += kSenderContextSize;
+  encapsulation_data->options = GetDintFromMessage(&receive_buffer);
+  encapsulation_data->current_communication_buffer_position = receive_buffer;
+  return (receive_buffer_length - ENCAPSULATION_HEADER_LENGTH
+      - encapsulation_data->data_length);
 }
 }
 
 
-/*   INT8 checkRegisteredSessions(struct S_Encapsulation_Data *pa_S_ReceiveData)
- *   check if received package belongs to registered session.
- *      pa_stReceiveData received data.
- *  return 0 .. Session registered
- *  		-1 .. invalid session -> return unsupported command received
+/** @brief Check if received package belongs to registered session.
+ *  @param receive_data Received data.
+ *  @return 0 .. Session registered
+ *  		kInvalidSession .. 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;
-        }
+EipStatus CheckRegisteredSessions(EncapsulationData *receive_data) {
+  if ((0 < receive_data->session_handle)
+      && (receive_data->session_handle <= OPENER_NUMBER_OF_SUPPORTED_SESSIONS)) {
+    if (kEipInvalidSocket
+        != g_registered_sessions[receive_data->session_handle - 1]) {
+      return kEipStatusOk;
     }
     }
+  }
 
 
-  return EIP_ERROR;
+  return kEipStatusError;
 }
 }
 
 
-void
-closeSession(int pa_nSocket)
-{
+void CloseSession(int socket) {
   int i;
   int i;
-  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i)
-    {
-      if (anRegisteredSessions[i] == pa_nSocket)
-        {
-          IApp_CloseSocket_tcp(pa_nSocket);
-          anRegisteredSessions[i] = EIP_INVALID_SOCKET;
-          break;
-        }
+  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+    if (g_registered_sessions[i] == socket) {
+      IApp_CloseSocket_tcp(socket);
+      g_registered_sessions[i] = kEipInvalidSocket;
+      break;
     }
     }
+  }
 }
 }
 
 
-void
-encapShutDown(void)
-{
+void EncapsulationShutDown(void) {
   int i;
   int i;
-  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i)
-    {
-      if (EIP_INVALID_SOCKET != anRegisteredSessions[i])
-        {
-          IApp_CloseSocket_tcp(anRegisteredSessions[i]);
-          anRegisteredSessions[i] = EIP_INVALID_SOCKET;
-        }
+  for (i = 0; i < OPENER_NUMBER_OF_SUPPORTED_SESSIONS; ++i) {
+    if (kEipInvalidSocket != g_registered_sessions[i]) {
+      IApp_CloseSocket_tcp(g_registered_sessions[i]);
+      g_registered_sessions[i] = kEipInvalidSocket;
     }
     }
+  }
 }
 }
 
 
-void
-manageEncapsulationMessages()
-{
+void ManageEncapsulationMessages(void) {
   unsigned int i;
   unsigned int i;
-  for (i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++)
-    {
-      if (-1 != g_stDelayedEncapsulationMessages[i].m_nSocket)
-        {
-          g_stDelayedEncapsulationMessages[i].m_unTimeOut -= OPENER_TIMER_TICK;
-          if (0 >= g_stDelayedEncapsulationMessages[i].m_unTimeOut)
-            {
-              IApp_SendUDPData(
-                  &(g_stDelayedEncapsulationMessages[i].m_stSendToAddr),
-                  g_stDelayedEncapsulationMessages[i].m_nSocket,
-                  &(g_stDelayedEncapsulationMessages[i].m_anMsg[0]),
-                  g_stDelayedEncapsulationMessages[i].m_unMessageSize);
-              g_stDelayedEncapsulationMessages[i].m_nSocket = -1;
-            }
-        }
+  for (i = 0; i < ENCAP_NUMBER_OF_SUPPORTED_DELAYED_ENCAP_MESSAGES; i++) {
+    if (-1 != g_delayed_encapsulation_messages[i].socket) {
+      g_delayed_encapsulation_messages[i].time_out -=
+          kOpenerTimerTickInMilliSeconds;
+      if (0 >= g_delayed_encapsulation_messages[i].time_out) {
+        SendUdpData(&(g_delayed_encapsulation_messages[i].m_stSendToAddr),
+                    g_delayed_encapsulation_messages[i].socket,
+                    &(g_delayed_encapsulation_messages[i].message[0]),
+                    g_delayed_encapsulation_messages[i].message_size);
+        g_delayed_encapsulation_messages[i].socket = -1;
+      }
     }
     }
+  }
 }
 }

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

@@ -3,77 +3,77 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef ENCAP_H_
-#define ENCAP_H_
+#ifndef OPENER_ENCAP_H_
+#define OPENER_ENCAP_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 
 
+/** @file encap.h
+ * @brief This file contains the public interface of the encapsulation layer
+ */
 
 
-/**  \defgroup ENCAP OpENer Ethernet encapsulation layer
+/**  @defgroup ENCAP OpENer Ethernet encapsulation layer
  * The Ethernet encapsulation layer handles provides the abstraction between the Ethernet and the CIP layer.
  * The Ethernet encapsulation layer handles provides the abstraction between the Ethernet and the CIP layer.
  */
  */
 
 
 /*** defines ***/
 /*** defines ***/
 
 
-#define ENCAPSULATION_HEADER_LENGTH 24
-#define OPENER_ETHERNET_PORT 0xAF12
+#define ENCAPSULATION_HEADER_LENGTH	24
 
 
-/* definition of status codes in encapsulation protocol */
-#define OPENER_ENCAP_STATUS_SUCCESS                     0x0000
-#define OPENER_ENCAP_STATUS_INVALID_COMMAND             0x0001
-#define OPENER_ENCAP_STATUS_INSUFFICIENT_MEM            0x0002
-#define OPENER_ENCAP_STATUS_INCORRECT_DATA              0x0003
-#define OPENER_ENCAP_STATUS_INVALID_SESSION_HANDLE      0x0064
-#define OPENER_ENCAP_STATUS_INVALID_LENGTH              0x0065
-#define OPENER_ENCAP_STATUS_UNSUPPORTED_PROTOCOL        0x0069
+static const int OPENER_ETHERNET_PORT = 0xAF12;
 
 
+/* definition of status codes in encapsulation protocol */
+typedef enum {
+  kEncapsulationProtocolSuccess = 0x0000,
+  kEncapsulationProtocolInvalidCommand = 0x0001,
+  kEncapsulationProtocolInsufficientMemory = 0x0002,
+  kEncapsulationProtocolIncorrectData = 0x0003,
+  kEncapsulationProtocolInvalidSessionHandle = 0x0064,
+  kEncapsulationProtocolInvalidLength = 0x0065,
+  kEncapsulationProtocolUnsupportedProtocol = 0x0069
+} EncapsulationProtocolStatus;
 
 
 /*** structs ***/
 /*** structs ***/
-struct S_Encapsulation_Data
-  {
-    EIP_UINT16 nCommand_code;
-    EIP_UINT16 nData_length;
-    EIP_UINT32 nSession_handle;
-    EIP_UINT32 nStatus;
-    /* The sender context is not needed any more with the new minimum data copy design */
-    /* EIP_UINT8 anSender_context[SENDER_CONTEXT_SIZE];  */
-    EIP_UINT32 nOptions;
-    EIP_UINT8 *m_acCommBufferStart;       /*Pointer to the communication buffer used for this message */
-    EIP_UINT8 *m_acCurrentCommBufferPos;  /*The current position in the communication buffer during the decoding process */
-  };
+typedef struct encapsulation_data {
+  EipUint16 command_code;
+  EipUint16 data_length;
+  EipUint32 session_handle;
+  EipUint32 status;
+  EipUint32 options;
+  EipUint8 *communication_buffer_start; /**< Pointer to the communication buffer used for this message */
+  EipUint8 *current_communication_buffer_position; /**< The current position in the communication buffer during the decoding process */
+} EncapsulationData;
 
 
-struct S_Encapsulation_Interface_Information
-  {
-    EIP_UINT16 TypeCode;
-    EIP_UINT16 Length;
-    EIP_UINT16 EncapsulationProtocolVersion;
-    EIP_UINT16 CapabilityFlags;
-    EIP_INT8 NameofService[16];
-  };
+typedef struct encapsulation_interface_information {
+  EipUint16 type_code;
+  EipUint16 length;
+  EipUint16 encapsulation_protocol_version;
+  EipUint16 capability_flags;
+  EipInt8 name_of_service[16];
+} EncapsulationInterfaceInformation;
 
 
 /*** global variables (public) ***/
 /*** global variables (public) ***/
 
 
 /*** public functions ***/
 /*** public functions ***/
-/*! \ingroup ENCAP 
- * \brief Initialize the encapsulation layer.
+/** @ingroup ENCAP
+ * @brief Initialize the encapsulation layer.
  */
  */
-void encapInit(void);
+void EncapsulationInit(void);
 
 
-/*! \ingroup ENCAP
- * \brief Shutdown the encapsulation layer.
+/** @ingroup ENCAP
+ * @brief Shutdown the encapsulation layer.
  *
  *
  * This means that all open sessions including their sockets are closed.
  * This means that all open sessions including their sockets are closed.
  */
  */
-void encapShutDown(void);
-
+void EncapsulationShutDown(void);
 
 
-/*! \ingroup ENCAP
- * \brief Handle delayed encapsulation message responses
+/** @ingroup ENCAP
+ * @brief Handle delayed encapsulation message responses
  *
  *
  * Certain encapsulation message requests require a delayed sending of the response
  * Certain encapsulation message requests require a delayed sending of the response
  * message. This functions checks if messages need to be sent and performs the
  * message. This functions checks if messages need to be sent and performs the
  * sending.
  * sending.
  */
  */
-void manageEncapsulationMessages();
+void ManageEncapsulationMessages(void);
 
 
-#endif /*ENCAP_H_*/
+#endif /* OPENER_ENCAP_H_ */

+ 118 - 150
source/src/enet_encap/endianconv.c

@@ -5,220 +5,188 @@
  ******************************************************************************/
  ******************************************************************************/
 #include "endianconv.h"
 #include "endianconv.h"
 
 
-int g_nOpENerPlatformEndianess = -1;
+OpenerEndianess g_opener_platform_endianess = kOpenerEndianessUnknown;
 
 
 /* THESE ROUTINES MODIFY THE BUFFER POINTER*/
 /* THESE ROUTINES MODIFY THE BUFFER POINTER*/
 
 
 /* little-endian-to-host unsigned 16 bit*/
 /* little-endian-to-host unsigned 16 bit*/
 
 
 /**
 /**
- *   \brief Reads EIP_UINT16 from *pa_buf and converts little endian to host.
- *   \param pa_buf pointer where data should be reed.
- *   \return EIP_UINT16 value
+ *   @brief Reads EIP_UINT16 from *pa_buf and converts little endian to host.
+ *   @param pa_buf pointer where data should be reed.
+ *   @return EIP_UINT16 data value
  */
  */
-EIP_UINT16
-ltohs(EIP_UINT8** pa_buf)
-{
-  unsigned char *p = (unsigned char *) *pa_buf;
-  EIP_UINT16 data = p[0] | p[1] << 8;
-  *pa_buf += 2;
+EipUint16 GetIntFromMessage(EipUint8** buffer) {
+  unsigned char *buffer_address = (unsigned char *) *buffer;
+  EipUint16 data = buffer_address[0] | buffer_address[1] << 8;
+  *buffer += 2;
   return data;
   return data;
 }
 }
 
 
 /**
 /**
- *   \brief Reads EIP_UINT32 from *pa_buf and converts little endian to host.
- *   \param pa_buf pointer where data should be reed.
- *   \return EIP_UNÍT32 value
+ *   @brief Reads EIP_UINT32 from *pa_buf and converts little endian to host.
+ *   @param pa_buf pointer where data should be reed.
+ *   @return EIP_UNÍT32 value
  */
  */
-EIP_UINT32
-ltohl(EIP_UINT8** pa_buf)
-{
-  unsigned char *p = (unsigned char *) *pa_buf;
-  EIP_UINT32 data = p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24;
-  *pa_buf += 4;
+EipUint32 GetDintFromMessage(EipUint8** buffer) {
+  unsigned char *p = (unsigned char *) *buffer;
+  EipUint32 data = p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24;
+  *buffer += 4;
   return data;
   return data;
 }
 }
 
 
 /**
 /**
- * \brief converts UINT16 data from host to little endian an writes it to pa_buf.
- * \param data value to be written
- * \param pa_buf pointer where data should be written.
+ * @brief converts UINT16 data from host to little endian an writes it to pa_buf.
+ * @param data value to be written
+ * @param pa_buf pointer where data should be written.
  */
  */
-void
-htols(EIP_UINT16 data, EIP_UINT8 **pa_buf)
-{
-  unsigned char *p = (unsigned char *) *pa_buf;
+void AddIntToMessage(EipUint16 data, EipUint8 **buffer) {
+  unsigned char *p = (unsigned char *) *buffer;
 
 
   p[0] = (unsigned char) data;
   p[0] = (unsigned char) data;
   p[1] = (unsigned char) (data >> 8);
   p[1] = (unsigned char) (data >> 8);
-  *pa_buf += 2;
+  *buffer += 2;
 }
 }
 
 
 /**
 /**
- * \brief Converts UINT32 data from host to little endian and writes it to pa_buf.
- * \param data value to be written
- * \param pa_buf pointer where data should be written.
+ * @brief Converts UINT32 data from host to little endian and writes it to pa_buf.
+ * @param data value to be written
+ * @param pa_buf pointer where data should be written.
  */
  */
-void
-htoll(EIP_UINT32 data, EIP_UINT8** pa_buf)
-{
-  unsigned char *p = (unsigned char *) *pa_buf;
+void AddDintToMessage(EipUint32 data, EipUint8** buffer) {
+  unsigned char *p = (unsigned char *) *buffer;
 
 
   p[0] = (unsigned char) data;
   p[0] = (unsigned char) data;
   p[1] = (unsigned char) (data >> 8);
   p[1] = (unsigned char) (data >> 8);
   p[2] = (unsigned char) (data >> 16);
   p[2] = (unsigned char) (data >> 16);
   p[3] = (unsigned char) (data >> 24);
   p[3] = (unsigned char) (data >> 24);
-  *pa_buf += 4;
+  *buffer += 4;
 }
 }
 
 
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 
 
-
 /**
 /**
- *   \brief Reads EIP_UINT64 from *pa_buf and converts little endian to host.
- *   \param pa_buf pointer where data should be reed.
- *   \return EIP_UNÍT64 value
+ *   @brief Reads EIP_UINT64 from *pa_buf and converts little endian to host.
+ *   @param pa_buf pointer where data should be reed.
+ *   @return EIP_UNÍT64 value
  */
  */
-EIP_UINT64
-ltoh64(EIP_UINT8 ** pa_pnBuf)
-{
-  EIP_UINT8 *pnBuffer = *pa_pnBuf;
-  EIP_UINT64 unData =
-      ((((EIP_UINT64) pnBuffer[0]) << 56) & 0xFF00000000000000LL)
-          + ((((EIP_UINT64) pnBuffer[1]) << 48) & 0x00FF000000000000LL)
-          + ((((EIP_UINT64) pnBuffer[2]) << 40) & 0x0000FF0000000000LL)
-          + ((((EIP_UINT64) pnBuffer[3]) << 32) & 0x000000FF00000000LL)
-          + ((((EIP_UINT64) pnBuffer[4]) << 24) & 0x00000000FF000000)
-          + ((((EIP_UINT64) pnBuffer[5]) << 16) & 0x0000000000FF0000)
-          + ((((EIP_UINT64) pnBuffer[6]) << 8) & 0x000000000000FF00)
-          + (((EIP_UINT64) pnBuffer[7]) & 0x00000000000000FF);
-  (*pa_pnBuf) += 8;
-  return unData;
+EipUint64 GetLintFromMessage(EipUint8 **buffer) {
+  EipUint8 *buffer_address = *buffer;
+  EipUint64 data = ((((EipUint64) buffer_address[0]) << 56)
+      & 0xFF00000000000000LL)
+      + ((((EipUint64) buffer_address[1]) << 48) & 0x00FF000000000000LL)
+      + ((((EipUint64) buffer_address[2]) << 40) & 0x0000FF0000000000LL)
+      + ((((EipUint64) buffer_address[3]) << 32) & 0x000000FF00000000LL)
+      + ((((EipUint64) buffer_address[4]) << 24) & 0x00000000FF000000)
+      + ((((EipUint64) buffer_address[5]) << 16) & 0x0000000000FF0000)
+      + ((((EipUint64) buffer_address[6]) << 8) & 0x000000000000FF00)
+      + (((EipUint64) buffer_address[7]) & 0x00000000000000FF);
+  (*buffer) += 8;
+  return data;
 }
 }
 
 
 /**
 /**
- * \brief Converts UINT64 data from host to little endian and writes it to pa_buf.
- * \param data value to be written
- * \param pa_buf pointer where data should be written.
+ * @brief Converts UINT64 data from host to little endian and writes it to pa_buf.
+ * @param data value to be written
+ * @param pa_buf pointer where data should be written.
  */
  */
-void
-htol64(EIP_UINT64 pa_unData, EIP_UINT8 ** pa_pnBuf)
-{
-  EIP_UINT8 *pnBuffer = *pa_pnBuf;
-  pnBuffer[0] = (EIP_UINT8) (pa_unData >> 56) & 0xFF;
-  pnBuffer[1] = (EIP_UINT8) (pa_unData >> 48) & 0xFF;
-  pnBuffer[2] = (EIP_UINT8) (pa_unData >> 40) & 0xFF;
-  pnBuffer[3] = (EIP_UINT8) (pa_unData >> 32) & 0xFF;
-  pnBuffer[4] = (EIP_UINT8) (pa_unData >> 24) & 0xFF;
-  pnBuffer[5] = (EIP_UINT8) (pa_unData >> 16) & 0xFF;
-  pnBuffer[6] = (EIP_UINT8) (pa_unData >> 8) & 0xFF;
-  pnBuffer[7] = (EIP_UINT8) (pa_unData) & 0xFF;
-  (*pa_pnBuf) += 8;
+void AddLintToMessage(EipUint64 data, EipUint8 **buffer) {
+  EipUint8 *buffer_address = *buffer;
+  buffer_address[0] = (EipUint8) (data >> 56) & 0xFF;
+  buffer_address[1] = (EipUint8) (data >> 48) & 0xFF;
+  buffer_address[2] = (EipUint8) (data >> 40) & 0xFF;
+  buffer_address[3] = (EipUint8) (data >> 32) & 0xFF;
+  buffer_address[4] = (EipUint8) (data >> 24) & 0xFF;
+  buffer_address[5] = (EipUint8) (data >> 16) & 0xFF;
+  buffer_address[6] = (EipUint8) (data >> 8) & 0xFF;
+  buffer_address[7] = (EipUint8) (data) & 0xFF;
+  (*buffer) += 8;
 }
 }
 
 
 #endif
 #endif
 
 
 /**
 /**
- * \brief Encapsulates the IP address and port into the package
+ * @brief Encapsulates the IP address and port into the package
  *
  *
- * \param pa_unPort IP Port
- * \param pa_unAddr IP Address
- * \param pa_acCommBuf Buffer for constructing the message
+ * @param pa_unPort IP Port
+ * @param pa_unAddr IP Address
+ * @param pa_acCommBuf Buffer for constructing the message
  */
  */
-void
-encapsulateIPAdress(EIP_UINT16 pa_unPort, EIP_UINT32 pa_unAddr,
-    EIP_BYTE *pa_acCommBuf)
-{
-  if (OPENER_LITTLE_ENDIAN_PLATFORM == g_nOpENerPlatformEndianess)
-    {
-      htols(htons(AF_INET), &pa_acCommBuf);
-      htols(htons(pa_unPort), &pa_acCommBuf);
-      htoll(pa_unAddr, &pa_acCommBuf);
-    }
-  else
-    {
-      if (OPENER_BIG_ENDIAN_PLATFORM == g_nOpENerPlatformEndianess)
-        {
-          pa_acCommBuf[0] = (unsigned char) (AF_INET >> 8);
-          pa_acCommBuf[1] = (unsigned char) AF_INET;
-          pa_acCommBuf += 2;
-
-          pa_acCommBuf[0] = (unsigned char) (pa_unPort >> 8);
-          pa_acCommBuf[1] = (unsigned char) pa_unPort;
-          pa_acCommBuf += 2;
-
-          pa_acCommBuf[3] = (unsigned char) pa_unAddr;
-          pa_acCommBuf[2] = (unsigned char) (pa_unAddr >> 8);
-          pa_acCommBuf[1] = (unsigned char) (pa_unAddr >> 16);
-          pa_acCommBuf[0] = (unsigned char) (pa_unAddr >> 24);
-        }
+void EncapsulateIpAddress(EipUint16 port, EipUint32 address,
+                          EipByte *communication_buffer) {
+  if (kOpENerEndianessLittle == g_opener_platform_endianess) {
+    AddIntToMessage(htons(AF_INET), &communication_buffer);
+    AddIntToMessage(htons(port), &communication_buffer);
+    AddDintToMessage(address, &communication_buffer);
+  } else {
+    if (kOpENerEndianessBig == g_opener_platform_endianess) {
+      communication_buffer[0] = (unsigned char) (AF_INET >> 8);
+      communication_buffer[1] = (unsigned char) AF_INET;
+      communication_buffer += 2;
+
+      communication_buffer[0] = (unsigned char) (port >> 8);
+      communication_buffer[1] = (unsigned char) port;
+      communication_buffer += 2;
+
+      communication_buffer[3] = (unsigned char) address;
+      communication_buffer[2] = (unsigned char) (address >> 8);
+      communication_buffer[1] = (unsigned char) (address >> 16);
+      communication_buffer[0] = (unsigned char) (address >> 24);
     }
     }
+  }
 }
 }
 
 
 /**
 /**
- * \brief encapsulates the ip address and port into the package (Common Paket Format variant)
+ * @brief encapsulates the IP address and port into the package (Common Paket Format variant)
  *
  *
- * \param pa_unPort IP port
- * \param pa_unAddr IP address
- * \param pa_acCommBuf buffer for constructing the message
+ * @param port IP port
+ * @param address IP address
+ * @param communication_buffer buffer for constructing the message
  */
  */
-void
-encapsulateIPAdressCPF(EIP_UINT16 pa_unPort, EIP_UINT32 pa_unAddr,
-    EIP_BYTE *pa_acCommBuf)
-{
-  if (OPENER_LITTLE_ENDIAN_PLATFORM == g_nOpENerPlatformEndianess)
-    {
-      htols(htons(AF_INET), &pa_acCommBuf);
-      htols(pa_unPort, &pa_acCommBuf);
-      htoll(pa_unAddr, &pa_acCommBuf);
-
-    }
-  else
-    {
-      if (OPENER_BIG_ENDIAN_PLATFORM == g_nOpENerPlatformEndianess)
-        {
-          pa_acCommBuf[0] = (unsigned char) (AF_INET >> 8);
-          pa_acCommBuf[1] = (unsigned char) AF_INET;
-          pa_acCommBuf += 2;
-
-          pa_acCommBuf[0] = (unsigned char) (pa_unPort >> 8);
-          pa_acCommBuf[1] = (unsigned char) pa_unPort;
-          pa_acCommBuf += 2;
-
-          pa_acCommBuf[3] = (unsigned char) pa_unAddr;
-          pa_acCommBuf[2] = (unsigned char) (pa_unAddr >> 8);
-          pa_acCommBuf[1] = (unsigned char) (pa_unAddr >> 16);
-          pa_acCommBuf[0] = (unsigned char) (pa_unAddr >> 24);
-        }
+void EncapsulateIpAddressCommonPaketFormat(EipUint16 port, EipUint32 address,
+                                           EipByte *communication_buffer) {
+  if (kOpENerEndianessLittle == g_opener_platform_endianess) {
+    AddIntToMessage(htons(AF_INET), &communication_buffer);
+    AddIntToMessage(port, &communication_buffer);
+    AddDintToMessage(address, &communication_buffer);
+
+  } else {
+    if (kOpENerEndianessBig == g_opener_platform_endianess) {
+      communication_buffer[0] = (unsigned char) (AF_INET >> 8);
+      communication_buffer[1] = (unsigned char) AF_INET;
+      communication_buffer += 2;
+
+      communication_buffer[0] = (unsigned char) (port >> 8);
+      communication_buffer[1] = (unsigned char) port;
+      communication_buffer += 2;
+
+      communication_buffer[3] = (unsigned char) address;
+      communication_buffer[2] = (unsigned char) (address >> 8);
+      communication_buffer[1] = (unsigned char) (address >> 16);
+      communication_buffer[0] = (unsigned char) (address >> 24);
     }
     }
+  }
 }
 }
 
 
 /**
 /**
- * \brief Detects Endianess of the platform and sets global g_nOpENerPlatformEndianess variable accordingly
+ * @brief Detects Endianess of the platform and sets global g_nOpENerPlatformEndianess variable accordingly
  *
  *
  * Detects Endianess of the platform and sets global variable g_nOpENerPlatformEndianess accordingly,
  * Detects Endianess of the platform and sets global variable g_nOpENerPlatformEndianess accordingly,
  * whereas 0 equals little endian and 1 equals big endian
  * whereas 0 equals little endian and 1 equals big endian
  */
  */
-void
-determineEndianess()
-{
+void DetermineEndianess() {
   int i = 1;
   int i = 1;
   char *p = (char *) &i;
   char *p = (char *) &i;
-  if (p[0] == 1)
-    {
-      g_nOpENerPlatformEndianess = OPENER_LITTLE_ENDIAN_PLATFORM;
-    }
-  else
-    {
-      g_nOpENerPlatformEndianess = OPENER_BIG_ENDIAN_PLATFORM;
-    }
+  if (p[0] == 1) {
+    g_opener_platform_endianess = kOpENerEndianessLittle;
+  } else {
+    g_opener_platform_endianess = kOpENerEndianessBig;
+  }
 }
 }
 
 
 /**
 /**
- * \brief Returns global variable g_nOpENerPlatformEndianess, whereas 0 equals little endian and 1 equals big endian
+ * @brief Returns global variable g_nOpENerPlatformEndianess, whereas 0 equals little endian and 1 equals big endian
  */
  */
-int
-getEndianess()
-{
-  return g_nOpENerPlatformEndianess;
+int GetEndianess() {
+  return g_opener_platform_endianess;
 }
 }

+ 47 - 42
source/src/enet_encap/endianconv.h

@@ -3,75 +3,80 @@
  * All rights reserved. 
  * All rights reserved. 
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef ENDIANCONV_H_
-#define ENDIANCONV_H_
+#ifndef OpENer_ENDIANCONV_H_
+#define OpENer_ENDIANCONV_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 
 
-#define OPENER_LITTLE_ENDIAN_PLATFORM 0
-#define OPENER_BIG_ENDIAN_PLATFORM    1
+/** @file endianconv.h
+ * @brief Responsible for Endianess conversion
+ */
 
 
-/*! \ingroup ENCAP
- * Get an 16Bit integer from the network buffer.
- * @param pa_buf pointer to the network buffer array. This pointer will be incremented by 2!
- */EIP_UINT16
-ltohs(EIP_UINT8 **pa_buf);
+typedef enum {
+  kOpenerEndianessUnknown = -1,
+  kOpENerEndianessLittle = 0,
+  kOpENerEndianessBig = 1
+} OpenerEndianess;
 
 
-/*! \ingroup ENCAP
- * Get an 32Bit integer from the network buffer.
- * @param pa_buf pointer to the network buffer array. This pointer will be incremented by 4!
- */EIP_UINT32
-ltohl(EIP_UINT8 **pa_buf);
+/** @ingroup ENCAP
+ *
+ * @brief Get an 16Bit integer from the network buffer, and moves pointer beyond the 16 bit value
+ * @param buffer Pointer to the network buffer array. This pointer will be incremented by 2!
+ * @return Extracted 16 bit integer value
+ */
+EipUint16 GetIntFromMessage(EipUint8 **buffer);
+
+/** @ingroup ENCAP
+ *
+ * @brief Get an 32Bit integer from the network buffer.
+ * @param buffer pointer to the network buffer array. This pointer will be incremented by 4!
+ * @return Extracted 32 bit integer value
+ */
+EipUint32 GetDintFromMessage(EipUint8 **buffer);
 
 
-/*! \ingroup ENCAP
- * Write an 16Bit integer to the network buffer.
+/** @ingroup ENCAP
+ *
+ * @brief Write an 16Bit integer to the network buffer.
  * @param data value to write
  * @param data value to write
- * @param pa_buf pointer to the network buffer array. This pointer will be incremented by 2!
+ * @param buffer pointer to the network buffer array. This pointer will be incremented by 2!
  */
  */
-void
-htols(EIP_UINT16 data, EIP_UINT8 **pa_buf);
+void AddIntToMessage(EipUint16 data, EipUint8 **buffer);
 
 
-/*! \ingroup ENCAP
- * Write an 32Bit integer to the network buffer.
+/** @ingroup ENCAP
+ *
+ * @brief Write an 32Bit integer to the network buffer.
  * @param data value to write
  * @param data value to write
- * @param pa_buf pointer to the network buffer array. This pointer will be incremented by 4!
+ * @param buffer pointer to the network buffer array. This pointer will be incremented by 4!
  */
  */
-void
-htoll(EIP_UINT32 data, EIP_UINT8 **pa_buf);
+void AddDintToMessage(EipUint32 data, EipUint8 **buffer);
 
 
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 
 
-EIP_UINT64
-ltoh64(EIP_UINT8 ** pa_pnBuf);
+EipUint64 GetLintFromMessage(EipUint8 **buffer);
 
 
-void
-htol64(EIP_UINT64 pa_unData, EIP_UINT8 ** pa_pnBuf);
+void AddLintToMessage(EipUint64 pa_unData, EipUint8 **buffer);
 
 
 #endif
 #endif
 
 
-void
-encapsulateIPAdress(EIP_UINT16 pa_unPort, EIP_UINT32 pa_unAddr,
-    EIP_BYTE *pa_acCommBuf);
+void EncapsulateIpAddress(EipUint16 port, EipUint32 address,
+                          EipByte *communication_buffer);
 
 
-/*! \brief Encapsulate the sockaddr information as necessary for the CPF data items
+/** @brief Encapsulate the sockaddr information as necessary for the Common Paket Format data items
  */
  */
-void
-encapsulateIPAdressCPF(EIP_UINT16 pa_unPort, EIP_UINT32 pa_unAddr,
-    EIP_BYTE *pa_acCommBuf);
-
-
+void EncapsulateIpAddressCommonPaketFormat(EipUint16 port, EipUint32 address,
+                                           EipByte *communication_buffer);
 
 
 /** Identify if we are running on a big or little endian system and set
 /** Identify if we are running on a big or little endian system and set
  * variable.
  * variable.
  */
  */
-void determineEndianess();
+void DetermineEndianess(void);
 
 
-/** Return the endianess identified on system startup
- * \return
+/** @brief Return the endianess identified on system startup
+ * @return
  *    - -1 endianess has not been identified up to now
  *    - -1 endianess has not been identified up to now
  *    - 0  little endian system
  *    - 0  little endian system
  *    - 1  big endian system
  *    - 1  big endian system
  */
  */
-int getEndianess();
+int GetEndianess(void);
 
 
-#endif /*ENDIANCONV_H_*/
+#endif /*OpENer_ENDIANCONV_H_*/

+ 565 - 475
source/src/opener_api.h

@@ -1,86 +1,79 @@
 /*******************************************************************************
 /*******************************************************************************
  * Copyright (c) 2009, Rockwell Automation, Inc.
  * Copyright (c) 2009, Rockwell Automation, Inc.
- * All rights reserved. 
+ * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef CIP_API_H_
-#define CIP_API_H_
+#ifndef OPENER_OPENER_API_H_
+#define OPENER_OPENER_API_H_
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 #include "ciptypes.h"
 #include "ciptypes.h"
 #include "ciperror.h"
 #include "ciperror.h"
-#include <opener_user_conf.h>
+#include "opener_user_conf.h"
 
 
-/**  \defgroup CIP_API OpENer User interface
- * \brief This is the public interface of the OpENer. It provides all function needed to implement an EtherNet/IP enabled slave-device.
+/**  @defgroup CIP_API OpENer User interface
+ * @brief This is the public interface of the OpENer. It provides all function
+ * needed to implement an EtherNet/IP enabled slave-device.
  */
  */
 
 
-
-/*! \ingroup CIP_API
- * \brief Configure the data of the network interface of the device
- * 
+/** @ingroup CIP_API
+ * @brief Configure the data of the network interface of the device
+ *
  *  This function setup the data of the network interface needed by OpENer.
  *  This function setup the data of the network interface needed by OpENer.
  *  The multicast address is automatically calculated from he given data.
  *  The multicast address is automatically calculated from he given data.
- * 
- *  @param pa_acIpAdress    the current IP address of the device
- *  @param pa_acSubNetMask  the subnet mask to be used
- *  @param pa_acGateway     the gateway address 
+ *
+ *  @param ip_address    the current IP address of the device
+ *  @param subnet_mask  the subnet mask to be used
+ *  @param gateway_address     the gateway address
  *  @return EIP_OK if the configuring worked otherwise EIP_ERROR
  *  @return EIP_OK if the configuring worked otherwise EIP_ERROR
  */
  */
-EIP_STATUS
-configureNetworkInterface(const char *pa_acIpAdress,
-    const char *pa_acSubNetMask, const char *pa_acGateway);
+EipStatus
+ConfigureNetworkInterface(const char *ip_address, const char *subnet_mask,
+                          const char *gateway_address);
 
 
-/*! \ingroup CIP_API 
- * \brief Configure the MAC address of the device
- * 
- *  @param pa_acMACAddress  the hardware MAC address of the network interface
+/** @ingroup CIP_API
+ * @brief Configure the MAC address of the device
+ *
+ *  @param mac_address  the hardware MAC address of the network interface
  */
  */
-void
-configureMACAddress(const EIP_UINT8 *pa_acMACAddress);
+void ConfigureMacAddress(const EipUint8 *mac_address);
 
 
-/*! \ingroup CIP_API 
- * \brief Configure the domain name of the device
- *  @param pa_acDomainName the domain name to be used
+/** @ingroup CIP_API
+ * @brief Configure the domain name of the device
+ * @param domain_name the domain name to be used
  */
  */
-void
-configureDomainName(const char *pa_acDomainName);
+void ConfigureDomainName(const char *domain_name);
 
 
-/*! \ingroup CIP_API 
- * \brief Configure the host name of the device
- *  @param pa_acHostName the host name to be used
+/** @ingroup CIP_API
+ * @brief Configure the host name of the device
+ * @param host_name the host name to be used
  */
  */
-void
-configureHostName(const char *pa_acHostName);
+void ConfigureHostName(const char *host_name);
 
 
-/*! \ingroup CIP_API
- * \brief Set the serial number of the device's identity object.
- * 
- * @param pa_nSerialNumber unique 32 bit number identifying the device
+/** @ingroup CIP_API
+ * @brief Set the serial number of the device's identity object.
+ *
+ * @param serial_number unique 32 bit number identifying the device
  */
  */
-void
-setDeviceSerialNumber(EIP_UINT32 pa_nSerialNumber);
+void SetDeviceSerialNumber(EipUint32 serial_number);
 
 
-/*!\ingroup CIP_API
- * \brief Set the current status of the device.
+/** @ingroup CIP_API
+ * @brief Set the current status of the device.
  *
  *
- * @param pa_unStatus the new status value
+ * @param device_status the new status value
  */
  */
-void
-setDeviceStatus(EIP_UINT16 pa_unStatus);
+void SetDeviceStatus(EipUint16 device_status);
 
 
-/** \ingroup CIP_API 
- * \brief Initialize and setup the CIP-stack
- * 
- * @param pa_nUniqueConnID value passed to Connection_Manager_Init() to form a
- *                      "per boot" unique connection ID.
+/** @ingroup CIP_API
+ * @brief Initialize and setup the CIP-stack
  *
  *
+ * @param unique_connection_id value passed to Connection_Manager_Init() to form
+ * a "per boot" unique connection ID.
  */
  */
-void
-CIP_Init(EIP_UINT16 pa_nUniqueConnID);
+void CipStackInit(EipUint16 unique_connection_id);
 
 
-/** \ingroup CIP_API
- * \brief Shutdown the CIP-stack
+/** @ingroup CIP_API
+ * @brief Shutdown of the CIP stack
  *
  *
  * This will
  * This will
  *   - close all open I/O connections,
  *   - close all open I/O connections,
@@ -90,104 +83,110 @@ CIP_Init(EIP_UINT16 pa_nUniqueConnID);
  * Memory allocated by the application will not be freed. This has to be done
  * Memory allocated by the application will not be freed. This has to be done
  * by the application!
  * by the application!
  */
  */
-void
-shutdownCIP(void);
+void ShutdownCipStack(void);
 
 
-/** \ingroup CIP_API 
- * \brief Get a pointer to a CIP object with given class code
- * 
- * @param pa_nClassID class ID of the object to retrieve 
+/** @ingroup CIP_API
+ * @brief Get a pointer to a CIP object with given class code
+ *
+ * @param class_id class ID of the object to retrieve
  * @return pointer to CIP Object
  * @return pointer to CIP Object
  *          0 if object is not present in the stack
  *          0 if object is not present in the stack
  */
  */
-S_CIP_Class *
-getCIPClass(EIP_UINT32 pa_nClassID);
+CipClass *GetCipClass(EipUint32 class_id);
 
 
-/** \ingroup CIP_API 
- * \brief Get a pointer to an instance
- * 
- * @param pa_pstObject pointer to the object the instance belongs to
- * @param pa_nInstanceNr number of the instance to retrieve
+/** @ingroup CIP_API
+ * @brief Get a pointer to an instance
+ *
+ * @param cip_object pointer to the object the instance belongs to
+ * @param instance_number number of the instance to retrieve
  * @return pointer to CIP Instance
  * @return pointer to CIP Instance
  *          0 if instance is not in the object
  *          0 if instance is not in the object
  */
  */
-S_CIP_Instance *
-getCIPInstance(S_CIP_Class *pa_pstObject, EIP_UINT32 pa_nInstanceNr);
+CipInstance *GetCipInstance(CipClass *cip_object, EipUint32 instance_number);
 
 
-/** \ingroup CIP_API 
- * \brief Get a pointer to an instance's attribute
- * 
+/** @ingroup CIP_API
+ * @brief Get a pointer to an instance's attribute
+ *
  * As instances and objects are selfsimilar this function can also be used
  * As instances and objects are selfsimilar this function can also be used
- * to retrieve the attribute of an object. 
- * @param pa_pInstance  pointer to the instance the attribute belongs to
- * @param pa_nAttributeNr number of the attribute to retrieve
+ * to retrieve the attribute of an object.
+ * @param cip_instance  pointer to the instance the attribute belongs to
+ * @param attribute_number number of the attribute to retrieve
  * @return pointer to attribute
  * @return pointer to attribute
  *          0 if instance is not in the object
  *          0 if instance is not in the object
  */
  */
-S_CIP_attribute_struct *
-getAttribute(S_CIP_Instance * pa_pInstance, EIP_UINT16 pa_nAttributeNr);
+CipAttributeStruct *GetCipAttribute(CipInstance *cip_instance,
+                                    EipUint16 attribute_number);
 
 
-/*! \ingroup CIP_API 
- * \brief Allocate memory for new CIP Class and attributes
+/** @ingroup CIP_API
+ * @brief Allocate memory for new CIP Class and attributes
  *
  *
  *  The new CIP class will be registered at the stack to be able
  *  The new CIP class will be registered at the stack to be able
  *  for receiving explicit messages.
  *  for receiving explicit messages.
- * 
- *  @param pa_nClassID class ID of the new class
- *  @param pa_nNr_of_ClassAttributes number of class attributes
- *  @param pa_nClassGetAttrAllMask mask of which attributes are included in the class getAttributeAll
- *       If the mask is 0 the getAttributeAll service will not be added as class service
- *  @param pa_nNr_of_ClassServices number of class services
- *  @param pa_nNr_of_InstanceAttributes number of attributes of each instance
- *  @param pa_nInstGetAttrAllMask  mask of which attributes are included in the instance getAttributeAll
- *       If the mask is 0 the getAttributeAll service will not be added as class service
- *  @param pa_nNr_of_InstanceServices number of instance services
- *  @param pa_nNr_of_Instances number of initial instances to create
- *  @param pa_acName  class name (for debugging class structure)
- *  @param pa_nRevision class revision
+ *
+ *  @param class_id class ID of the new class
+ *  @param number_of_class_attributes number of class attributes
+ *  @param get_attribute_all_mask mask of which attributes are included in the
+ *  class getAttributeAll.
+ *  If the mask is 0 the getAttributeAll service will not be added as class
+ *  service
+ *  @param number_of_class_services number of class services
+ *  @param number_of_instance_attributes number of attributes of each instance
+ *  @param instance_attributes_get_attributes_all_mask  mask of which attributes
+ *  are included in the instance getAttributeAll
+ *  If the mask is 0 the getAttributeAll service will not be added as class
+ *  service
+ *  @param number_of_instance_services number of instance services
+ *  @param number_of_instances number of initial instances to create
+ *  @param class_name  class name (for debugging class structure)
+ *  @param class_revision class revision
  *  @return pointer to new class object
  *  @return pointer to new class object
  *      0 on error
  *      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);
-
-/** \ingroup CIP_API 
- * \brief Add a number of CIP instances to a given CIP class
- *
- * The required number of instances are created in a block, but are attached to the class as a linked list.
- * the instances are numbered sequentially -- i.e. the first node in the chain is instance 1, the second is 2, etc.
- * you can add new instances at any time (you do not have to create all the instances of a class at the same time)
- * deleting instances once they have been created is not supported
- * out-of-order instance numbers are not supported
- * running out of memory while creating new instances causes an assert
- *
- * @param pa_pstCIPObject CIP object the instances should be added
- * @param pa_nNr_of_Instances number of instances to be generated.
+CipClass *CreateCipClass(EipUint32 class_id, int number_of_class_attributes,
+                         EipUint32 class_attributes_get_attribute_all_mask,
+                         int number_of_class_services,
+                         int number_of_instance_attributes,
+                         EipUint32 instance_attributes_get_attributes_all_mask,
+                         int number_of_instance_services,
+                         int number_of_instances, char *class_name,
+                         EipUint16 class_revision);
+
+/** @ingroup CIP_API
+ * @brief Add a number of CIP instances to a given CIP class
+ *
+ * The required number of instances are created in a block, but are attached to
+ * the class as a linked list.
+ * The instances are numbered sequentially -- i.e. the first node in the chain
+ * is instance 1, the second is 2, and so on.
+ * You can add new instances at any time (you do not have to create all the
+ * instances of a class at the same time) deleting instances once they have
+ * been created is not supported out-of-order instance numbers are not
+ * supported running out of memory while creating new instances causes an
+ * assert.
+ *
+ * @param cip_object_to_add_instances CIP object the instances should be added
+ * @param number_of_instances number of instances to be generated.
  * @return pointer to the first of the new instances
  * @return pointer to the first of the new instances
  *              0 on error
  *              0 on error
  */
  */
-S_CIP_Instance *
-addCIPInstances(S_CIP_Class *pa_pstCIPObject, int pa_nNr_of_Instances);
+CipInstance *AddCipInstances(CipClass *cip_object_to_add_instances,
+                             int number_of_instances);
 
 
-/** \ingroup CIP_API 
- * \brief Create one instance of a given class with a certain instance number
+/** @ingroup CIP_API
+ * @brief Create one instance of a given class with a certain instance number
  *
  *
  * This function can be used for creating out of order instance numbers
  * This function can be used for creating out of order instance numbers
  * @param pa_pstCIPClass the class the instance should be created for
  * @param pa_pstCIPClass the class the instance should be created for
  * @param pa_nInstanceId the instance id of the created instance
  * @param pa_nInstanceId the instance id of the created instance
- * @return pointer to the created instance, if an instance with the given id 
+ * @return pointer to the created instance, if an instance with the given id
  *         already exists the existing is returned an no new instance is created
  *         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);
+CipInstance *AddCIPInstance(CipClass *cip_class_to_add_instance,
+                            EipUint32 pa_nInstanceId);
 
 
-/*! \ingroup CIP_API 
- * \brief Insert an attribute in an instance of a CIP class
+/** @ingroup CIP_API
+ * @brief Insert an attribute in an instance of a CIP class
  *
  *
  *  Note that attributes are stored in an array pointer in the instance
  *  Note that attributes are stored in an array pointer in the instance
  *  the attributes array is not expandable if you insert an attributes that has
  *  the attributes array is not expandable if you insert an attributes that has
@@ -195,548 +194,639 @@ addCIPInstance(S_CIP_Class * pa_pstCIPClass, EIP_UINT32 pa_nInstanceId);
  *
  *
  *  @param pa_pInstance pointer to CIP class. (may be also instance 0)
  *  @param pa_pInstance pointer to CIP class. (may be also instance 0)
  *  @param pa_nAttributeNr number of attribute to be inserted.
  *  @param pa_nAttributeNr number of attribute to be inserted.
- *  @param pa_nCIP_Type type of attribute to be inserted.
- *  @param pa_pt2data pointer to data of attribute.
- *  @param pa_bCIP_Flags flags to indicate set-ability and get-ability of attribute.
+ *  @param cip_data_type type of attribute to be inserted.
+ *  @param cip_data pointer to data of attribute.
+ *  @param cip_flags flags to indicate set-ability and get-ability of attribute.
  */
  */
-void
-insertAttribute(S_CIP_Instance *pa_pInstance, EIP_UINT16 pa_nAttributeNr,
-    EIP_UINT8 pa_nCIP_Type, void* pa_pt2data, EIP_BYTE pa_bCIP_Flags);
+void InsertAttribute(CipInstance *cip_instance, EipUint16 attribute_number,
+                     EipUint8 cip_data_type, void *cip_data, EipByte cip_flags);
 
 
-/** \ingroup CIP_API 
- * \brief Insert a service in an instance of a CIP object
+/** @ingroup CIP_API
+ * @brief Insert a service in an instance of a CIP object
  *
  *
  *  Note that services are stored in an array pointer in the class object
  *  Note that services are stored in an array pointer in the class object
- *  the service array is not expandable if you insert a service that has 
+ *  the service array is not expandable if you insert a service that has
  *  already been defined, the previous service will be replaced
  *  already been defined, the previous service will be replaced
- * 
- * @param pa_pClass pointer to CIP object. (may be also instance 0)
- * @param pa_nServiceNr service code of service to be inserted.
- * @param pa_ptfuncService pointer to function which represents the service.
- * @param name name of the service
+ *
+ * @param cip_class_to_add_service pointer to CIP object. (may be also
+ * instance# 0)
+ * @param service_code service code of service to be inserted.
+ * @param service_function pointer to function which represents the service.
+ * @param service_name name of the service
  */
  */
-void
-insertService(S_CIP_Class *pa_pClass, EIP_UINT8 pa_nServiceNr,
-    TCIPServiceFunc pa_ptfuncService, char *name);
+void InsertService(CipClass *cip_class_to_add_service, EipUint8 service_code,
+                   CipServiceFunction service_function, char *service_name);
 
 
-/** \ingroup CIP_API 
- * \brief Produce the data according to CIP encoding onto the message buffer.
+/** @ingroup CIP_API
+ * @brief Produce the data according to CIP encoding onto the message buffer.
  *
  *
  * This function may be used in own services for sending data back to the
  * This function may be used in own services for sending data back to the
  * requester (e.g., getAttributeSingle for special structs).
  * requester (e.g., getAttributeSingle for special structs).
- *  @param pa_nCIP_Type the cip type to encode
- *  @param pa_pt2data pointer to data value.
- *  @param pa_pnMsg pointer to memory where response should be written
+ *  @param cip_data_type the cip type to encode
+ *  @param cip_data pointer to data value.
+ *  @param cip_message pointer to memory where response should be written
  *  @return length of attribute in bytes
  *  @return length of attribute in bytes
  *          -1 .. error
  *          -1 .. error
  */
  */
-int
-encodeData(EIP_UINT8 pa_nCIP_Type, void *pa_pt2data, EIP_UINT8 **pa_pnMsg);
+int EncodeData(EipUint8 cip_data_type, void *cip_data, EipUint8 **cip_message);
 
 
-/*! \ingroup CIP_API
- * \brief Retrieve the given data according to CIP encoding from the message buffer.
+/** @ingroup CIP_API
+ * @brief Retrieve the given data according to CIP encoding from the message
+ * buffer.
  *
  *
  * This function may be used in in own services for handling data from the
  * This function may be used in in own services for handling data from the
  * requester (e.g., setAttributeSingle).
  * requester (e.g., setAttributeSingle).
- *  @param pa_nCIP_Type the cip type to decode
- *  @param pa_pt2data pointer to data value to written.
- *  @param pa_pnMsg pointer to memory where the data should be taken from
+ *  @param cip_data_type the CIP type to decode
+ *  @param cip_data pointer to data value to written.
+ *  @param cip_message pointer to memory where the data should be taken from
  *  @return length of taken bytes
  *  @return length of taken bytes
  *          -1 .. error
  *          -1 .. error
  */
  */
-int
-decodeData(EIP_UINT8 pa_nCIP_Type, void *pa_pt2data, EIP_UINT8 **pa_pnMsg);
+int DecodeData(EipUint8 cip_data_type, void *cip_data, EipUint8 **cip_message);
 
 
-/** \ingroup CIP_API
- * \brief Create an instance of an assembly object
- * 
- * @param pa_nInstanceID  instance number of the assembly object to create 
- * @param pa_data         pointer to the data the assembly object should contain
- * @param pa_datalength   length of the assembly object's data
+/** @ingroup CIP_API
+ * @brief Create an instance of an assembly object
+ *
+ * @param instance_number  instance number of the assembly object to create
+ * @param data         pointer to the data the assembly object should contain
+ * @param data_length   length of the assembly object's data
  * @return pointer to the instance of the created assembly object. NULL on error
  * @return pointer to the instance of the created assembly object. NULL on error
  *
  *
  * Assembly Objects for Configuration Data:
  * Assembly Objects for Configuration Data:
  *
  *
- * The CIP stack treats configuration assembly objects the same way as any other assembly object. 
- * 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.
+ * The CIP stack treats configuration assembly objects the same way as any other
+ * assembly object.
+ * 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_UINT32 pa_nInstanceID, EIP_BYTE *pa_data,
-    EIP_UINT16 pa_datalength);
+CipInstance *CreateAssemblyObject(EipUint32 instance_number, EipByte *data,
+                                  EipUint16 data_length);
 
 
+struct connection_object;
 
 
-struct CIP_ConnectionObject;
+/** @ingroup CIP_API
+ * @brief Function prototype for handling the opening of connections
+ *
+ * @param connection_object The connection object which is opening the
+ * connection
+ * @param extended_error_code The returned error code of the connection object
+ *
+ * @return CIP error code
+ */
+typedef int (*OpenConnectionFunction)(
+    struct connection_object *connection_object, EipUint16 *extended_error_code);
 
 
+/** @ingroup CIP_API
+ * @brief Function prototype for handling the closing of connections
+ *
+ * @param connection_object The connection object which is closing the
+ * connection
+ */
+typedef void (*ConnectionCloseFunction)(
+    struct connection_object *connection_object);
+
+/** @ingroup CIP_API
+ * @brief Function prototype for handling the timeout of connections
+ *
+ * @param connection_object The connection object which connection timed out
+ */
+typedef void (*ConnectionTimeoutFunction)(
+    struct connection_object *connection_object);
 
 
-typedef int (*TConnOpenFunc)(struct CIP_ConnectionObject *pa_pstConnObj, EIP_UINT16 *pa_pnExtendedError);
-typedef void (*TConnCloseFunc)(struct CIP_ConnectionObject *pa_pstConnObj);
-typedef void (*TConnTimeOutFunc)(struct CIP_ConnectionObject *pa_pstConnObj);
-typedef EIP_STATUS (*TConnSendDataFunc)(struct CIP_ConnectionObject *pa_pstConnection);
-typedef EIP_STATUS (*TConnRecvDataFunc)(struct CIP_ConnectionObject *pa_pstConnection, EIP_UINT8 * pa_pnData, EIP_UINT16 pa_nDataLength);
+/** @ingroup CIP_API
+ * @brief Function prototype for sending data via a connection
+ *
+ * @param connection_object The connection object which connection timed out
+ *
+ * @return EIP stack status
+ */
+typedef EipStatus (*ConnectionSendDataFunction)(
+    struct connection_object *connection_object);
 
 
+/** @ingroup CIP_API
+ * @brief Function prototype for receiving data via a connection
+ *
+ * @param connection_object The connection object which connection timed out
+ * @param data The payload of the CIP message
+ * @param data_length Length of the payload
+ *
+ * @return Stack status
+ */
+typedef EipStatus (*ConnectionReceiveDataFunction)(
+    struct connection_object *connection_object, EipUint8 *data,
+    EipUint16 data_length);
 
 
-/*!\ingroup CIP_API
- * \brief register open functions for an specific object.
+/** @ingroup CIP_API
+ * @brief register open functions for an specific object.
  *
  *
- * With this function any object can be enabled to be a target for forward open/close
- * request.
- * @param pa_nClassId    the class id
- * @param pa_pfOpenFunc   pointer to the function handling the open process
+ * With this function any object can be enabled to be a target for forward
+ * open/close request.
+ * @param class_id The class ID
+ * @param open_connection_function   pointer to the function handling the open
+ * process
  * @return EIP_OK on success
  * @return EIP_OK on success
  */
  */
-EIP_STATUS
-addConnectableObject(EIP_UINT32 pa_nClassId, TConnOpenFunc pa_pfOpenFunc);
+EipStatus
+AddConnectableObject(EipUint32 class_id,
+                     OpenConnectionFunction open_connection_function);
 
 
-/** \ingroup CIP_API
- * \brief Configures the connection point for an exclusive owner connection.
+/** @ingroup CIP_API
+ * @brief Configures the connection point for an exclusive owner connection.
  *
  *
- * @param pa_unConnNum the number of the exclusive owner connection. The
+ * @param connection_number The number of the exclusive owner connection. The
  *        enumeration starts with 0. Has to be smaller than
  *        enumeration starts with 0. Has to be smaller than
  *        OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS.
  *        OPENER_CIP_NUM_EXLUSIVE_OWNER_CONNS.
- * @param pa_unOutputAssembly the O-to-T point to be used for this connection
- * @param pa_unInputAssembly the T-to-O point to be used for this connection
- * @param pa_unConfigAssembly the configuration point to be used for this connection
+ * @param output_assembly_id ID of the O-to-T point to be used for this
+ * connection
+ * @param input_assembly_id ID of the T-to-O point to be used for this
+ * connection
+ * @param configuration_assembly_id ID of the configuration point to be used for
+ * this connection
  */
  */
-void
-configureExclusiveOwnerConnectionPoint(unsigned int pa_unConnNum,
-    unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly,
-    unsigned int pa_unConfigAssembly);
+void ConfigureExclusiveOwnerConnectionPoint(
+    unsigned int connection_number, unsigned int output_assembly_id,
+    unsigned int input_assembly_id, unsigned int configuration_assembly_id);
 
 
-/** \ingroup CIP_API
- * \brief Configures the connection point for an input only connection.
+/** @ingroup CIP_API
+ * @brief Configures the connection point for an input only connection.
  *
  *
- * @param pa_unConnNum the number of the input only connection. The
+ * @param connection_number The number of the input only connection. The
  *        enumeration starts with 0. Has to be smaller than
  *        enumeration starts with 0. Has to be smaller than
  *        OPENER_CIP_NUM_INPUT_ONLY_CONNS.
  *        OPENER_CIP_NUM_INPUT_ONLY_CONNS.
- * @param pa_unOutputAssembly the O-to-T point to be used for this connection
- * @param pa_unInputAssembly the T-to-O point to be used for this connection
- * @param pa_unConfigAssembly the configuration point to be used for this connection
- */
-void
-configureInputOnlyConnectionPoint(unsigned int pa_unConnNum,
-    unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly,
-    unsigned int pa_unConfigAssembly);
+ * @param output_assembly_id ID of the O-to-T point to be used for this
+ * connection
+ * @param input_assembly_id ID of the T-to-O point to be used for this
+ * connection
+ * @param configuration_assembly_id ID of the configuration point to be used for
+ *this connection
+ */
+void ConfigureInputOnlyConnectionPoint(unsigned int connection_number,
+                                       unsigned int output_assembly_id,
+                                       unsigned int input_assembly_id,
+                                       unsigned int configuration_assembly_id);
 
 
 /** \ingroup CIP_API
 /** \ingroup CIP_API
  * \brief Configures the connection point for a listen only connection.
  * \brief Configures the connection point for a listen only connection.
  *
  *
- * @param pa_unConnNum the number of the input only connection. The
+ * @param connection_number The number of the input only connection. The
  *        enumeration starts with 0. Has to be smaller than
  *        enumeration starts with 0. Has to be smaller than
  *        OPENER_CIP_NUM_LISTEN_ONLY_CONNS.
  *        OPENER_CIP_NUM_LISTEN_ONLY_CONNS.
- * @param pa_unOutputAssembly the O-to-T point to be used for this connection
- * @param pa_unInputAssembly the T-to-O point to be used for this connection
- * @param pa_unConfigAssembly the configuration point to be used for this connection
- */
-void
-configureListenOnlyConnectionPoint(unsigned int pa_unConnNum,
-    unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly,
-    unsigned int pa_unConfigAssembly);
-
-/** \ingroup CIP_API 
- * \brief Notify the encapsulation layer that an explicit message has been received via TCP.
- * 
- * @param pa_socket socket handle from which data is received.
- * @param pa_buf buffer that contains the received data. This buffer will also contain the
- *       response if one is to be sent.  
- * @param pa_length length of the data in pa_buf.
- * @param pa_nRemainingBytes return how many bytes of the input are left over after we're done here
+ * @param output_assembly_id ID of the O-to-T point to be used for this
+ * connection
+ * @param input_assembly_id ID of the T-to-O point to be used for this
+ * connection
+ * @param configuration_assembly_id ID of the configuration point to be used for
+ * this connection
+ */
+void ConfigureListenOnlyConnectionPoint(unsigned int connection_number,
+                                        unsigned int output_assembly_id,
+                                        unsigned int input_assembly_id,
+                                        unsigned int configuration_assembly_id);
+
+/** @ingroup CIP_API
+ * @brief Notify the encapsulation layer that an explicit message has been
+ * received via TCP.
+ *
+ * @param socket_handle socket handle from which data is received.
+ * @param buffer buffer that contains the received data. This buffer will also
+ * contain the response if one is to be sent.
+ * @param buffer length of the data in buffer.
+ * @param number_of_remaining_bytes 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
  * @return length of reply that need to be sent back
  */
  */
-int
-handleReceivedExplictTCPData(int pa_socket, EIP_UINT8* pa_buf,
-    unsigned int pa_length, int *pa_nRemainingBytes);
-
-/** \ingroup CIP_API
- * \brief Notify the encapsulation layer that an explicit message has been received via UDP.
- *
- * @param pa_socket socket handle from which data is received.
- * @param pa_pstFromAddr remote address from which the data is received.
- * @param pa_buf buffer that contains the received data. This buffer will also contain the
- *       response if one is to be sent.
- * @param pa_length length of the data in pa_buf.
- * @param pa_nRemainingBytes return how many bytes of the input are left over after we're done here
+int HandleReceivedExplictTcpData(int socket, EipUint8 *buffer,
+                                 unsigned int buffer_length,
+                                 int *number_of_remaining_bytes);
+
+/** @ingroup CIP_API
+ * @brief Notify the encapsulation layer that an explicit message has been
+ * received via UDP.
+ *
+ * @param socket_handle socket handle from which data is received.
+ * @param from_address remote address from which the data is received.
+ * @param buffer buffer that contains the received data. This buffer will also
+ * contain the response if one is to be sent.
+ * @param buffer_length length of the data in buffer.
+ * @param number_of_remaining_bytes 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
  * @return length of reply that need to be sent back
  */
  */
-int
-handleReceivedExplictUDPData(int pa_socket, struct sockaddr_in *pa_pstFromAddr, EIP_UINT8* pa_buf,
-    unsigned int pa_length, int *pa_nRemainingBytes);
+int HandleReceivedExplictUdpData(int socket, struct sockaddr_in *from_address,
+                                 EipUint8 *buffer, unsigned int buffer_length,
+                                 int *number_of_remaining_bytes);
 
 
-/*! \ingroup CIP_API
- *  \brief Notify the connection manager that data for a connection has been received.
+/** @ingroup CIP_API
+ *  @brief Notify the connection manager that data for a connection has been
+ *  received.
  *
  *
  *  This function should be invoked by the network layer.
  *  This function should be invoked by the network layer.
- *  @param pa_pnData pointer to the buffer of data that has been received
- *  @param pa_nDataLength number of bytes in the data buffer
- *  @param pa_pstFromAddr address from which the data has been received. Only
+ *  @param received_data pointer to the buffer of data that has been received
+ *  @param received_data_length number of bytes in the data buffer
+ *  @param from_address address from which the data has been received. Only
  *           data from the connections originator may be accepted. Avoids
  *           data from the connections originator may be accepted. Avoids
  *           connection hijacking
  *           connection hijacking
  *  @return EIP_OK on success
  *  @return EIP_OK on success
  */
  */
-EIP_STATUS
-handleReceivedConnectedData(EIP_UINT8 *pa_pnData, int pa_nDataLength,
-    struct sockaddr_in *pa_pstFromAddr);
+EipStatus
+HandleReceivedConnectedData(EipUint8 *received_data, int received_data_length,
+                            struct sockaddr_in *from_address);
 
 
-/*! \ingroup CIP_API
- * \brief Check if any of the connection timers (TransmissionTrigger or WarchdogTimeout) have timed out.
+/** @ingroup CIP_API
+ * @brief Check if any of the connection timers (TransmissionTrigger or
+ * WatchdogTimeout) have timed out.
+ *
+ * If the a timeout occurs the function performs the necessary action. This
+ * function should be called periodically once every OPENER_TIMER_TICK
+ * milliseconds.
  *
  *
- * If the a timeout occurs the function performs the necessary action. This function should be called periodically once every
- * OPENER_TIMER_TICK ms. 
- * 
  * @return EIP_OK on success
  * @return EIP_OK on success
  */
  */
-EIP_STATUS
-manageConnections(void);
+EipStatus
+ManageConnections(void);
 
 
-/*! \ingroup CIP_API
- * \brief Trigger the production of an application triggered connection.
+/** @ingroup CIP_API
+ * @brief Trigger the production of an application triggered connection.
  *
  *
  * This will issue the production of the specified connection at the next
  * This will issue the production of the specified connection at the next
  * possible occasion. Depending on the values for the RPI and the production
  * possible occasion. Depending on the values for the RPI and the production
  * inhibit timer. The application is informed via the
  * inhibit timer. The application is informed via the
- * EIP_BOOL8 IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance)
- * callback function when the production will happen. This function should only be
- * invoked from void IApp_HandleApplication(void).
+ * EIP_BOOL8 BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance)
+ * callback function when the production will happen. This function should only
+ * be invoked from void HandleApplication(void).
  *
  *
  * The connection can only be triggered if the application is established and it
  * The connection can only be triggered if the application is established and it
  * is of application application triggered type.
  * is of application application triggered type.
  *
  *
- * @param pa_unOutputAssembly the output assembly connection point of the connection
- * @param pa_unInputAssembly the input assembly connection point of the connection
+ * @param output_assembly_id the output assembly connection point of the
+ * connection
+ * @param input_assembly_id the input assembly connection point of the
+ * connection
  * @return EIP_OK on success
  * @return EIP_OK on success
  */
  */
-EIP_STATUS
-triggerConnections(unsigned int pa_unOutputAssembly,
-    unsigned int pa_unInputAssembly);
+EipStatus
+TriggerConnections(unsigned int output_assembly_id,
+                   unsigned int input_assembly_id);
 
 
-/*! \ingroup CIP_API
- * \brief Inform the encapsulation layer that the remote host has closed the connection.
+/** @ingroup CIP_API
+ * @brief Inform the encapsulation layer that the remote host has closed the
+ * connection.
  *
  *
- * According to the specifications that will clean up and close the session in the encapsulation layer.
- * @param pa_nSocket the handler to the socket of the closed connection
+ * According to the specifications that will clean up and close the session in
+ * the encapsulation layer.
+ * @param socket_handle the handler to the socket of the closed connection
  */
  */
-void
-closeSession(int pa_nSocket);
+void CloseSession(int socket);
 
 
-/**  \defgroup CIP_CALLBACK_API Callback Functions Demanded by OpENer
- * \ingroup CIP_API
- * 
- * \brief These functions have to implemented in order to give the OpENer a
+/**  @defgroup CIP_CALLBACK_API Callback Functions Demanded by OpENer
+ * @ingroup CIP_API
+ *
+ * @brief These functions have to implemented in order to give the OpENer a
  * method to inform the application on certain state changes.
  * method to inform the application on certain state changes.
  */
  */
 
 
-/** \ingroup CIP_CALLBACK_API 
- * \brief Callback for the application initialization
+/** @ingroup CIP_CALLBACK_API
+ * @brief Callback for the application initialization
  *
  *
  * This function will be called by the CIP stack after it has finished its
  * This function will be called by the CIP stack after it has finished its
  * initialization. In this function the user can setup all CIP objects she
  * initialization. In this function the user can setup all CIP objects she
  * likes to have.
  * likes to have.
  *
  *
- * This function is provided for convenience reasons. After the void CIP_Init(void)
+ * This function is provided for convenience reasons. After the void
+ * CipStackInit(void)
  * function has finished it is okay to also generate your CIP objects.
  * function has finished it is okay to also generate your CIP objects.
  *  return status EIP_ERROR .. error
  *  return status EIP_ERROR .. error
  *                EIP_OK ... successful finish
  *                EIP_OK ... successful finish
  */
  */
-EIP_STATUS
-IApp_Init(void);
+EipStatus
+ApplicationInitialization(void);
 
 
-
-/**\ingroup CIP_CALLBACK_API
- * \brief Allow the device specific application to perform its execution
+/** @ingroup CIP_CALLBACK_API
+ * @brief Allow the device specific application to perform its execution
  *
  *
  * This function will be executed by the stack at the beginning of each
  * This function will be executed by the stack at the beginning of each
- * execution of EIP_STATUS manageConnections(void). It allows to implement
+ * execution of EIP_STATUS ManageConnections(void). It allows to implement
  * device specific application functions. Execution within this function should
  * device specific application functions. Execution within this function should
  * be short.
  * be short.
- *
  */
  */
-void IApp_HandleApplication(void);
+void HandleApplication(void);
 
 
-/** \ingroup CIP_CALLBACK_API
- * \brief Inform the application on changes occurred for a connection
+/** @ingroup CIP_CALLBACK_API
+ * @brief Inform the application on changes occurred for a connection
  *
  *
- * @param pa_unOutputAssembly the output assembly connection point of the connection
- * @param pa_unInputAssembly the input assembly connection point of the connection
- * @param pa_eIOConnectionEvent information on the change occurred
+ * @param output_assembly_id the output assembly connection point of the
+ * connection
+ * @param input_assembly_id the input assembly connection point of the
+ * connection
+ * @param io_connection_event information on the change occurred
  */
  */
-void
-IApp_IOConnectionEvent(unsigned int pa_unOutputAssembly,
-    unsigned int pa_unInputAssembly, EIOConnectionEvent pa_eIOConnectionEvent);
+void IoConnectionEvent(unsigned int output_assembly_id,
+                       unsigned int input_assembly_id,
+                       IoConnectionEvents io_connection_event);
 
 
-/** \ingroup CIP_CALLBACK_API 
- * \brief Call back function to inform application on received data for an assembly object.
- * 
+/** @ingroup CIP_CALLBACK_API
+ * @brief Call back function to inform application on received data for an
+ * assembly object.
+ *
  * This function has to be implemented by the user of the CIP-stack.
  * This function has to be implemented by the user of the CIP-stack.
- * @param pa_pstInstance pointer to the assembly object data was received for
+ * @param instance pointer to the assembly object data was received for
  * @return Information if the data could be processed
  * @return Information if the data could be processed
- *     - EIP_OK the received data was ok 
- *     - EIP_ERROR the received data was wrong (especially needed for configuration data assembly
- *                 objects) 
- * 
+ *     - EIP_OK the received data was ok
+ *     - EIP_ERROR the received data was wrong (especially needed for
+ * configuration data assembly objects)
+ *
  * Assembly Objects for Configuration Data:
  * Assembly Objects for Configuration Data:
- * 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.
+ * 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);
-/** \ingroup CIP_CALLBACK_API 
- * \brief Inform the application that the data of an assembly
+EipStatus
+AfterAssemblyDataReceived(CipInstance *instance);
+
+/** @ingroup CIP_CALLBACK_API
+ * @brief Inform the application that the data of an assembly
  * object will be sent.
  * object will be sent.
  *
  *
- * Within this function the user can update the data of the assembly object before it
- * gets sent. The application can inform the application if data has changed.
- * @param pa_pstInstance instance of assembly object that should send data.
+ * Within this function the user can update the data of the assembly object
+ * before it gets sent. The application can inform the application if data has
+ * changed.
+ * @param instance instance of assembly object that should send data.
  * @return data has changed:
  * @return data has changed:
  *          - true assembly data has changed
  *          - true assembly data has changed
  *          - false assembly data has not changed
  *          - false assembly data has not changed
  */
  */
-EIP_BOOL8
-IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance);
+EipBool8
+BeforeAssemblyDataSend(CipInstance *instance);
 
 
-/** \ingroup CIP_CALLBACK_API 
- * \brief Emulate as close a possible a power cycle of the device
- *  
+/** @ingroup CIP_CALLBACK_API
+ * @brief Emulate as close a possible a power cycle of the device
+ *
  * @return if the service is supported the function will not return.
  * @return if the service is supported the function will not return.
  *     EIP_ERROR if this service is not supported
  *     EIP_ERROR if this service is not supported
  */
  */
-EIP_STATUS
-IApp_ResetDevice(void);
+EipStatus
+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
- * 
- * return if the service is supported the function will not return.
+/** @ingroup CIP_CALLBACK_API
+ * @brief Reset the device to the initial configuration and emulate as close as
+ * possible a power cycle of the device
+ *
+ * @return if the service is supported the function will not return.
  *     EIP_ERROR if this service is not supported
  *     EIP_ERROR if this service is not supported
  */
  */
-EIP_STATUS
-IApp_ResetDeviceToInitialConfiguration(void);
+EipStatus
+ResetDeviceToInitialConfiguration(void);
 
 
-/**\ingroup CIP_CALLBACK_API 
- * \brief Allocate memory for the cip stack
- * 
+/** @ingroup CIP_CALLBACK_API
+ * @brief Allocate memory for the CIP stack
+ *
  * emulate the common c-library function calloc
  * emulate the common c-library function calloc
- * In OpENer allocation only happens on application startup and on class/instance creation
- * and configuration not on during operation (processing messages)
- * @param pa_nNumberOfElements number of elements to allocate
- * @param pa_nSizeOfElement size in bytes of one element
- * return pointer to the allocated memory, 0 on error
+ * In OpENer allocation only happens on application startup and on
+ * class/instance creation and configuration not on during operation
+ * (processing messages).
+ * @param number_of_elements number of elements to allocate
+ * @param size_of_element 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 *CipCalloc(unsigned int number_of_elements, unsigned int size_of_element);
 
 
-/**\ingroup CIP_CALLBACK_API 
- * \brief Free memory allocated by the OpENer
+/** @ingroup CIP_CALLBACK_API
+ * @brief Free memory allocated by the OpENer
  *
  *
  * emulate the common c-library function free
  * emulate the common c-library function free
  * @param pa_poData pointer to the allocated memory
  * @param pa_poData pointer to the allocated memory
- * return
- */
-void
-IApp_CipFree(void *pa_poData);
-
-/**\ingroup CIP_CALLBACK_API
- * \brief Inform the application that the Run/Idle State has been changed
- *  by the originator. 
- * 
- * 
- * @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);
-
-/**\ingroup CIP_CALLBACK_API 
- * \brief create a producing or consuming UDP socket
- * 
- * @param pa_nDirection PRODCUER or CONSUMER
- * @param pa_pstAddr pointer to the address holding structure
- *     Attention: For producing point-to-point connection the pa_pstAddr->sin_addr.s_addr
- *         member is set to 0 by OpENer. The network layer of the application has
- *         to set the correct address of the originator.
- *     Attention: For consuming connection the network layer has to set the pa_pstAddr->sin_addr.s_addr
- *         to the correct address of the originator.
- * FIXME add an additional parameter that can be used by the CIP stack to request the originators sockaddr_in
- * data.
+ */
+void CipFree(void *data);
+
+/** @ingroup CIP_CALLBACK_API
+ * @brief Inform the application that the Run/Idle State has been changed
+ * by the originator.
+ *
+ * @param run_idle_value the current value of the run/idle flag according to CIP
+ * spec Vol 1 3-6.5
+ */
+void RunIdleChanged(EipUint32 run_idle_value);
+
+/** @ingroup CIP_CALLBACK_API
+ * @brief create a producing or consuming UDP socket
+ *
+ * @param communication_direction PRODCUER or CONSUMER
+ * @param socket_data pointer to the address holding structure
+ *     Attention: For producing point-to-point connection the
+ *     *pa_pstAddr->sin_addr.s_addr member is set to 0 by OpENer. The network
+ *     layer of the application has to set the correct address of the
+ *     originator.
+ *     Attention: For consuming connection the network layer has to set the
+ * pa_pstAddr->sin_addr.s_addr to the correct address of the originator.
+ * FIXME add an additional parameter that can be used by the CIP stack to
+ * request the originators sockaddr_in data.
  * @return socket identifier on success
  * @return socket identifier on success
- *         -1 on error 
- */
-int
-IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr);
-
-/**\ingroup CIP_CALLBACK_API 
- * \brief create a producing or consuming UDP socket
- * 
- * @param pa_pstAddr pointer to the sendto address
- * @param pa_nSockFd socket descriptor to send on
- * @param pa_acData pointer to the data to send
- * @param pa_nDataLength length of the data to send
+ *         -1 on error
+ */
+int CreateUdpSocket(UdpCommuncationDirection communication_direction,
+                    struct sockaddr_in *socket_data);
+
+/** @ingroup CIP_CALLBACK_API
+ * @brief create a producing or consuming UDP socket
+ *
+ * @param socket_data pointer to the "send to" address
+ * @param socket_handle socket descriptor to send on
+ * @param data pointer to the data to send
+ * @param data_length length of the data to send
  * @return  EIP_SUCCESS on success
  * @return  EIP_SUCCESS on success
  */
  */
-EIP_STATUS
-IApp_SendUDPData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
-    EIP_UINT8 *pa_acData, EIP_UINT16 pa_nDataLength);
+EipStatus
+SendUdpData(struct sockaddr_in *socket_data, int socket, EipUint8 *data,
+            EipUint16 data_length);
 
 
-/**\ingroup CIP_CALLBACK_API 
- * \brief Close the given socket and clean up the stack 
- * 
- * @param pa_nSockFd socket descriptor to close
+/** @ingroup CIP_CALLBACK_API
+ * @brief Close the given socket and clean up the stack
+ *
+ * @param socket_handle socket descriptor to close
  */
  */
-void
-IApp_CloseSocket(int pa_nSockFd);
+void CloseSocket(int socket);
 
 
-/*! \mainpage OpENer - Open Source EtherNet/IP(TM) Communication Stack Documentation
+/** @mainpage OpENer - Open Source EtherNet/IP(TM) Communication Stack
+ *Documentation
  *
  *
  * EtherNet/IP stack for adapter devices (connection target); supports multiple
  * EtherNet/IP stack for adapter devices (connection target); supports multiple
  * I/O and explicit connections; includes features and objects required by the
  * I/O and explicit connections; includes features and objects required by the
  * CIP specification to enable devices to comply with ODVA's conformance/
  * CIP specification to enable devices to comply with ODVA's conformance/
  * interoperability tests.
  * interoperability tests.
- * 
- * \section intro_sec Introduction
+ *
+ * @section intro_sec Introduction
  *
  *
  * This is the introduction.
  * This is the introduction.
  *
  *
- * \section install_sec Building
+ * @section install_sec Building
  * How to compile, install and run OpENer on a specific platform.
  * How to compile, install and run OpENer on a specific platform.
- * \subsection build_req_sec Requirements
- * OpENer has been developed to be highly portable. The default version targets PCs
- * with a POSIX operating system and a BSD-socket network interface. To test this
- * version we recommend a Linux PC or Windows with Cygwin (www.cygwin.com)
- * installed. You will need to have the following installed:
+ *
+ * @subsection build_req_sec Requirements
+ * OpENer has been developed to be highly portable. The default version targets
+ * PCs with a POSIX operating system and a BSD-socket network interface. To
+ * test this version we recommend a Linux PC or Windows with Cygwin installed.
+ *  You will need to have the following installed:
  *   - gcc, make, binutils, etc.
  *   - gcc, make, binutils, etc.
- * 
- * for normal building. These should be installed on most Linux installations and
- * are part of the development packages of cygwin.
- * 
- * For the development itself we recommend the use of Eclipse with the CTD plugin
- * (www.eclipse.org). For your convenience OpENer already comes with an Eclipse
- * project file. This allows to just import the OpENer source tree into Eclipse.
- * 
- * \subsection compile_pcs_sec Compile for PCs
+ *
+ * for normal building. These should be installed on most Linux installations
+ * and are part of the development packages of Cygwin.
+ *
+ * For the development itself we recommend the use of Eclipse with the CDT
+ * plugin. For your convenience OpENer already comes with an Eclipse project
+ * file. This allows to just import the OpENer source tree into Eclipse.
+ *
+ * @subsection compile_pcs_sec Compile for PCs
  *   -# Directly in the shell
  *   -# Directly in the shell
  *       -# Go into the bin/pc directory
  *       -# Go into the bin/pc directory
  *       -# Invoke make
  *       -# Invoke make
  *       -# For invoking opener type:\n
  *       -# For invoking opener type:\n
- *          ./opener ipaddress subnetmask gateway domainname hostaddress macaddress\n
- *          e.g., ./opener 192.168.0.2 255.255.255.0 192.168.0.1 test.com testdevice 00 15 C5 BF D0 87 
+ *          ./opener ipaddress subnetmask gateway domainname hostaddress
+ * macaddress\n
+ *          e.g., ./opener 192.168.0.2 255.255.255.0 192.168.0.1 test.com
+ * testdevice 00 15 C5 BF D0 87
  *   -# Within Eclipse
  *   -# Within Eclipse
  *       -# Import the project
  *       -# Import the project
  *       -# Go to the bin/pc folder in the make targets view
  *       -# Go to the bin/pc folder in the make targets view
  *       -# Choose all from the make targets
  *       -# Choose all from the make targets
  *       -# The resulting executable will be in the directory
  *       -# The resulting executable will be in the directory
  *           ./bin/pc
  *           ./bin/pc
- *       -# The command line parameters can be set in the run configuration dialog of Eclipse
- * 
- * \section further_reading_sec Further Topics
- *   - \ref porting
- *   - \ref extending
- *   - \ref license 
- * 
- * \page porting Porting OpENer
- * \section gen_config_section General Stack Configuration
- * The general stack properties have to be defined prior to building your 
- * production. This is done by providing a file called opener_user_conf.h. An 
- * example file can be found in the src/ports/platform-pc directory. The 
- * documentation of the example file for the necessary configuration options: 
+ *       -# The command line parameters can be set in the run configuration
+ * dialog of Eclipse
+ *
+ * @section further_reading_sec Further Topics
+ *   - @ref porting
+ *   - @ref extending
+ *   - @ref license
+ *
+ * @page porting Porting OpENer
+ * @section gen_config_section General Stack Configuration
+ * The general stack properties have to be defined prior to building your
+ * production. This is done by providing a file called opener_user_conf.h. An
+ * example file can be found in the src/ports/platform-pc directory. The
+ * documentation of the example file for the necessary configuration options:
  * opener_user_conf.h
  * opener_user_conf.h
- * 
- * \copydoc opener_user_conf.h
- * 
- * \section startup_sec Startup Sequence
- * During startup of your EtherNet/IP(TM) device the following steps have to be 
+ *
+ * @copydoc opener_user_conf.h
+ *
+ * @section startup_sec Startup Sequence
+ * During startup of your EtherNet/IP(TM) device the following steps have to be
  * performed:
  * performed:
  *   -# Configure the network properties:\n
  *   -# Configure the network properties:\n
- *       With the following functions the network interface of OpENer is 
+ *       With the following functions the network interface of OpENer is
  *       configured:
  *       configured:
- *        - EIP_STATUS configureNetworkInterface(const char *pa_acIpAdress, const char *pa_acSubNetMask, const char *pa_acGateway)
- *        - void configureMACAddress(const EIP_UINT8 *pa_acMACAddress)
- *        - void configureDomainName(const char *pa_acDomainName)
- *        - void configureHostName(const char *pa_acHostName)
+ *        - EIP_STATUS ConfigureNetworkInterface(const char *ip_address,
+ *        const char *subnet_mask, const char *gateway_address)
+ *        - void ConfigureMACAddress(const EIP_UINT8 *mac_address)
+ *        - void ConfigureDomainName(const char *domain_name)
+ *        - void ConfigureHostName(const char *host_name)
  *        .
  *        .
- *       Depending on your platform these data can come from a configuration 
- *       file or from operating system functions. If these values should be 
+ *       Depending on your platform these data can come from a configuration
+ *       file or from operating system functions. If these values should be
  *       setable remotely via explicit messages the SetAttributeSingle functions
  *       setable remotely via explicit messages the SetAttributeSingle functions
  *       of the EtherNetLink and the TCPIPInterface object have to be adapted.
  *       of the EtherNetLink and the TCPIPInterface object have to be adapted.
  *   -# Set the device's serial number\n
  *   -# Set the device's serial number\n
  *      According to the CIP specification a device vendor has to ensure that
  *      According to the CIP specification a device vendor has to ensure that
  *      each of its devices has a unique 32Bit device id. You can set it with
  *      each of its devices has a unique 32Bit device id. You can set it with
  *      the function:
  *      the function:
- *       - void setDeviceSerialNumber(EIP_UINT32 pa_nSerialNumber)
+ *       - void setDeviceSerialNumber(EIP_UINT32 serial_number)
  *   -# Initialize OpENer: \n
  *   -# Initialize OpENer: \n
- *      With the function CIP_Init(EIP_UINT16 pa_nUniqueConnID) the internal data structures of opener are
- *      correctly setup. After this step own CIP objects and Assembly objects 
- *      instances may be created. For your convenience we provide the call-back 
- *      function IApp_Init(void). This call back function is called when the stack is
- *      ready to receive application specific CIP objects.
+ *      With the function CipStackInit(EIP_UINT16 unique_connection_id) the
+ *      internal data structures of opener are correctly setup. After this
+ *      step own CIP objects and Assembly objects instances may be created. For
+ *      your convenience we provide the call-back function
+ *      ApplicationInitialization. This call back function is called when the
+ * stack is ready to receive application specific CIP objects.
  *   -# Create Application Specific CIP Objects:\n
  *   -# Create Application Specific CIP Objects:\n
- *      Within the call-back function IApp_Init(void) or after CIP_Init(void) 
- *      has finished you may create and configure any CIP object or Assembly object instances. See 
- *      the module \ref CIP_API for available functions. Currently no functions 
- *      are available to remove any created objects or instances. This is planned
+ *      Within the call-back function ApplicationInitialization(void) or
+ *      after CipStackInit(void) has finished you may create and configure any
+ *      CIP object or Assembly object instances. See the module @ref CIP_API
+ *      for available functions. Currently no functions are available to
+ *      remove any created objects or instances. This is planned
  *      for future versions.
  *      for future versions.
  *   -# Setup the listening TCP and UDP port:\n
  *   -# Setup the listening TCP and UDP port:\n
- *      THE ETHERNET/IP SPECIFICATION demands from devices to listen to TCP 
+ *      THE ETHERNET/IP SPECIFICATION demands from devices to listen to TCP
  *      connections and UDP datagrams on the port AF12hex for explicit messages.
  *      connections and UDP datagrams on the port AF12hex for explicit messages.
- *      Therefore before going into normal operation you need to configure your 
- *      network library so that TCP and UDP messages on this port will be 
+ *      Therefore before going into normal operation you need to configure your
+ *      network library so that TCP and UDP messages on this port will be
  *      received and can be hand over to the Ethernet encapsulation layer.
  *      received and can be hand over to the Ethernet encapsulation layer.
- * 
- * \section normal_op_sec Normal Operation
+ *
+ * @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:
  * specific code:
  *   - Establish connections requested on TCP port AF12hex
  *   - Establish connections requested on TCP port AF12hex
  *   - Receive explicit message data on connected TCP sockets and the UPD socket
  *   - Receive explicit message data on connected TCP sockets and the UPD socket
  *     for port AF12hex. The received data has to be hand over to Ethernet
  *     for port AF12hex. The received data has to be hand over to Ethernet
  *     encapsulation layer with the functions: \n
  *     encapsulation layer with the functions: \n
- *      int handleReceivedExplictTCPData(int pa_socket, EIP_UINT8* pa_buf, int pa_length, int *pa_nRemainingBytes),\n
- *      int handleReceivedExplictUDPData(int pa_socket, struct sockaddr_in *pa_pstFromAddr, EIP_UINT8* pa_buf, unsigned int pa_length, int *pa_nRemainingBytes).\n
+ *      int HandleReceivedExplictTCPData(int socket_handle, EIP_UINT8* buffer, int
+ * buffer_length, int *number_of_remaining_bytes),\n
+ *      int HandleReceivedExplictUDPData(int socket_handle, struct sockaddr_in
+ * *from_address, EIP_UINT8* buffer, unsigned int buffer_length, int
+ * *number_of_remaining_bytes).\n
  *     Depending if the data has been received from a TCP or from a UDP socket.
  *     Depending if the data has been received from a TCP or from a UDP socket.
  *     As a result of this function a response may have to be sent. The data to
  *     As a result of this function a response may have to be sent. The data to
  *     be sent is in the given buffer pa_buf.
  *     be sent is in the given buffer pa_buf.
- *   - Create UDP sending and receiving sockets for implicit connected messages\n
- *     OpENer will use to call-back function int IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr)
- *     for informing the platform specific code that a new connection is 
+ *   - Create UDP sending and receiving sockets for implicit connected
+ * messages\n
+ *     OpENer will use to call-back function int CreateUdpSocket(
+ *     UdpCommuncationDirection connection_direction,
+ *     struct sockaddr_in *pa_pstAddr)
+ *     for informing the platform specific code that a new connection is
  *     established and new sockets are necessary
  *     established and new sockets are necessary
  *   - Receive implicit connected data on a receiving UDP socket\n
  *   - Receive implicit connected data on a receiving UDP socket\n
- *     The received data has to be hand over to the Connection Manager Object 
- *     with the function EIP_STATUS handleReceivedConnectedData(EIP_UINT8 *pa_pnData, int pa_nDataLength)
+ *     The received data has to be hand over to the Connection Manager Object
+ *     with the function EIP_STATUS HandleReceivedConnectedData(EIP_UINT8
+ * *data, int data_length)
  *   - Close UDP and TCP sockets:
  *   - Close UDP and TCP sockets:
- *      -# Requested by OpENer through the call back function: void IApp_CloseSocket(int pa_nSockFd)
- *      -# For TCP connection when the peer closed the connection OpENer needs 
- *         to be informed to clean up internal data structures. This is done with
- *         the function void closeSession(int pa_nSocket).
+ *      -# Requested by OpENer through the call back function: void
+ * CloseSocket(int socket_handle)
+ *      -# For TCP connection when the peer closed the connection OpENer needs
+ *         to be informed to clean up internal data structures. This is done
+ *with
+ *         the function void CloseSession(int socket_handle).
  *      .
  *      .
  *   - Cyclically update the connection status:\n
  *   - Cyclically update the connection status:\n
- *     In order that OpENer can determine when to produce new data on 
- *     connections or that a connection timed out every \ref OPENER_TIMER_TICK ms the 
- *     function EIP_STATUS manageConnections(void) has to be called.
- * 
- * \section callback_funcs_sec Callback Functions
- * In order to make OpENer more platform independent and in order to inform the 
- * application on certain state changes and actions within the stack a set of 
- * call-back functions is provided. These call-back functions are declared in 
- * the file opener_api.h and have to be implemented by the application specific 
- * code. An overview and explanation of OpENer's call-back API may be found in 
- * the module \ref CIP_CALLBACK_API.
- *  
- * \page extending Extending OpENer
+ *     In order that OpENer can determine when to produce new data on
+ *     connections or that a connection timed out every @ref OPENER_TIMER_TICK
+ * milliseconds the
+ *     function EIP_STATUS ManageConnections(void) has to be called.
+ *
+ * @section callback_funcs_sec Callback Functions
+ * In order to make OpENer more platform independent and in order to inform the
+ * application on certain state changes and actions within the stack a set of
+ * call-back functions is provided. These call-back functions are declared in
+ * the file opener_api.h and have to be implemented by the application specific
+ * code. An overview and explanation of OpENer's call-back API may be found in
+ * the module @ref CIP_CALLBACK_API.
+ *
+ * @page extending Extending OpENer
  * OpENer provides an API for adding own CIP objects and instances with
  * OpENer provides an API for adding own CIP objects and instances with
  * specific services and attributes. Therefore OpENer can be easily adapted to
  * specific services and attributes. Therefore OpENer can be easily adapted to
  * support different device profiles and specific CIP objects needed for your
  * support different device profiles and specific CIP objects needed for your
  * device. The functions to be used are:
  * device. The functions to be used are:
- *   - 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_Instance * addCIPInstances(S_CIP_Class *pa_pstCIPObject, int pa_nNr_of_Instances);
- *   - S_CIP_Instance * addCIPInstance(S_CIP_Class * pa_pstCIPClass, EIP_UINT32 pa_nInstanceId);
- *   - void insertAttribute(S_CIP_Instance *pa_pInstance, EIP_UINT16 pa_nAttributeNr, EIP_UINT8 pa_nCIP_Type, void* pa_pt2data);
- *   - void insertService(S_CIP_Class *pa_pClass, EIP_UINT8 pa_nServiceNr, TCIPServiceFunc pa_ptfuncService, char *name);
- * 
- * \page license OpENer Open Source License
- * The OpENer Open Source License is an adapted BSD style license. The 
- * adaptations include the use of the term EtherNet/IP(TM) and the necessary 
- * guarding conditions for using OpENer in own products. For this please look 
+ *   - S_CIP_Class *CreateCIPClass(EIP_UINT32 class_id, int
+ * number_of_class_attributes, EIP_UINT32 class_get_attribute_all_mask, int
+ * number_of_class_services, int number_of_instance_attributes, EIP_UINT32
+ * instance_get_attribute_all_mask, int number_of_instance_services, int
+ * number_of_instances, char *class_name, EIP_UINT16 revision);
+ *   - S_CIP_Instance *AddCIPInstances(S_CIP_Class *cip_object, int
+ * number_of_instances);
+ *   - S_CIP_Instance *AddCIPInstance(S_CIP_Class * cip_class, EIP_UINT32
+ * instance_id);
+ *   - void InsertAttribute(S_CIP_Instance *instance, EIP_UINT16
+ * attribute_number, EIP_UINT8 cip_type, void* data);
+ *   - void InsertService(S_CIP_Class *class, EIP_UINT8 service_number,
+ * CipServiceFunction service_function, char *service_name);
+ *
+ * @page license OpENer Open Source License
+ * The OpENer Open Source License is an adapted BSD style license. The
+ * adaptations include the use of the term EtherNet/IP(TM) and the necessary
+ * guarding conditions for using OpENer in own products. For this please look
  * in license text as shown below:
  * in license text as shown below:
- * 
- * \include "license.txt"  
- * 
+ *
+ * @include "license.txt"
+ *
  */
  */
 
 
-#endif /*CIP_API_H_*/
-
+#endif /*OPENER_OPENER_API_H_*/

+ 51 - 62
source/src/ports/LM3S8962/basiccip.c

@@ -19,51 +19,58 @@
 #define DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM 0x305
 #define DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM 0x305
 #define DEMO_APP_EXPLICT_ASSEMBLY_NUM              0x306
 #define DEMO_APP_EXPLICT_ASSEMBLY_NUM              0x306
 
 
-
 /* global variables for demo application (4 assembly data fields) */
 /* global variables for demo application (4 assembly data fields) */
-EIP_UINT8 g_assemblydata301[32]; /* Input */
-EIP_UINT8 g_assemblydata302[32]; /* Output */
-EIP_UINT8 g_assemblydata303[10]; /* Config */
-EIP_UINT8 g_assemblydata306[32]; /* Explicit */
+EipUint8 g_assemblydata301[32]; /* Input */
+EipUint8 g_assemblydata302[32]; /* Output */
+EipUint8 g_assemblydata303[10]; /* Config */
+EipUint8 g_assemblydata306[32]; /* Explicit */
 
 
 extern int newfd;
 extern int newfd;
 
 
-
-EIP_STATUS
-IApp_Init(void)
-{
+EipStatus ApplicationInitialization(void) {
 //  CIP_Motion_Init();
 //  CIP_Motion_Init();
 
 
   /* create 3 assembly object instances*/
   /* create 3 assembly object instances*/
   /*INPUT*/
   /*INPUT*/
-  createAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, &g_assemblydata301[0], sizeof(g_assemblydata301));
+  CreateAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, &g_assemblydata301[0],
+                       sizeof(g_assemblydata301));
 
 
   /*OUTPUT*/
   /*OUTPUT*/
-  createAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, &g_assemblydata302[0], sizeof(g_assemblydata302));
+  CreateAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, &g_assemblydata302[0],
+                       sizeof(g_assemblydata302));
 
 
   /*CONFIG*/
   /*CONFIG*/
-  createAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, &g_assemblydata303[0], sizeof(g_assemblydata303));
+  CreateAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, &g_assemblydata303[0],
+                       sizeof(g_assemblydata303));
 
 
   /*Heart-beat output assembly for Input only connections */
   /*Heart-beat output assembly for Input only connections */
-  createAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /*Heart-beat output assembly for Listen only connections */
   /*Heart-beat output assembly for Listen only connections */
-  createAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /* assembly for explicit messaging */
   /* assembly for explicit messaging */
-  createAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assemblydata306[0], sizeof(g_assemblydata306));
-
-  configureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM, DEMO_APP_INPUT_ASSEMBLY_NUM, DEMO_APP_CONFIG_ASSEMBLY_NUM);
-  configureInputOnlyConnectionPoint(0, DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, DEMO_APP_INPUT_ASSEMBLY_NUM, DEMO_APP_CONFIG_ASSEMBLY_NUM);
-  configureListenOnlyConnectionPoint(0, DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, DEMO_APP_INPUT_ASSEMBLY_NUM, DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  CreateAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assemblydata306[0],
+                       sizeof(g_assemblydata306));
+
+  ConfigureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM,
+                                         DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                         DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  ConfigureInputOnlyConnectionPoint(0,
+                                    DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM,
+                                    DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                    DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  ConfigureListenOnlyConnectionPoint(0,
+                                     DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM,
+                                     DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                     DEMO_APP_CONFIG_ASSEMBLY_NUM);
 
 
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-void
-IApp_IOConnectionEvent(unsigned int pa_unOutputAssembly,
-    unsigned int pa_unInputAssembly, EIOConnectionEvent pa_eIOConnectionEvent)
-{
+void IoConnectionEvent(unsigned int pa_unOutputAssembly,
+                       unsigned int pa_unInputAssembly,
+                       EIOConnectionEvent pa_eIOConnectionEvent) {
   /* maintain a correct output state according to the connection state*/
   /* maintain a correct output state according to the connection state*/
 
 
   (void) pa_unOutputAssembly; /* suppress compiler warning */
   (void) pa_unOutputAssembly; /* suppress compiler warning */
@@ -71,78 +78,60 @@ IApp_IOConnectionEvent(unsigned int pa_unOutputAssembly,
   pa_eIOConnectionEvent = pa_eIOConnectionEvent; /* suppress compiler warning */
   pa_eIOConnectionEvent = pa_eIOConnectionEvent; /* suppress compiler warning */
 }
 }
 
 
-EIP_STATUS
-IApp_AfterAssemblyDataReceived(S_CIP_Instance *pa_pstInstance)
-{
+EipStatus AfterAssemblyDataReceived(CipInstance *pa_pstInstance) {
   /*handle the data received e.g., update outputs of the device */
   /*handle the data received e.g., update outputs of the device */
 
 
-  if (pa_pstInstance->nInstanceNr == DEMO_APP_OUTPUT_ASSEMBLY_NUM)
-    {
-      /* Data for the output assembly has been received.
-       * Mirror it to the inputs */
-      memcpy(&g_assemblydata301[0], &g_assemblydata302[0], sizeof(g_assemblydata301));
-    }
-  else if (pa_pstInstance->nInstanceNr == DEMO_APP_EXPLICT_ASSEMBLY_NUM)
-    {
-      /* do something interesting with the new data from
-       * the explicit set-data-attribute message */
-    }
+  if (pa_pstInstance->instance_number == DEMO_APP_OUTPUT_ASSEMBLY_NUM) {
+    /* Data for the output assembly has been received.
+     * Mirror it to the inputs */
+    memcpy(&g_assemblydata301[0], &g_assemblydata302[0],
+           sizeof(g_assemblydata301));
+  } else if (pa_pstInstance->instance_number == DEMO_APP_EXPLICT_ASSEMBLY_NUM) {
+    /* do something interesting with the new data from
+     * the explicit set-data-attribute message */
+  }
 
 
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-EIP_BOOL8
-IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance)
-{
+EipBool8 BeforeAssemblyDataSend(CipInstance *pa_pstInstance) {
   /*update data to be sent e.g., read inputs of the device */
   /*update data to be sent e.g., read inputs of the device */
   /*In this sample app we mirror the data from out to inputs on data receive
   /*In this sample app we mirror the data from out to inputs on data receive
    * therefore we need nothing to do here. Just return true to inform that
    * therefore we need nothing to do here. Just return true to inform that
    * the data is new.
    * the data is new.
    */
    */
 
 
-  if (pa_pstInstance->nInstanceNr == DEMO_APP_EXPLICT_ASSEMBLY_NUM)
-    {
-      /* do something interesting with the existing data
-       * for the explicit get-data-attribute message */
-    }
+  if (pa_pstInstance->instance_number == DEMO_APP_EXPLICT_ASSEMBLY_NUM) {
+    /* do something interesting with the existing data
+     * for the explicit get-data-attribute message */
+  }
   return true;
   return true;
 }
 }
 
 
-EIP_STATUS
-IApp_ResetDevice(void)
-{
+EipStatus ResetDevice(void) {
   /* add reset code here*/
   /* add reset code here*/
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-EIP_STATUS
-IApp_ResetDeviceToInitialConfiguration(void)
-{
+EipStatus ResetDeviceToInitialConfiguration(void) {
   /*rest the parameters and than perform device reset*/
   /*rest the parameters and than perform device reset*/
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
 void *
 void *
-IApp_CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement)
-{
+CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement) {
   return mem_calloc(pa_nNumberOfElements, pa_nSizeOfElement);
   return mem_calloc(pa_nNumberOfElements, pa_nSizeOfElement);
 }
 }
 
 
-void
-IApp_CipFree(void *pa_poData)
-{
+void CipFree(void *pa_poData) {
   mem_free(pa_poData);
   mem_free(pa_poData);
 }
 }
 
 
-void
-IApp_RunIdleChanged(EIP_UINT32 pa_nRunIdleValue)
-{
+void RunIdleChanged(EipUint32 pa_nRunIdleValue) {
   (void) pa_nRunIdleValue;
   (void) pa_nRunIdleValue;
 }
 }
 
 
-void
-IApp_HandleApplication(void)
-{
+void HandleApplication(void) {
   /* check if application needs to trigger an connection */
   /* check if application needs to trigger an connection */
 }
 }
 
 

+ 63 - 68
source/src/ports/LM3S8962/flashmgr.c

@@ -39,92 +39,87 @@
 // This flash manger only supports one parameter block at a time.
 // This flash manger only supports one parameter block at a time.
 // It does not support multiple block types, or multiple instances of blocks.
 // It does not support multiple block types, or multiple instances of blocks.
 
 
-
 #define FLASHBASE ((unsigned long *)(255*1024))			// parameter sector is the last 1024 byte chunk of the program flash
 #define FLASHBASE ((unsigned long *)(255*1024))			// parameter sector is the last 1024 byte chunk of the program flash
 #define FLASHEND ((unsigned long *)(256*1024))
 #define FLASHEND ((unsigned long *)(256*1024))
 #define CHUNKSIZE 1024
 #define CHUNKSIZE 1024
 static const int erasedFlashField = 0xffffffff;
 static const int erasedFlashField = 0xffffffff;
 
 
 // erase everything in the parameters block
 // erase everything in the parameters block
-static void eraseAllParameters(void)
-{
-	FlashErase((unsigned long)FLASHBASE);
+static void eraseAllParameters(void) {
+  FlashErase((unsigned long) FLASHBASE);
 }
 }
 
 
 // find the parameter block
 // find the parameter block
 // returns the address of the parameter block, or zero if not found
 // returns the address of the parameter block, or zero if not found
 
 
-unsigned long* findNextEmptyParameterBlock(void)
-{
-	unsigned long* currentFlashAddress = FLASHBASE;
-	unsigned long* const noSpaceLeft = 0;
-
-	while (currentFlashAddress < FLASHEND)
-	{
-		if (0 == *currentFlashAddress)
-			++currentFlashAddress;
-		else if (erasedFlashField == *currentFlashAddress)
-			return noSpaceLeft;
-		else
-			return currentFlashAddress;
-	}
-	return noSpaceLeft;
+unsigned long* findNextEmptyParameterBlock(void) {
+  unsigned long* currentFlashAddress = FLASHBASE;
+  unsigned long* const noSpaceLeft = 0;
+
+  while (currentFlashAddress < FLASHEND) {
+    if (0 == *currentFlashAddress)
+      ++currentFlashAddress;
+    else if (erasedFlashField == *currentFlashAddress)
+      return noSpaceLeft;
+    else
+      return currentFlashAddress;
+  }
+  return noSpaceLeft;
 }
 }
 
 
 // verify that the block to be written is erased
 // verify that the block to be written is erased
-static int parameterBlockIsEmpty(unsigned long *data, // pointer to are to be checked
-		int dataSize) // sizeof(struct)
+static int parameterBlockIsEmpty(unsigned long *data,  // pointer to are to be checked
+    int dataSize)  // sizeof(struct)
 {
 {
-	int const isNotEmpty = 0;
-	int const isEmpty = 1;
-	while (dataSize > 0)
-	{
-		if (*data++ != erasedFlashField)
-			return isNotEmpty;
-		dataSize -= 4;
-	}
-	return isEmpty;
+  int const isNotEmpty = 0;
+  int const isEmpty = 1;
+  while (dataSize > 0) {
+    if (*data++ != erasedFlashField)
+      return isNotEmpty;
+    dataSize -= 4;
+  }
+  return isEmpty;
 }
 }
 
 
 // write a new parameter block
 // write a new parameter block
-void writeParameter(unsigned long *data, // pointer to struct to be saved
-		int dataSize) // sizeof(struct)
+void writeParameter(unsigned long *data,  // pointer to struct to be saved
+    int dataSize)  // sizeof(struct)
 {
 {
-	unsigned long *currentParameterBlock = findNextEmptyParameterBlock(); // find the current parameter block;
-	unsigned long zero = 0;
-
-	if (currentParameterBlock) // if found, zero it
-	{
-		int lengthToBeErased = *currentParameterBlock + 4; // calc dataSize of region to be erased
-
-		if (currentParameterBlock + lengthToBeErased / 4 <= FLASHEND) // if properly formatted, zero the current block
-		{
-			while (lengthToBeErased > 0) //   for each word
-			{
-				FlashProgram(&zero, (unsigned long)currentParameterBlock, 4); // zero one word
-				currentParameterBlock++; //     advance to next word
-				lengthToBeErased -= 4; //     dec dataSize
-			}
-		}
-		else // else flash is corrupt -- erase it all
-		{
-			eraseAllParameters();
-			currentParameterBlock = FLASHBASE;
-		}
-	}
-
-	// at this point p should point to useable erased flash
-
-	// currentParameterBlock now points to the first unerased word
-
-	if (currentParameterBlock + dataSize/4 > FLASHEND // if flash is full
-			|| !parameterBlockIsEmpty(currentParameterBlock, dataSize)) // or not properly erased
-	{
-		eraseAllParameters(); // erase the entire block
-		currentParameterBlock = FLASHBASE; // start from the beginning
-	}
-
-	FlashProgram((unsigned long *)&dataSize, (unsigned long)currentParameterBlock, 4); // program the length
-	FlashProgram(data, (unsigned long)(currentParameterBlock+1), dataSize); // program the data
+  unsigned long *currentParameterBlock = findNextEmptyParameterBlock();  // find the current parameter block;
+  unsigned long zero = 0;
+
+  if (currentParameterBlock)  // if found, zero it
+  {
+    int lengthToBeErased = *currentParameterBlock + 4;  // calc dataSize of region to be erased
+
+    if (currentParameterBlock + lengthToBeErased / 4 <= FLASHEND)  // if properly formatted, zero the current block
+    {
+      while (lengthToBeErased > 0)  //   for each word
+      {
+        FlashProgram(&zero, (unsigned long) currentParameterBlock, 4);  // zero one word
+        currentParameterBlock++;  //     advance to next word
+        lengthToBeErased -= 4;  //     dec dataSize
+      }
+    } else  // else flash is corrupt -- erase it all
+    {
+      eraseAllParameters();
+      currentParameterBlock = FLASHBASE;
+    }
+  }
+
+  // at this point p should point to useable erased flash
+
+  // currentParameterBlock now points to the first unerased word
+
+  if (currentParameterBlock + dataSize / 4 > FLASHEND  // if flash is full
+  || !parameterBlockIsEmpty(currentParameterBlock, dataSize))  // or not properly erased
+                            {
+    eraseAllParameters();  // erase the entire block
+    currentParameterBlock = FLASHBASE;  // start from the beginning
+  }
+
+  FlashProgram((unsigned long *) &dataSize,
+               (unsigned long) currentParameterBlock, 4);  // program the length
+  FlashProgram(data, (unsigned long) (currentParameterBlock + 1), dataSize);  // program the data
 }
 }
 
 

+ 177 - 215
source/src/ports/LM3S8962/networkhandler.c

@@ -23,8 +23,8 @@
 #define MAX_RECEIVE_SIZE 512
 #define MAX_RECEIVE_SIZE 512
 #define MAX_SEND_SIZE 512
 #define MAX_SEND_SIZE 512
 
 
-static EIP_UINT8 rxbuf[MAX_RECEIVE_SIZE]; // this appears to be the EIP command buffer
-EIP_UINT8 eip_reply_buf[MAX_SEND_SIZE]; // this appears to be the EthernetIP reply buffer
+static EipUint8 rxbuf[MAX_RECEIVE_SIZE];  // this appears to be the EIP command buffer
+EipUint8 eip_reply_buf[MAX_SEND_SIZE];  // this appears to be the EthernetIP reply buffer
 
 
 extern void
 extern void
 dump(unsigned char *p, int size);
 dump(unsigned char *p, int size);
@@ -41,131 +41,117 @@ struct tcp_pcb *g_pstCurrentTCP_PCB = NULL;
 // UDP UNSOLICITED DATA RECEIVE CALLBACK
 // UDP UNSOLICITED DATA RECEIVE CALLBACK
 // The callback function is responsible for deallocating the pbuf.
 // The callback function is responsible for deallocating the pbuf.
 
 
-void
-udp_unsolicited_receive_callback(void * arg, // arg specified when the callback was registered
-    struct udp_pcb * pcb, // pcb handling the receive
-    struct pbuf * p, // the packet
-    struct ip_addr * addr, // source IP address
-    u16_t port) // source UDP port number
+void udp_unsolicited_receive_callback(void * arg,  // arg specified when the callback was registered
+    struct udp_pcb * pcb,  // pcb handling the receive
+    struct pbuf * p,  // the packet
+    struct ip_addr * addr,  // source IP address
+    u16_t port)  // source UDP port number
 {
 {
-  EIP_UINT8 *rxp; // pointer into the receive buf
-  int rxlen; // size of the received message
-  int bytesleft; // bytes left (allows for multiple messages per packet)
+  EipUint8 *rxp;  // pointer into the receive buf
+  int rxlen;  // size of the received message
+  int bytesleft;  // bytes left (allows for multiple messages per packet)
   int replylen;
   int replylen;
   err_t status;
   err_t status;
-  struct pbuf * r; // reply buffer
+  struct pbuf * r;  // reply buffer
   struct sockaddr_in stFrom;
   struct sockaddr_in stFrom;
 
 
-  assert(p->tot_len <= sizeof(rxbuf)); // TODO this needs to be hardened
-  pbuf_copy_partial(p, rxbuf, sizeof(rxbuf), 0); // copy the packet into a contiguous receive buffer
-  rxlen = p->tot_len; // size of the received message
-  pbuf_free(p); // we no longer need the packet buffer
-
-  if (EIP_DEBUG > EIP_VVERBOSE)
-    {
-      OPENER_TRACE_INFO("Data received on UDP:\n");
-      dump(rxbuf, rxlen);
-    }
-
-  rxp = &rxbuf[0]; // point to the start of the message
-  do
-    {
-      stFrom.sin_family = AF_INET;
-      stFrom.sin_port = port;
-      stFrom.sin_addr.s_addr = addr->addr;
-      memset(&stFrom.sin_zero, 0, sizeof(stFrom.sin_zero));
-
-      replylen = handleReceivedExplictUDPData((unsigned) pcb, // bogus a socket fd (use the pcb address cast to an int)
-          &stFrom, rxp, rxlen, &bytesleft);
-
-      rxp += rxlen - bytesleft; // bump the buffer pointer by the amount of data that was eaten
-      rxlen = bytesleft; // dec the data size by the same amount
-
-      if (replylen > 0)
-        {
-          if (EIP_DEBUG >= EIP_VVERBOSE)
-            {
-              OPENER_TRACE_INFO("reply sent:\n");
-              dump(eip_reply_buf, replylen);
-            }
-
-          r = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF);
-          assert(r != 0); // TODO harden
-          //r->payload = &eip_reply_buf[0];
-          r->payload = &rxbuf[0];
-          r->len = r->tot_len = replylen;
-          status = udp_sendto(pcb, r, (struct ip_addr *) &addr->addr, port);
-          assert(status == 0); // TODO check for non-fatal status response?
-          pbuf_free(r); // reference counting makes sure the header does not get freed prematurely, but what about the replybuf?
-        }
+  assert(p->tot_len <= sizeof(rxbuf));  // TODO this needs to be hardened
+  pbuf_copy_partial(p, rxbuf, sizeof(rxbuf), 0);  // copy the packet into a contiguous receive buffer
+  rxlen = p->tot_len;  // size of the received message
+  pbuf_free(p);  // we no longer need the packet buffer
+
+  if (EIP_DEBUG > EIP_VVERBOSE) {
+    OPENER_TRACE_INFO("Data received on UDP:\n");
+    dump(rxbuf, rxlen);
+  }
+
+  rxp = &rxbuf[0];  // point to the start of the message
+  do {
+    stFrom.sin_family = AF_INET;
+    stFrom.sin_port = port;
+    stFrom.sin_addr.s_addr = addr->addr;
+    memset(&stFrom.sin_zero, 0, sizeof(stFrom.sin_zero));
+
+    replylen = HandleReceivedExplictUdpData((unsigned) pcb,  // bogus a socket fd (use the pcb address cast to an int)
+        &stFrom, rxp, rxlen, &bytesleft);
+
+    rxp += rxlen - bytesleft;  // bump the buffer pointer by the amount of data that was eaten
+    rxlen = bytesleft;  // dec the data size by the same amount
+
+    if (replylen > 0) {
+      if (EIP_DEBUG >= EIP_VVERBOSE) {
+        OPENER_TRACE_INFO("reply sent:\n");
+        dump(eip_reply_buf, replylen);
+      }
+
+      r = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF);
+      assert(r != 0);  // TODO harden
+      //r->payload = &eip_reply_buf[0];
+      r->payload = &rxbuf[0];
+      r->len = r->tot_len = replylen;
+      status = udp_sendto(pcb, r, (struct ip_addr *) &addr->addr, port);
+      assert(status == 0);  // TODO check for non-fatal status response?
+      pbuf_free(r);  // reference counting makes sure the header does not get freed prematurely, but what about the replybuf?
     }
     }
-  while (rxlen > 0);
+  } while (rxlen > 0);
 }
 }
 
 
 // UDP CONNECTED DATA CALLBACK
 // UDP CONNECTED DATA CALLBACK
 
 
-void
-udp_registered_receive_callback(void * arg, // arg specified when the callback was registered
-    struct udp_pcb * pcb, // pcb handling the receive
-    struct pbuf * pbuf, // the packet
-    struct ip_addr * addr, // source IP address
-    u16_t port) // source UDP port number
+void udp_registered_receive_callback(void * arg,  // arg specified when the callback was registered
+    struct udp_pcb * pcb,  // pcb handling the receive
+    struct pbuf * pbuf,  // the packet
+    struct ip_addr * addr,  // source IP address
+    u16_t port)  // source UDP port number
 {
 {
-  EIP_UINT8 *rxp; // pointer into the receive buf
-  int rxlen; // size of the received message
+  EipUint8 *rxp;  // pointer into the receive buf
+  int rxlen;  // size of the received message
   struct sockaddr_in stFrom;
   struct sockaddr_in stFrom;
 
 
   //assert(pbuf->len == pbuf->tot_len);
   //assert(pbuf->len == pbuf->tot_len);
-  assert(pbuf->tot_len <= MAX_RECEIVE_SIZE); // TODO this needs to be hardened
-  rxlen = pbuf_copy_partial(pbuf, rxbuf, MAX_RECEIVE_SIZE, 0); // copy the packet into a contiguous receive buffer
+  assert(pbuf->tot_len <= MAX_RECEIVE_SIZE);// TODO this needs to be hardened
+  rxlen = pbuf_copy_partial(pbuf, rxbuf, MAX_RECEIVE_SIZE, 0);  // copy the packet into a contiguous receive buffer
   //assert(rxlen == pbuf->tot_len);
   //assert(rxlen == pbuf->tot_len);
-  rxp = &rxbuf[0]; // point to the start of the message
-  pbuf_free(pbuf); // we no longer need the packet buffer
-
-  if (rxlen == 0)
-    {
-      OPENER_TRACE_ERR("connection closed by client\n");
-      udp_disconnect(pcb); /* close socket */
-      udp_remove(pcb);
-      return;
-    }
-  if (rxlen <= 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: error on recv");
-      udp_disconnect(pcb); /* close socket */
-      udp_remove(pcb);
-      return;
-    }
+  rxp = &rxbuf[0];  // point to the start of the message
+  pbuf_free(pbuf);  // we no longer need the packet buffer
+
+  if (rxlen == 0) {
+    OPENER_TRACE_ERR("connection closed by client\n");
+    udp_disconnect(pcb); /* close socket */
+    udp_remove(pcb);
+    return;
+  }
+  if (rxlen <= 0) {
+    OPENER_TRACE_ERR("networkhandler: error on recv");
+    udp_disconnect(pcb); /* close socket */
+    udp_remove(pcb);
+    return;
+  }
 
 
   stFrom.sin_family = AF_INET;
   stFrom.sin_family = AF_INET;
   stFrom.sin_port = port;
   stFrom.sin_port = port;
   stFrom.sin_addr.s_addr = addr->addr;
   stFrom.sin_addr.s_addr = addr->addr;
   memset(&stFrom.sin_zero, 0, sizeof(stFrom.sin_zero));
   memset(&stFrom.sin_zero, 0, sizeof(stFrom.sin_zero));
 
 
-  handleReceivedConnectedData(rxbuf, rxlen, &stFrom);
+  HandleReceivedConnectedData(rxbuf, rxlen, &stFrom);
 }
 }
 
 
 // TCP DATA SENT CALLBACK
 // TCP DATA SENT CALLBACK
 
 
-err_t
-tcp_sent_callback(void * arg, struct tcp_pcb * tpcb, u16_t len)
-{
+err_t tcp_sent_callback(void * arg, struct tcp_pcb * tpcb, u16_t len) {
   // TODO unlock the reply buf?
   // TODO unlock the reply buf?
 
 
   return ERR_OK;
   return ERR_OK;
 }
 }
 
 
-
-
 // TCP DATA RECEIVE CALLBACK
 // TCP DATA RECEIVE CALLBACK
 
 
-err_t
-tcp_receive_callback(void * arg, // arg specified earlier
-    struct tcp_pcb *pcb, // pcb that is delivering the data
-    struct pbuf *pbuf, // the packet
-    err_t err) // TCP uses this to tell us what's happening to the connection perhaps?
+err_t tcp_receive_callback(void * arg,  // arg specified earlier
+    struct tcp_pcb *pcb,  // pcb that is delivering the data
+    struct pbuf *pbuf,  // the packet
+    err_t err)  // TCP uses this to tell us what's happening to the connection perhaps?
 {
 {
-  EIP_UINT8 *rxp;
+  EipUint8 *rxp;
   int rxlen;
   int rxlen;
   int bytesread;
   int bytesread;
   int bytesleft;
   int bytesleft;
@@ -175,84 +161,76 @@ tcp_receive_callback(void * arg, // arg specified earlier
   err_t status;
   err_t status;
 
 
   if (err != ERR_OK)
   if (err != ERR_OK)
-    return err; // don't try to receive if error
+    return err;  // don't try to receive if error
+
+  if (pbuf == 0)  // check if connection is closing
+      {
+    tcp_close(pcb);  // close out end
+    return ERR_OK;
+  }
+
+  while (rxoff < pbuf->tot_len) {
+    rxlen = pbuf_copy_partial(pbuf, rxbuf, 4, rxoff);  // copy the first four words into the contiguous receive buffer
+    assert(rxlen == 4);  //need at least four bytes of the header at this point
+    rxp = &rxbuf[2];  // at this place EIP stores the data length
+    rxlen = GetIntFromMessage(&rxp) + ENCAPSULATION_HEADER_LENGTH - 4;  // -4 is for the 4 bytes we have already read
+    // (NOTE this advances the buffer pointer)
+
+    if (rxlen + 4 > MAX_RECEIVE_SIZE) {  //TODO can this be handled in a better way?
+      OPENER_TRACE_ERR("too large packet received will be ignored\n");  // this may corrupt the connection ???
+      return EIP_ERROR;
+    }
+
+    bytesread = pbuf_copy_partial(pbuf, &rxbuf[4], rxlen, rxoff + 4);  // copy the rest of the message into the contiguous receive buffer
+    assert(bytesread == rxlen);
+    rxlen += 4;
+    rxoff += rxlen;
+    tcp_recved(pcb, rxlen);  // tell TCP we have received the data
 
 
-  if (pbuf == 0) // check if connection is closing
-    {
-      tcp_close(pcb); // close out end
-      return ERR_OK;
+    if (EIP_DEBUG >= EIP_VVERBOSE) {
+      OPENER_TRACE_INFO("Data received on tcp:\n");
+      dump(rxbuf, rxlen);
     }
     }
 
 
-  while (rxoff < pbuf->tot_len)
-    {
-      rxlen = pbuf_copy_partial(pbuf, rxbuf, 4, rxoff); // copy the first four words into the contiguous receive buffer
-      assert(rxlen == 4); //need at least four bytes of the header at this point
-      rxp = &rxbuf[2]; // at this place EIP stores the data length
-      rxlen = ltohs(&rxp) + ENCAPSULATION_HEADER_LENGTH - 4; // -4 is for the 4 bytes we have already read
-      // (NOTE this advances the buffer pointer)
-
-      if (rxlen + 4 > MAX_RECEIVE_SIZE)
-        { //TODO can this be handled in a better way?
-          OPENER_TRACE_ERR("too large packet received will be ignored\n"); // this may corrupt the connection ???
-          return EIP_ERROR;
-        }
-
-      bytesread = pbuf_copy_partial(pbuf, &rxbuf[4], rxlen, rxoff + 4); // copy the rest of the message into the contiguous receive buffer
-      assert(bytesread == rxlen);
-      rxlen += 4;
-      rxoff += rxlen;
-      tcp_recved(pcb, rxlen); // tell TCP we have received the data
-
-      if (EIP_DEBUG >= EIP_VVERBOSE)
-        {
-          OPENER_TRACE_INFO("Data received on tcp:\n");
-          dump(rxbuf, rxlen);
-        }
-
-      g_pstCurrentTCP_PCB = pcb;
-      replylen = handleReceivedExplictTCPData((unsigned) pcb, // bogus a socket fd (use the pcb address cast to an int) -- I do not think this is used anywhere
-          rxbuf, rxlen, &bytesleft);
-      g_pstCurrentTCP_PCB = NULL;
-      assert(bytesleft == 0);
-
-      if (replylen > 0)
-        {
-          if (EIP_DEBUG >= EIP_VVERBOSE)
-            {
-              OPENER_TRACE_INFO("reply sent:\n");
-              dump(eip_reply_buf, replylen);
-            }
-
-          txspace = tcp_sndbuf(pcb); // see how much data can be sent
-          assert(txspace >= replylen); // TODO harden this
-
-          status = tcp_write(pcb, rxbuf, replylen, TCP_WRITE_FLAG_COPY); // TODO need to examine serial reuse of the reply buf
-          if (status != ERR_OK)
-            {
-              OPENER_TRACE_ERR("TCP response was not sent OK: %d\n", status);
-            }
-          tcp_output(pcb); // push the data out
-        }
+    g_pstCurrentTCP_PCB = pcb;
+    replylen = HandleReceivedExplictTcpData((unsigned) pcb,  // bogus a socket fd (use the pcb address cast to an int) -- I do not think this is used anywhere
+        rxbuf, rxlen, &bytesleft);
+    g_pstCurrentTCP_PCB = NULL;
+    assert(bytesleft == 0);
+
+    if (replylen > 0) {
+      if (EIP_DEBUG >= EIP_VVERBOSE) {
+        OPENER_TRACE_INFO("reply sent:\n");
+        dump(eip_reply_buf, replylen);
+      }
+
+      txspace = tcp_sndbuf(pcb);  // see how much data can be sent
+      assert(txspace >= replylen);  // TODO harden this
+
+      status = tcp_write(pcb, rxbuf, replylen, TCP_WRITE_FLAG_COPY);  // TODO need to examine serial reuse of the reply buf
+      if (status != ERR_OK) {
+        OPENER_TRACE_ERR("TCP response was not sent OK: %d\n", status);
+      }
+      tcp_output(pcb);  // push the data out
     }
     }
+  }
 
 
-  pbuf_free(pbuf); // we no longer need the packet buffer
+  pbuf_free(pbuf);  // we no longer need the packet buffer
 
 
   return ERR_OK;
   return ERR_OK;
 }
 }
 
 
 // TCP CONNECTION ACCEPT CALLBACK
 // TCP CONNECTION ACCEPT CALLBACK
 
 
-err_t
-tcp_connection_accept_callback(void *arg, // arg registered for this listener (ignored in this case)
-    struct tcp_pcb *newpcb, // pcb for new tcp connection
-    err_t err)
-{
+err_t tcp_connection_accept_callback(void *arg,  // arg registered for this listener (ignored in this case)
+    struct tcp_pcb *newpcb,  // pcb for new tcp connection
+    err_t err) {
   OPENER_TRACE_INFO("networkhandler: new TCP connection\n");
   OPENER_TRACE_INFO("networkhandler: new TCP connection\n");
 
 
-  tcp_accepted(TCPlistener); // tell the listener that the call was accepted
+  tcp_accepted(TCPlistener);  // tell the listener that the call was accepted
 
 
-  tcp_recv(newpcb, tcp_receive_callback); // set the callback for received data on the new connection
-  tcp_sent(newpcb, tcp_sent_callback); // set the callback for transmitted data on the new connection
+  tcp_recv(newpcb, tcp_receive_callback);  // set the callback for received data on the new connection
+  tcp_sent(newpcb, tcp_sent_callback);  // set the callback for transmitted data on the new connection
 
 
   return ERR_OK;
   return ERR_OK;
 }
 }
@@ -263,9 +241,7 @@ tcp_connection_accept_callback(void *arg, // arg registered for this listener (i
  * 			-1 .. error
  * 			-1 .. error
  */
  */
 
 
-EIP_STATUS
-Start_NetworkHandler()
-{
+EipStatus Start_NetworkHandler() {
   err_t status;
   err_t status;
 
 
   my_addr.sin_family = AF_INET;
   my_addr.sin_family = AF_INET;
@@ -286,7 +262,7 @@ Start_NetworkHandler()
   UDPlistener = udp_new();
   UDPlistener = udp_new();
   assert(UDPlistener != 0);
   assert(UDPlistener != 0);
   udp_bind(UDPlistener, INADDR_ANY, OPENER_ETHERNET_PORT);
   udp_bind(UDPlistener, INADDR_ANY, OPENER_ETHERNET_PORT);
-  udp_recv(UDPlistener, udp_unsolicited_receive_callback, 0); // set the callback
+  udp_recv(UDPlistener, udp_unsolicited_receive_callback, 0);  // set the callback
 
 
   return EIP_OK;
   return EIP_OK;
 }
 }
@@ -294,16 +270,14 @@ Start_NetworkHandler()
 static elapsedtime = 0;
 static elapsedtime = 0;
 
 
 // this gets called every 10 ms from the lwiptick handler, which is called from an Ethernet controller interrupt (SYSTICKHZ = 100)
 // this gets called every 10 ms from the lwiptick handler, which is called from an Ethernet controller interrupt (SYSTICKHZ = 100)
-void
-CIPtick(int delta) // time since last tick in ms, probably 10
+void CIPtick(int delta)  // time since last tick in ms, probably 10
 {
 {
   /* call manage_connections() in connection manager every TIMERTICK ms */
   /* call manage_connections() in connection manager every TIMERTICK ms */
   elapsedtime += delta;
   elapsedtime += delta;
-  if (elapsedtime >= TIMERTICK)
-    {
-      manageConnections();
-      elapsedtime = 0;
-    }
+  if (elapsedtime >= TIMERTICK) {
+    ManageConnections();
+    elapsedtime = 0;
+  }
 }
 }
 
 
 /* INT8 registerCallbackFunc(int sockfd, struct sockaddr_in pa_addr, S_CIP_Class *p_stObject, INT8 (*pt2func)(S_CIP_Class *p_stObject, INT8 *data, UINT16 datalength))
 /* INT8 registerCallbackFunc(int sockfd, struct sockaddr_in pa_addr, S_CIP_Class *p_stObject, INT8 (*pt2func)(S_CIP_Class *p_stObject, INT8 *data, UINT16 datalength))
@@ -317,16 +291,13 @@ CIPtick(int delta) // time since last tick in ms, probably 10
  * 			-1 .. error
  * 			-1 .. error
  */
  */
 
 
-EIP_STATUS
-registerCallbackFunc(int sockfd, struct sockaddr_in *pa_addr,
-    S_CIP_Instance *pa_pstInstance, TCIPServiceFunc pa_ptfuncReceiveData)
-{
+EipStatus registerCallbackFunc(int sockfd, struct sockaddr_in *pa_addr,
+                               CipInstance *pa_pstInstance,
+                               CipServiceFunction pa_ptfuncReceiveData) {
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-EIP_STATUS
-unregisterCallbackFunc(S_CIP_Instance * pa_pstInstance)
-{
+EipStatus unregisterCallbackFunc(CipInstance * pa_pstInstance) {
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
@@ -341,23 +312,21 @@ unregisterCallbackFunc(S_CIP_Instance * pa_pstInstance)
  * 			-1 .. error
  * 			-1 .. error
  */
  */
 
 
-EIP_STATUS
-IApp_SendUDPData(struct sockaddr_in *pa_addr, int sockfd, EIP_UINT8 *pa_data,
-    EIP_UINT16 pa_datalength)
-{
+EipStatus SendUdpData(struct sockaddr_in *pa_addr, int sockfd,
+                      EipUint8 *pa_data, EipUint16 pa_datalength) {
   struct pbuf *r;
   struct pbuf *r;
   err_t status;
   err_t status;
   struct udp_pcb *pcb;
   struct udp_pcb *pcb;
 
 
   pcb = (struct udp_pcb *) sockfd;
   pcb = (struct udp_pcb *) sockfd;
   r = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF);
   r = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF);
-  assert(r != 0); // TODO harden
+  assert(r != 0);  // TODO harden
   r->payload = pa_data;
   r->payload = pa_data;
   r->len = r->tot_len = pa_datalength;
   r->len = r->tot_len = pa_datalength;
   status = udp_sendto(pcb, r, (struct ip_addr *) &pa_addr->sin_addr,
   status = udp_sendto(pcb, r, (struct ip_addr *) &pa_addr->sin_addr,
-      htons(pa_addr->sin_port));
-  assert(status == 0); // TODO check for non-fatal status response?
-  pbuf_free(r); // reference counting make sure the header does not get freed prematurely, but what about the replybuf?
+                      htons(pa_addr->sin_port));
+  assert(status == 0);  // TODO check for non-fatal status response?
+  pbuf_free(r);  // reference counting make sure the header does not get freed prematurely, but what about the replybuf?
 
 
   return EIP_OK;
   return EIP_OK;
 }
 }
@@ -365,49 +334,43 @@ IApp_SendUDPData(struct sockaddr_in *pa_addr, int sockfd, EIP_UINT8 *pa_data,
 // create a new UDP socket for the connection manager
 // create a new UDP socket for the connection manager
 // returns the fd if successful, else -1
 // returns the fd if successful, else -1
 
 
-int
-IApp_CreateUDPSocket(int pa_nDirection, // direction: CONSUMING or PRODUCING
-    struct sockaddr_in *pa_pstAddr) // bind address, used for producing only
+int CreateUdpSocket(int pa_nDirection,  // direction: CONSUMING or PRODUCING
+    struct sockaddr_in *pa_pstAddr)  // bind address, used for producing only
 {
 {
   struct udp_pcb *pcb;
   struct udp_pcb *pcb;
 
 
   /* create a new UDP socket */
   /* create a new UDP socket */
   pcb = udp_new();
   pcb = udp_new();
-  if (pcb == 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: cannot create UDP socket\n");
-      return -1;
-    } OPENER_TRACE_INFO("networkhandler: created UDP socket %x\n", pcb);
+  if (pcb == 0) {
+    OPENER_TRACE_ERR("networkhandler: cannot create UDP socket\n");
+    return -1;
+  }
+  OPENER_TRACE_INFO("networkhandler: created UDP socket %x\n", pcb);
 
 
   /* check if it is sending or receiving */
   /* check if it is sending or receiving */
-  if (pa_nDirection == CONSUMING)
-    { /* bind is only for consuming necessary */
-      struct ip_addr addr;
-
-      addr.addr = htonl(pa_pstAddr->sin_addr.s_addr);
-      if (udp_bind(pcb, &addr, htons(pa_pstAddr->sin_port)) != ERR_OK)
-        {
-          OPENER_TRACE_INFO("networkhandler: error on bind udp\n");
-          return -1;
-        }
-
-      OPENER_TRACE_INFO("networkhandler: bind UDP socket %08x port %d\n", pcb,
-          pa_pstAddr->sin_port);
-      udp_recv(pcb, udp_registered_receive_callback, 0); // set the callback
+  if (pa_nDirection == CONSUMING) { /* bind is only for consuming necessary */
+    struct ip_addr addr;
+
+    addr.addr = htonl(pa_pstAddr->sin_addr.s_addr);
+    if (udp_bind(pcb, &addr, htons(pa_pstAddr->sin_port)) != ERR_OK) {
+      OPENER_TRACE_INFO("networkhandler: error on bind udp\n");
+      return -1;
     }
     }
 
 
+    OPENER_TRACE_INFO("networkhandler: bind UDP socket %08x port %d\n", pcb,
+                      pa_pstAddr->sin_port);
+    udp_recv(pcb, udp_registered_receive_callback, 0);  // set the callback
+  }
 
 
-  if ((pa_nDirection == CONSUMING) || (0 == pa_pstAddr->sin_addr.s_addr))
-    {
-      /* store the originators address */
-      pa_pstAddr->sin_addr.s_addr =  g_pstCurrentTCP_PCB->remote_ip.addr;
-    }
+  if ((pa_nDirection == CONSUMING) || (0 == pa_pstAddr->sin_addr.s_addr)) {
+    /* store the originators address */
+    pa_pstAddr->sin_addr.s_addr = g_pstCurrentTCP_PCB->remote_ip.addr;
+  }
 
 
   return (int) pcb;
   return (int) pcb;
 }
 }
 
 
-void IApp_CloseSocket_udp(int fd)
-{
+void IApp_CloseSocket_udp(int fd) {
   struct udp_pcb *pcb;
   struct udp_pcb *pcb;
 
 
   OPENER_TRACE_INFO("networkhandler: shutdown UDP socket %x\n", pcb);
   OPENER_TRACE_INFO("networkhandler: shutdown UDP socket %x\n", pcb);
@@ -415,8 +378,7 @@ void IApp_CloseSocket_udp(int fd)
   udp_remove(pcb);
   udp_remove(pcb);
 }
 }
 
 
-void IApp_CloseSocket_tcp(int fd)
-{
+void IApp_CloseSocket_tcp(int fd) {
   struct tcp_pcb *pcb;
   struct tcp_pcb *pcb;
 
 
   OPENER_TRACE_INFO("networkhandler: shutdown TCP socket %x\n", pcb);
   OPENER_TRACE_INFO("networkhandler: shutdown TCP socket %x\n", pcb);

+ 1 - 2
source/src/ports/LM3S8962/networkhandler.h

@@ -8,11 +8,10 @@
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 
 
-
 /*! Start a TCP/UDP listening socket, accept connections, receive data in select loop, call manageConnections periodically.
 /*! Start a TCP/UDP listening socket, accept connections, receive data in select loop, call manageConnections periodically.
  *  @return status
  *  @return status
  *          EIP_ERROR .. error
  *          EIP_ERROR .. error
  */
  */
-EIP_STATUS Start_NetworkHandler(void);
+EipStatus Start_NetworkHandler(void);
 
 
 #endif /*NETWORKHANDLER_H_*/
 #endif /*NETWORKHANDLER_H_*/

+ 66 - 87
source/src/ports/LM3S8962/sample_application/main.c

@@ -65,15 +65,13 @@ volatile unsigned long g_ulSystemTimeNanoSeconds;
 #error "useStaticIP undefined"
 #error "useStaticIP undefined"
 #endif
 #endif
 
 
-struct parm
-{
-  int useStatic; // 1 use static IP address, 0 use DHCP
-  unsigned long ip; // my ip address
-  unsigned long nm; // net mask
-  unsigned long gw; // gateway ip address
+struct parm {
+  int useStatic;  // 1 use static IP address, 0 use DHCP
+  unsigned long ip;  // my ip address
+  unsigned long nm;  // net mask
+  unsigned long gw;  // gateway ip address
 };
 };
 
 
-
 //*****************************************************************************
 //*****************************************************************************
 //
 //
 // Defines for setting up the system clock.
 // Defines for setting up the system clock.
@@ -84,7 +82,6 @@ struct parm
 #define SYSTICKUS               (1000000 / SYSTICKHZ)
 #define SYSTICKUS               (1000000 / SYSTICKHZ)
 #define SYSTICKNS               (1000000000 / SYSTICKHZ)
 #define SYSTICKNS               (1000000000 / SYSTICKHZ)
 
 
-
 //*****************************************************************************
 //*****************************************************************************
 //
 //
 // Interrupt priority definitions.  The top 3 bits of these values are
 // Interrupt priority definitions.  The top 3 bits of these values are
@@ -102,15 +99,14 @@ struct parm
 #ifdef DEBUG
 #ifdef DEBUG
 void
 void
 __error__(char *pcFilename, unsigned long ulLine)
 __error__(char *pcFilename, unsigned long ulLine)
-  {
-  }
+{
+}
 #endif
 #endif
 
 
 // change my IP address etc.
 // change my IP address etc.
-void
-setCIPaddress(unsigned long addr, // my IP address, in network order
-    unsigned long mask, // netmask, in network order
-    unsigned long gw) // gateway, in network order
+void setCIPaddress(unsigned long addr,  // my IP address, in network order
+    unsigned long mask,  // netmask, in network order
+    unsigned long gw)  // gateway, in network order
 {
 {
   struct in_addr inAddr;
   struct in_addr inAddr;
   inAddr.s_addr = addr;
   inAddr.s_addr = addr;
@@ -123,15 +119,13 @@ setCIPaddress(unsigned long addr, // my IP address, in network order
   char acGW[16];
   char acGW[16];
   strncpy(acGW, inet_ntoa(inAddr), 16);
   strncpy(acGW, inet_ntoa(inAddr), 16);
 
 
-  configureNetworkInterface(acIPAddr, acNetMask, acGW);
-  configureDomainName("test");
-  configureHostName("karl");
+  ConfigureNetworkInterface(acIPAddr, acNetMask, acGW);
+  ConfigureDomainName("test");
+  ConfigureHostName("karl");
 }
 }
 
 
 // this gets called every 100 usec by the lwip timer handler
 // this gets called every 100 usec by the lwip timer handler
-void
-lwIPHostTimerHandler(void)
-{
+void lwIPHostTimerHandler(void) {
   static unsigned long ulLastIPAddress = 0;
   static unsigned long ulLastIPAddress = 0;
   unsigned long ulIPAddress;
   unsigned long ulIPAddress;
   unsigned long ulNetmask;
   unsigned long ulNetmask;
@@ -139,18 +133,15 @@ lwIPHostTimerHandler(void)
 
 
   ulIPAddress = lwIPLocalIPAddrGet();
   ulIPAddress = lwIPLocalIPAddrGet();
 
 
-  if (ulLastIPAddress != ulIPAddress)
-    {
-      ulLastIPAddress = ulIPAddress;
-      ulNetmask = lwIPLocalNetMaskGet();
-      ulGateway = lwIPLocalGWAddrGet();
-      setCIPaddress(ulIPAddress, ulNetmask, ulGateway);
-    }
+  if (ulLastIPAddress != ulIPAddress) {
+    ulLastIPAddress = ulIPAddress;
+    ulNetmask = lwIPLocalNetMaskGet();
+    ulGateway = lwIPLocalGWAddrGet();
+    setCIPaddress(ulIPAddress, ulNetmask, ulGateway);
+  }
 }
 }
 
 
-int
-main(void)
-{
+int main(void) {
   int i;
   int i;
   unsigned long ulUser0, ulUser1;
   unsigned long ulUser0, ulUser1;
   unsigned char pucMACArray[8];
   unsigned char pucMACArray[8];
@@ -167,8 +158,8 @@ main(void)
   //
   //
   // Set the clocking to run directly from the crystal.
   // Set the clocking to run directly from the crystal.
   //
   //
-  SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN
-                  | SYSCTL_XTAL_8MHZ);
+  SysCtlClockSet(
+      SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_8MHZ);
 
 
   SysCtlPeripheralEnable(SYSCTL_PERIPH_ETH);
   SysCtlPeripheralEnable(SYSCTL_PERIPH_ETH);
   SysCtlPeripheralReset(SYSCTL_PERIPH_ETH);
   SysCtlPeripheralReset(SYSCTL_PERIPH_ETH);
@@ -180,26 +171,25 @@ main(void)
   SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
   SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
   SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
   SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
   GPIODirModeSet(GPIO_PORTF_BASE, GPIO_PIN_2 | GPIO_PIN_3, GPIO_DIR_MODE_HW);
   GPIODirModeSet(GPIO_PORTF_BASE, GPIO_PIN_2 | GPIO_PIN_3, GPIO_DIR_MODE_HW);
-  GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_2 | GPIO_PIN_3,
-                  GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
+  GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_2 | GPIO_PIN_3, GPIO_STRENGTH_2MA,
+                   GPIO_PIN_TYPE_STD);
 
 
   //
   //
   // Configure the GPIOs used to read the state of the on-board push buttons.
   // Configure the GPIOs used to read the state of the on-board push buttons.
   //
   //
-  GPIOPinTypeGPIOInput(GPIO_PORTE_BASE, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2
-                  | GPIO_PIN_3);
-  GPIOPadConfigSet(GPIO_PORTE_BASE, GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2
-                  | GPIO_PIN_3, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
+  GPIOPinTypeGPIOInput(GPIO_PORTE_BASE,
+                       GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3);
+  GPIOPadConfigSet(GPIO_PORTE_BASE,
+                   GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3,
+                   GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
   GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_1);
   GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_1);
   GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_STRENGTH_2MA,
   GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_1, GPIO_STRENGTH_2MA,
-                  GPIO_PIN_TYPE_STD_WPU);
+                   GPIO_PIN_TYPE_STD_WPU);
 
 
   // configure the user LED output
   // configure the user LED output
   GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_0);
   GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_0);
   GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_0, 0);
   GPIOPinWrite(GPIO_PORTF_BASE, GPIO_PIN_0, 0);
 
 
-
-
   //
   //
   // Configure SysTick for a 100 Hz (10 ms) interrupt.
   // Configure SysTick for a 100 Hz (10 ms) interrupt.
   //
   //
@@ -221,17 +211,15 @@ main(void)
   // using the FlashUserGet function, as illustrated below.
   // using the FlashUserGet function, as illustrated below.
   //
   //
   FlashUserGet(&ulUser0, &ulUser1);
   FlashUserGet(&ulUser0, &ulUser1);
-  if ((ulUser0 == 0xffffffff) || (ulUser1 == 0xffffffff))
-    {
-      //
-      // We should never get here.  This is an error if the MAC address has
-      // not been programmed into the device.  Exit the program.
-      //
-
-      while (1)
-        {
-        }
+  if ((ulUser0 == 0xffffffff) || (ulUser1 == 0xffffffff)) {
+    //
+    // We should never get here.  This is an error if the MAC address has
+    // not been programmed into the device.  Exit the program.
+    //
+
+    while (1) {
     }
     }
+  }
 
 
   //
   //
   // Convert the 24/24 split MAC address from NV ram into a 32/16 split MAC
   // Convert the 24/24 split MAC address from NV ram into a 32/16 split MAC
@@ -249,47 +237,43 @@ main(void)
   //////////////////////////////////////////////////////////
   //////////////////////////////////////////////////////////
   // YOU MUST SET THESE TO VALID VALUES FOR YOUR LOCATION //
   // YOU MUST SET THESE TO VALID VALUES FOR YOUR LOCATION //
   //////////////////////////////////////////////////////////
   //////////////////////////////////////////////////////////
-  configureMACAddress(pucMACArray);
+  ConfigureMacAddress(pucMACArray);
 
 
   //
   //
   // Initialze the lwIP library
   // Initialze the lwIP library
   //
   //
 
 
-
   pl = findNextEmptyParameterBlock();
   pl = findNextEmptyParameterBlock();
   p = (struct parm *) (pl + 1);
   p = (struct parm *) (pl + 1);
 
 
-  if (useStaticIP)
-    {
-      OPENER_TRACE_INFO("using static IP address\n");
-
-      ip = 0x8083BAC9; //128.130.200.201
-      nm = 0xFFFFFF00;
-      gw = 0x8083BA01;
-      valid = 7;
-      lwIPInit(pucMACArray, ip, nm, gw, IPADDR_USE_STATIC);
-    }
-  else
-    {
-      //
-      // Initialze the lwIP library, using DHCP.
-      //
-      OPENER_TRACE_INFO("using DHCP\n");
-      valid = 0; //0
-      lwIPInit(pucMACArray, 0, 0, 0, IPADDR_USE_DHCP);
-    }
+  if (useStaticIP) {
+    OPENER_TRACE_INFO("using static IP address\n");
+
+    ip = 0x8083BAC9;  //128.130.200.201
+    nm = 0xFFFFFF00;
+    gw = 0x8083BA01;
+    valid = 7;
+    lwIPInit(pucMACArray, ip, nm, gw, IPADDR_USE_STATIC);
+  } else {
+    //
+    // Initialze the lwIP library, using DHCP.
+    //
+    OPENER_TRACE_INFO("using DHCP\n");
+    valid = 0;  //0
+    lwIPInit(pucMACArray, 0, 0, 0, IPADDR_USE_DHCP);
+  }
 
 
-    //change time-interval value for call of updateElMeasuringAndMeteringData
-    //in SysTickIntHandler-method to show/provide correct values (see line 370)
+  //change time-interval value for call of updateElMeasuringAndMeteringData
+  //in SysTickIntHandler-method to show/provide correct values (see line 370)
 
 
   IntPrioritySet(INT_ETH, ETHERNET_INT_PRIORITY);
   IntPrioritySet(INT_ETH, ETHERNET_INT_PRIORITY);
   IntPrioritySet(FAULT_SYSTICK, SYSTICK_INT_PRIORITY);
   IntPrioritySet(FAULT_SYSTICK, SYSTICK_INT_PRIORITY);
 
 
   /*for a real device the serial number should be unique per device */
   /*for a real device the serial number should be unique per device */
-  setDeviceSerialNumber(123456789);
+  SetDeviceSerialNumber(123456789);
 
 
   /* Setup the CIP Layer */
   /* Setup the CIP Layer */
-  CIP_Init(365);
+  CipStackInit(365);
   IntMasterDisable();
   IntMasterDisable();
 
 
   IntMasterEnable();
   IntMasterEnable();
@@ -297,25 +281,20 @@ main(void)
 
 
   // this is a simple command interpreter which reads from serial port 0
   // this is a simple command interpreter which reads from serial port 0
   // it is used to set a static IP address
   // it is used to set a static IP address
-  while (1)
-    {
+  while (1) {
 
 
-    }
+  }
 }
 }
 
 
 /* implement missing functions rand and srand */
 /* implement missing functions rand and srand */
-int _EXFUN(rand,(_VOID))
-{
-  return nextXorShiftUInt32();
+int _EXFUN( rand, (_VOID)) {
+  return NextXorShiftUInt32();
 }
 }
 
 
-_VOID   _EXFUN(srand,(unsigned __seed))
-{
-  setXorShiftSeed(__seed);
+_VOID _EXFUN( srand, (unsigned __seed)) {
+  SetXorShiftSeed(__seed);
 }
 }
 
 
-
-
 //*****************************************************************************
 //*****************************************************************************
 //
 //
 // The interrupt handler for the SysTick interrupt.
 // The interrupt handler for the SysTick interrupt.

+ 6 - 18
source/src/ports/LM3S8962/sample_application/opener_user_conf.h

@@ -22,7 +22,6 @@
  *    - inet_addr
  *    - inet_addr
  */
  */
 
 
-
 #include "lwiplib.h"
 #include "lwiplib.h"
 #include "archnw.h"
 #include "archnw.h"
 
 
@@ -45,7 +44,6 @@ struct sockaddr {
 #define socklen_t u32_t
 #define socklen_t u32_t
 #endif
 #endif
 
 
-
 #define SOCK_STREAM     1
 #define SOCK_STREAM     1
 #define  SOL_SOCKET  0xfff    /* options for socket level */
 #define  SOL_SOCKET  0xfff    /* options for socket level */
 #define  SO_BROADCAST   0x0020 /* Unimplemented: permit sending of broadcast msgs */
 #define  SO_BROADCAST   0x0020 /* Unimplemented: permit sending of broadcast msgs */
@@ -68,7 +66,7 @@ struct sockaddr {
 
 
 /*! Define the number of supported explicit connections.
 /*! Define the number of supported explicit connections.
  *  According to ODVA's PUB 70 this number should be greater than 6.
  *  According to ODVA's PUB 70 this number should be greater than 6.
- */  
+ */
 #define OPENER_CIP_NUM_EXPLICIT_CONNS 6
 #define OPENER_CIP_NUM_EXPLICIT_CONNS 6
 
 
 /*! Define the number of supported exclusive owner connections.
 /*! Define the number of supported exclusive owner connections.
@@ -89,7 +87,6 @@ struct sockaddr {
  */
  */
 #define OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH 1
 #define OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH 1
 
 
-
 /*! Define the number of supported listen only connections.
 /*! Define the number of supported listen only connections.
  *  Each of these connections has to be configured with the function
  *  Each of these connections has to be configured with the function
  *  void configureListenOnlyConnectionPoint(unsigned int pa_unConnNum, unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly, unsigned int pa_unConfigAssembly)
  *  void configureListenOnlyConnectionPoint(unsigned int pa_unConnNum, unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly, unsigned int pa_unConfigAssembly)
@@ -101,25 +98,23 @@ struct sockaddr {
  */
  */
 #define OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH   1
 #define OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH   1
 
 
-
 /*! The number of bytes used for the buffer that will be used for generating any
 /*! The number of bytes used for the buffer that will be used for generating any
  *  reply data of messages. There are two uses in OpENer:
  *  reply data of messages. There are two uses in OpENer:
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    2. I/O Connections will use this buffer for the produced data
  *    2. I/O Connections will use this buffer for the produced data
- */ 
+ */
 #define OPENER_MESSAGE_DATA_REPLY_BUFFER 250
 #define OPENER_MESSAGE_DATA_REPLY_BUFFER 250
 
 
 /*! Number of sessions that can be handled at the same time
 /*! Number of sessions that can be handled at the same time
- */ 
+ */
 #define OPENER_NUMBER_OF_SUPPORTED_SESSIONS 4
 #define OPENER_NUMBER_OF_SUPPORTED_SESSIONS 4
 
 
 /*! The time in ms of the timer used in this implementations
 /*! The time in ms of the timer used in this implementations
- */ 
+ */
 #define OPENER_TIMER_TICK 10 
 #define OPENER_TIMER_TICK 10 
 
 
-
 /*! Define if RUN IDLE data is sent with consumed data
 /*! Define if RUN IDLE data is sent with consumed data
- */ 
+ */
 #define OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER 1
 #define OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER 1
 
 
 /*! Define if RUN IDLE data is to be sent with produced data
 /*! Define if RUN IDLE data is to be sent with produced data
@@ -136,7 +131,6 @@ struct sockaddr {
 
 
 /*#define PRINT_TRACE(args...)  fprintf(stderr,args);*/
 /*#define PRINT_TRACE(args...)  fprintf(stderr,args);*/
 
 
-
 /*! A specialized assertion command that will log the assertion and block
 /*! A specialized assertion command that will log the assertion and block
  *  further execution in an while(1) loop.
  *  further execution in an while(1) loop.
  */
  */
@@ -152,7 +146,6 @@ struct sockaddr {
 //#include <assert.h>
 //#include <assert.h>
 //#include <stdio.h>
 //#include <stdio.h>
 //#define OPENER_ASSERT(assertion) assert(assertion)
 //#define OPENER_ASSERT(assertion) assert(assertion)
-
 #else
 #else
 
 
 /* for release builds execute the assertion, but don't test it */
 /* for release builds execute the assertion, but don't test it */
@@ -163,16 +156,13 @@ struct sockaddr {
  *  macro can be used as below
  *  macro can be used as below
  */
  */
 //#define OPENER_ASSERT(assertion)
 //#define OPENER_ASSERT(assertion)
-
 /* else if you still want assertions to stop execution but without tracing, use the following */
 /* else if you still want assertions to stop execution but without tracing, use the following */
 //#define OPENER_ASSERT(assertion) do { if(!(assertion)) { while(1){;} } } while (0)
 //#define OPENER_ASSERT(assertion) do { if(!(assertion)) { while(1){;} } } while (0)
-
 /* else use standard assert() */
 /* else use standard assert() */
 //#include <assert.h>
 //#include <assert.h>
 //#include <stdio.h>
 //#include <stdio.h>
 //#define OPENER_ASSERT(assertion) assert(assertion)
 //#define OPENER_ASSERT(assertion) assert(assertion)
 
 
-
 #endif
 #endif
 
 
 /*! The number of bytes used for the Ethernet message buffer on
 /*! The number of bytes used for the Ethernet message buffer on
@@ -181,14 +171,12 @@ struct sockaddr {
  *
  *
  *  This buffer size will be used for any received message.
  *  This buffer size will be used for any received message.
  *  The same buffer is used for the replied explicit message.
  *  The same buffer is used for the replied explicit message.
- */ 
+ */
 #define PC_OPENER_ETHERNET_BUFFER_SIZE 512
 #define PC_OPENER_ETHERNET_BUFFER_SIZE 512
 
 
-
 /*! If this define is here opener will enable 64Bit data type support.
 /*! If this define is here opener will enable 64Bit data type support.
  *
  *
  */
  */
 #define OPENER_SUPPORT_64BIT_DATATYPES 1
 #define OPENER_SUPPORT_64BIT_DATATYPES 1
 
 
-
 #endif /*OPENER_USER_CONF_H_*/
 #endif /*OPENER_USER_CONF_H_*/

+ 46 - 56
source/src/ports/LM3S8962/stubs.c

@@ -10,71 +10,61 @@
 #include <assert.h>
 #include <assert.h>
 #include <trace.h>
 #include <trace.h>
 
 
-int __errno(void)
-  {
-    return 0;
-  }
+int __errno(void) {
+  return 0;
+}
 
 
-void raise(void)
-  {
-    while (1)
-      ;
-  }
+void raise(void) {
+  while (1)
+    ;
+}
 
 
-void abort(void)
-  {
-    while (1)
-      ;
-  }
+void abort(void) {
+  while (1)
+    ;
+}
 
 
-void BUG(char *s)
-  {
-    while (1)
-      ;
-  }
+void BUG(char *s) {
+  while (1)
+    ;
+}
 
 
 static char dumpbuf[256];
 static char dumpbuf[256];
 
 
 void __assert_func(const char *__file, int __line, const char *__function,
 void __assert_func(const char *__file, int __line, const char *__function,
-    const char *__assertion)
-  {
-    snprintf(dumpbuf, 100,
-        "assert(%s) failed in function %s, file %s, at line %d\n", __assertion,
-        __function, __file, __line);
+                   const char *__assertion) {
+  snprintf(dumpbuf, 100,
+           "assert(%s) failed in function %s, file %s, at line %d\n",
+           __assertion, __function, __file, __line);
 
 
-    OPENER_TRACE_ERR(dumpbuf);
-    while (1)
-      ;
-  }
+  OPENER_TRACE_ERR(dumpbuf);
+  while (1)
+    ;
+}
 
 
-void dump(unsigned char *p, int size)
-  {
-    int i;
-    char *b;
+void dump(unsigned char *p, int size) {
+  int i;
+  char *b;
 
 
-    while (size>0)
-      {
-        b = dumpbuf;
-        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;
-        OPENER_TRACE_INFO("%s\n", dumpbuf);
+  while (size > 0) {
+    b = dumpbuf;
+    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;
+    OPENER_TRACE_INFO("%s\n", dumpbuf);
   }
   }
+}

+ 43 - 55
source/src/ports/POSIX/main.c

@@ -12,8 +12,6 @@
 #include "cipcommon.h"
 #include "cipcommon.h"
 #include "trace.h"
 #include "trace.h"
 
 
-
-
 extern int newfd;
 extern int newfd;
 
 
 /******************************************************************************/
 /******************************************************************************/
@@ -30,40 +28,35 @@ leaveStack(int pa_nSig);
 int g_nEndStack = 0;
 int g_nEndStack = 0;
 
 
 /******************************************************************************/
 /******************************************************************************/
-int
-main(int argc, char *arg[])
-{
-  EIP_UINT8 acMyMACAddress[6];
-  EIP_UINT16 nUniqueConnectionID;
-
-  if (argc != 12)
-    {
-      printf("Wrong number of command line parameters!\n");
-      printf("The correct command line parameters are:\n");
-      printf(
-          "./OpENer ipaddress subnetmask gateway domainname hostaddress macaddress\n");
-      printf(
-          "    e.g. ./OpENer 192.168.0.2 255.255.255.0 192.168.0.1 test.com testdevice 00 15 C5 BF D0 87\n");
-      exit(0);
-    }
-  else
-    {
-      /* fetch Internet address info from the platform */
-      configureNetworkInterface(arg[1], arg[2], arg[3]);
-      configureDomainName(arg[4]);
-      configureHostName(arg[5]);
-
-      acMyMACAddress[0] = (EIP_UINT8) strtoul(arg[6], NULL, 16);
-      acMyMACAddress[1] = (EIP_UINT8) strtoul(arg[7], NULL, 16);
-      acMyMACAddress[2] = (EIP_UINT8) strtoul(arg[8], NULL, 16);
-      acMyMACAddress[3] = (EIP_UINT8) strtoul(arg[9], NULL, 16);
-      acMyMACAddress[4] = (EIP_UINT8) strtoul(arg[10], NULL, 16);
-      acMyMACAddress[5] = (EIP_UINT8) strtoul(arg[11], NULL, 16);
-      configureMACAddress(acMyMACAddress);
-    }
+int main(int argc, char *arg[]) {
+  EipUint8 acMyMACAddress[6];
+  EipUint16 nUniqueConnectionID;
+
+  if (argc != 12) {
+    printf("Wrong number of command line parameters!\n");
+    printf("The correct command line parameters are:\n");
+    printf(
+        "./OpENer ipaddress subnetmask gateway domainname hostaddress macaddress\n");
+    printf(
+        "    e.g. ./OpENer 192.168.0.2 255.255.255.0 192.168.0.1 test.com testdevice 00 15 C5 BF D0 87\n");
+    exit(0);
+  } else {
+    /* fetch Internet address info from the platform */
+    ConfigureNetworkInterface(arg[1], arg[2], arg[3]);
+    ConfigureDomainName(arg[4]);
+    ConfigureHostName(arg[5]);
+
+    acMyMACAddress[0] = (EipUint8) strtoul(arg[6], NULL, 16);
+    acMyMACAddress[1] = (EipUint8) strtoul(arg[7], NULL, 16);
+    acMyMACAddress[2] = (EipUint8) strtoul(arg[8], NULL, 16);
+    acMyMACAddress[3] = (EipUint8) strtoul(arg[9], NULL, 16);
+    acMyMACAddress[4] = (EipUint8) strtoul(arg[10], NULL, 16);
+    acMyMACAddress[5] = (EipUint8) strtoul(arg[11], NULL, 16);
+    ConfigureMacAddress(acMyMACAddress);
+  }
 
 
   /*for a real device the serial number should be unique per device */
   /*for a real device the serial number should be unique per device */
-  setDeviceSerialNumber(123456789);
+  SetDeviceSerialNumber(123456789);
 
 
   /* nUniqueConnectionID should be sufficiently random or incremented and stored
   /* nUniqueConnectionID should be sufficiently random or incremented and stored
    *  in non-volatile memory each time the device boots.
    *  in non-volatile memory each time the device boots.
@@ -71,38 +64,33 @@ main(int argc, char *arg[])
   nUniqueConnectionID = rand();
   nUniqueConnectionID = rand();
 
 
   /* Setup the CIP Layer */
   /* Setup the CIP Layer */
-  CIP_Init(nUniqueConnectionID);
+  CipStackInit(nUniqueConnectionID);
 
 
   /* Setup Network Handles */
   /* Setup Network Handles */
-  if (EIP_OK == NetworkHandler_Init())
-    {
-      g_nEndStack = 0;
+  if (kEipStatusOk == NetworkHandler_Init()) {
+    g_nEndStack = 0;
 #ifndef WIN32
 #ifndef WIN32
-      /* register for closing signals so that we can trigger the stack to end */
-      signal(SIGHUP, leaveStack);
+    /* register for closing signals so that we can trigger the stack to end */
+    signal(SIGHUP, leaveStack);
 #endif
 #endif
 
 
-      /* The event loop. Put other processing you need done continually in here */
-      while (1 != g_nEndStack)
-        {
-          if( EIP_OK != NetworkHandler_ProcessOnce())
-            {
-              break;
-            }
-        }
-
-      /* clean up network state */
-      NetworkHandler_Finish();
+    /* The event loop. Put other processing you need done continually in here */
+    while (1 != g_nEndStack) {
+      if (kEipStatusOk != NetworkHandler_ProcessOnce()) {
+        break;
+      }
     }
     }
+
+    /* clean up network state */
+    NetworkHandler_Finish();
+  }
   /* close remaining sessions and connections, cleanup used data */
   /* close remaining sessions and connections, cleanup used data */
-  shutdownCIP();
+  ShutdownCipStack();
 
 
   return -1;
   return -1;
 }
 }
 
 
-void
-leaveStack(int pa_nSig)
-{
+void leaveStack(int pa_nSig) {
   (void) pa_nSig; /* kill unused parameter warning */
   (void) pa_nSig; /* kill unused parameter warning */
   OPENER_TRACE_STATE("got signal HUP\n");
   OPENER_TRACE_STATE("got signal HUP\n");
   g_nEndStack = 1;
   g_nEndStack = 1;

+ 359 - 426
source/src/ports/POSIX/networkhandler.c

@@ -20,8 +20,8 @@
 #include <ciptcpipinterface.h>
 #include <ciptcpipinterface.h>
 
 
 /* values needed from the connection manager */
 /* values needed from the connection manager */
-extern S_CIP_ConnectionObject *g_pstActiveConnectionList;
-/* communication buffer */EIP_UINT8 g_acPCEthernetCommBuffer[PC_OPENER_ETHERNET_BUFFER_SIZE];
+extern ConnectionObject *g_active_connection_list;
+/* communication buffer */EipUint8 g_acPCEthernetCommBuffer[PC_OPENER_ETHERNET_BUFFER_SIZE];
 
 
 #define MAX_NO_OF_TCP_SOCKETS 10
 #define MAX_NO_OF_TCP_SOCKETS 10
 
 
@@ -61,26 +61,24 @@ void
 checkAndHandleConsumingUDPSockets();
 checkAndHandleConsumingUDPSockets();
 /*! \brief check if the given socket is set in the read set
 /*! \brief check if the given socket is set in the read set
  *
  *
- */EIP_BOOL8
+ */EipBool8
 checkSocketSet(int pa_nSocket);
 checkSocketSet(int pa_nSocket);
 
 
 /*!
 /*!
  *
  *
  */
  */
-EIP_STATUS
+EipStatus
 handleDataOnTCPSocket(int pa_nSocket);
 handleDataOnTCPSocket(int pa_nSocket);
 
 
-static MICROSECONDS
-getMicroseconds()
-{
+static MICROSECONDS getMicroseconds() {
 #ifdef WIN32
 #ifdef WIN32
-    LARGE_INTEGER lPerformanceCouner;
-    LARGE_INTEGER lPerformanceFrequency;
+  LARGE_INTEGER lPerformanceCouner;
+  LARGE_INTEGER lPerformanceFrequency;
 
 
-    QueryPerformanceCounter(&lPerformanceCouner);
-    QueryPerformanceFrequency(&lPerformanceFrequency);
+  QueryPerformanceCounter(&lPerformanceCouner);
+  QueryPerformanceFrequency(&lPerformanceFrequency);
 
 
-    return (MICROSECONDS) (lPerformanceCouner.QuadPart * 1000000LL / lPerformanceFrequency.QuadPart);
+  return (MICROSECONDS) (lPerformanceCouner.QuadPart * 1000000LL / lPerformanceFrequency.QuadPart);
 #else
 #else
   struct timeval tv;
   struct timeval tv;
   gettimeofday(&tv, 0);
   gettimeofday(&tv, 0);
@@ -88,10 +86,8 @@ getMicroseconds()
 #endif
 #endif
 }
 }
 
 
-static MILLISECONDS
-getmilliseconds(void)
-{
-    return (MILLISECONDS) ( getMicroseconds() / 1000ULL );
+static MILLISECONDS getmilliseconds(void) {
+  return (MILLISECONDS) (getMicroseconds() / 1000ULL);
 }
 }
 
 
 /* INT8 Start_NetworkHandler()
 /* INT8 Start_NetworkHandler()
@@ -100,18 +96,15 @@ getmilliseconds(void)
  * 			-1 .. error
  * 			-1 .. error
  */
  */
 
 
-struct NetworkStatus
-{
+struct NetworkStatus {
   int nTCPListener;
   int nTCPListener;
   int nUDPListener;
   int nUDPListener;
   MILLISECONDS elapsedtime;
   MILLISECONDS elapsedtime;
 } PACKED;
 } PACKED;
 
 
-struct NetworkStatus TheNetworkStatus;
+struct NetworkStatus g_network_status;
 
 
-EIP_STATUS
-NetworkHandler_Init(void)
-{
+EipStatus NetworkHandler_Init(void) {
   struct sockaddr_in my_addr;
   struct sockaddr_in my_addr;
   int y;
   int y;
   int nOptVal;
   int nOptVal;
@@ -128,33 +121,31 @@ NetworkHandler_Init(void)
   FD_ZERO(&read_fds);
   FD_ZERO(&read_fds);
 
 
   /* create a new TCP socket */
   /* create a new TCP socket */
-  if ((TheNetworkStatus.nTCPListener = socket(PF_INET, SOCK_STREAM, 0)) == -1)
-    {
-      OPENER_TRACE_ERR("error allocating socket stream listener, %d\n", errno);
-      return EIP_ERROR;
-    }
+  if ((g_network_status.nTCPListener = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
+    OPENER_TRACE_ERR("error allocating socket stream listener, %d\n", errno);
+    return kEipStatusError;
+  }
 
 
   nOptVal = 1;
   nOptVal = 1;
-  if (setsockopt(TheNetworkStatus.nTCPListener, SOL_SOCKET, SO_REUSEADDR,
-      (char *)&nOptVal, sizeof(nOptVal)) == -1)
-    {
-      OPENER_TRACE_ERR("error setting socket option SO_REUSEADDR on nTCPListener\n");
-      return EIP_ERROR;
-    }
+  if (setsockopt(g_network_status.nTCPListener, SOL_SOCKET, SO_REUSEADDR,
+                 (char *) &nOptVal, sizeof(nOptVal)) == -1) {
+    OPENER_TRACE_ERR(
+        "error setting socket option SO_REUSEADDR on nTCPListener\n");
+    return kEipStatusError;
+  }
 
 
   /* create a new UDP socket */
   /* create a new UDP socket */
-  if ((TheNetworkStatus.nUDPListener = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
-    {
-      OPENER_TRACE_ERR("error allocating udp listener socket, %d\n", errno);
-      return EIP_ERROR;
-    }
-
-  if (setsockopt(TheNetworkStatus.nUDPListener, SOL_SOCKET, SO_REUSEADDR,
-      (char *)&nOptVal, sizeof(nOptVal)) == -1)
-    {
-      OPENER_TRACE_ERR("error setting socket option SO_REUSEADDR on nUDPListener\n");
-      return EIP_ERROR;
-    }
+  if ((g_network_status.nUDPListener = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
+    OPENER_TRACE_ERR("error allocating udp listener socket, %d\n", errno);
+    return kEipStatusError;
+  }
+
+  if (setsockopt(g_network_status.nUDPListener, SOL_SOCKET, SO_REUSEADDR,
+                 (char *) &nOptVal, sizeof(nOptVal)) == -1) {
+    OPENER_TRACE_ERR(
+        "error setting socket option SO_REUSEADDR on nUDPListener\n");
+    return kEipStatusError;
+  }
 
 
   my_addr.sin_family = AF_INET;
   my_addr.sin_family = AF_INET;
   my_addr.sin_port = htons(OPENER_ETHERNET_PORT);
   my_addr.sin_port = htons(OPENER_ETHERNET_PORT);
@@ -162,55 +153,52 @@ NetworkHandler_Init(void)
   memset(&my_addr.sin_zero, 0, sizeof(my_addr.sin_zero));
   memset(&my_addr.sin_zero, 0, sizeof(my_addr.sin_zero));
 
 
   /* bind the new socket to port 0xAF12 (CIP) */
   /* bind the new socket to port 0xAF12 (CIP) */
-  if ((bind(TheNetworkStatus.nTCPListener, (struct sockaddr *) &my_addr,
-      sizeof(struct sockaddr))) == -1)
-    {
-      OPENER_TRACE_ERR("error with bind: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+  if ((bind(g_network_status.nTCPListener, (struct sockaddr *) &my_addr,
+            sizeof(struct sockaddr))) == -1) {
+    OPENER_TRACE_ERR("error with bind: %s\n", strerror(errno));
+    return kEipStatusError;
+  }
 
 
   /* enable the udp socket to receive broadcast messages*/
   /* enable the udp socket to receive broadcast messages*/
   y = 1;
   y = 1;
   if (0
   if (0
-      > setsockopt(TheNetworkStatus.nUDPListener, SOL_SOCKET, SO_BROADCAST, (char *)&y,
-          sizeof(int)))
-    {
-      OPENER_TRACE_ERR("error with setting broadcast receive for udp socket: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-
-  if ((bind(TheNetworkStatus.nUDPListener, (struct sockaddr *) &my_addr,
-      sizeof(struct sockaddr))) == -1)
-    {
-      OPENER_TRACE_ERR("error with udp bind: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+      > setsockopt(g_network_status.nUDPListener, SOL_SOCKET, SO_BROADCAST,
+                   (char *) &y, sizeof(int))) {
+    OPENER_TRACE_ERR(
+        "error with setting broadcast receive for udp socket: %s\n",
+        strerror(errno));
+    return kEipStatusError;
+  }
+
+  if ((bind(g_network_status.nUDPListener, (struct sockaddr *) &my_addr,
+            sizeof(struct sockaddr))) == -1) {
+    OPENER_TRACE_ERR("error with udp bind: %s\n", strerror(errno));
+    return kEipStatusError;
+  }
 
 
   /* switch socket in listen mode */
   /* switch socket in listen mode */
-  if ((listen(TheNetworkStatus.nTCPListener, MAX_NO_OF_TCP_SOCKETS)) == -1)
-    {
-      OPENER_TRACE_ERR("networkhandler: error with listen: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+  if ((listen(g_network_status.nTCPListener, MAX_NO_OF_TCP_SOCKETS)) == -1) {
+    OPENER_TRACE_ERR("networkhandler: error with listen: %s\n",
+                     strerror(errno));
+    return kEipStatusError;
+  }
 
 
   /* add the listener socket to the master set */FD_SET(
   /* add the listener socket to the master set */FD_SET(
-      TheNetworkStatus.nTCPListener, &master);
-  FD_SET(TheNetworkStatus.nUDPListener, &master);
+      g_network_status.nTCPListener, &master);
+  FD_SET(g_network_status.nUDPListener, &master);
 
 
   /* keep track of the biggest file descriptor */
   /* keep track of the biggest file descriptor */
   fdmax =
   fdmax =
-      (TheNetworkStatus.nTCPListener > TheNetworkStatus.nUDPListener) ? TheNetworkStatus.nTCPListener :
-          TheNetworkStatus.nUDPListener;
+      (g_network_status.nTCPListener > g_network_status.nUDPListener) ?
+          g_network_status.nTCPListener : g_network_status.nUDPListener;
 
 
   lasttime = getmilliseconds(); /* initialize time keeping */
   lasttime = getmilliseconds(); /* initialize time keeping */
-  TheNetworkStatus.elapsedtime = 0;
+  g_network_status.elapsedtime = 0;
 
 
-  return EIP_OK;
+  return kEipStatusOk;
 }
 }
 
 
-EIP_STATUS
-NetworkHandler_ProcessOnce(void)
-{
+EipStatus NetworkHandler_ProcessOnce(void) {
   int fd;
   int fd;
   int res;
   int res;
 
 
@@ -218,118 +206,97 @@ NetworkHandler_ProcessOnce(void)
 
 
   tv.tv_sec = 0;
   tv.tv_sec = 0;
   tv.tv_usec = (
   tv.tv_usec = (
-      TheNetworkStatus.elapsedtime < OPENER_TIMER_TICK ? OPENER_TIMER_TICK
-          - TheNetworkStatus.elapsedtime :
-          0) * 1000; /* 10 ms */
+      g_network_status.elapsedtime < kOpenerTimerTickInMilliSeconds ?
+          kOpenerTimerTickInMilliSeconds - g_network_status.elapsedtime : 0)
+      * 1000; /* 10 ms */
 
 
   res = select(fdmax + 1, &read_fds, 0, 0, &tv);
   res = select(fdmax + 1, &read_fds, 0, 0, &tv);
 
 
-  if (res == -1)
+  if (res == -1) {
+    if (EINTR == errno) /* we have somehow been interrupted. The default behavior is to go back into the select loop. */
     {
     {
-      if (EINTR == errno) /* we have somehow been interrupted. The default behavior is to go back into the select loop. */
-        {
-          return EIP_OK;
-        }
-      else
-        {
-          OPENER_TRACE_ERR("networkhandler: error with select: %s\n", strerror(errno));
-          return EIP_ERROR;
-        }
+      return kEipStatusOk;
+    } else {
+      OPENER_TRACE_ERR("networkhandler: error with select: %s\n",
+                       strerror(errno));
+      return kEipStatusError;
     }
     }
+  }
 
 
-  if (res > 0)
-    {
+  if (res > 0) {
 
 
-      checkAndHandleTCPListenerSocket();
-      checkAndHandleUDPBroadCastSocket();
-      checkAndHandleConsumingUDPSockets();
+    checkAndHandleTCPListenerSocket();
+    checkAndHandleUDPBroadCastSocket();
+    checkAndHandleConsumingUDPSockets();
 
 
-      for (fd = 0; fd <= fdmax; fd++)
+    for (fd = 0; fd <= fdmax; fd++) {
+      if (true == checkSocketSet(fd)) {
+        /* if it is still checked it is a TCP receive */
+        if (kEipStatusError == handleDataOnTCPSocket(fd)) /* if error */
         {
         {
-          if (true == checkSocketSet(fd))
-            {
-              /* if it is still checked it is a TCP receive */
-              if (EIP_ERROR == handleDataOnTCPSocket(fd)) /* if error */
-                {
-                  IApp_CloseSocket(fd);
-                  closeSession(fd); /* clean up session and close the socket */
-                }
-            }
+          CloseSocket(fd);
+          CloseSession(fd); /* clean up session and close the socket */
         }
         }
+      }
     }
     }
+  }
 
 
   actualtime = getmilliseconds();
   actualtime = getmilliseconds();
-  TheNetworkStatus.elapsedtime += actualtime - lasttime;
+  g_network_status.elapsedtime += actualtime - lasttime;
   lasttime = actualtime;
   lasttime = actualtime;
 
 
   /* check if we had been not able to update the connection manager for several OPENER_TIMER_TICK.
   /* check if we had been not able to update the connection manager for several OPENER_TIMER_TICK.
    * This should compensate the jitter of the windows timer
    * This should compensate the jitter of the windows timer
    */
    */
-  while (TheNetworkStatus.elapsedtime >= OPENER_TIMER_TICK)
-    {
-      /* call manage_connections() in connection manager every OPENER_TIMER_TICK ms */
-      manageConnections();
-      TheNetworkStatus.elapsedtime -= OPENER_TIMER_TICK;
-    }
-  return EIP_OK;
+  while (g_network_status.elapsedtime >= kOpenerTimerTickInMilliSeconds) {
+    /* call manage_connections() in connection manager every OPENER_TIMER_TICK ms */
+    ManageConnections();
+    g_network_status.elapsedtime -= kOpenerTimerTickInMilliSeconds;
+  }
+  return kEipStatusOk;
 }
 }
 
 
-EIP_STATUS
-NetworkHandler_Finish(void)
-{
-  IApp_CloseSocket(TheNetworkStatus.nTCPListener);
-  IApp_CloseSocket(TheNetworkStatus.nUDPListener);
-  return EIP_OK;
+EipStatus NetworkHandler_Finish(void) {
+  CloseSocket(g_network_status.nTCPListener);
+  CloseSocket(g_network_status.nUDPListener);
+  return kEipStatusOk;
 }
 }
 
 
-EIP_BOOL8
-checkSocketSet(int pa_nSocket)
-{
-  EIP_BOOL8 nRetVal = false;
-  if (FD_ISSET(pa_nSocket, &read_fds))
-    {
-      if (FD_ISSET(pa_nSocket, &master))
-        {
-          nRetVal = true;
-        }
-      else
-        {
-          OPENER_TRACE_INFO("socket: %d closed with pending message\n", pa_nSocket);
-        }
-      FD_CLR(pa_nSocket, &read_fds);
-      /* remove it from the read set so that later checks will not find it */
+EipBool8 checkSocketSet(int pa_nSocket) {
+  EipBool8 nRetVal = false;
+  if (FD_ISSET(pa_nSocket, &read_fds)) {
+    if (FD_ISSET(pa_nSocket, &master)) {
+      nRetVal = true;
+    } else {
+      OPENER_TRACE_INFO("socket: %d closed with pending message\n", pa_nSocket);
     }
     }
+    FD_CLR(pa_nSocket, &read_fds);
+    /* remove it from the read set so that later checks will not find it */
+  }
 
 
   return nRetVal;
   return nRetVal;
 }
 }
-EIP_STATUS
-IApp_SendUDPData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
-    EIP_UINT8 *pa_acData, EIP_UINT16 pa_nDataLength)
-{
+EipStatus SendUdpData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
+                      EipUint8 *pa_acData, EipUint16 pa_nDataLength) {
   int sentlength;
   int sentlength;
 
 
   sentlength = sendto(pa_nSockFd, (char *) pa_acData, pa_nDataLength, 0,
   sentlength = sendto(pa_nSockFd, (char *) pa_acData, pa_nDataLength, 0,
-      (struct sockaddr *) pa_pstAddr, sizeof(*pa_pstAddr));
-
-  if (sentlength < 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: error with sendto in sendUDPData: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-  else if (sentlength != pa_nDataLength)
-    {
-      OPENER_TRACE_WARN("not all data was sent in sendUDPData, sent %d of %d\n",
-          sentlength, pa_nDataLength);
-      return EIP_ERROR;
-    }
-  else
-    return EIP_OK;
+                      (struct sockaddr *) pa_pstAddr, sizeof(*pa_pstAddr));
+
+  if (sentlength < 0) {
+    OPENER_TRACE_ERR("networkhandler: error with sendto in sendUDPData: %s\n",
+                     strerror(errno));
+    return kEipStatusError;
+  } else if (sentlength != pa_nDataLength) {
+    OPENER_TRACE_WARN("not all data was sent in sendUDPData, sent %d of %d\n",
+                      sentlength, pa_nDataLength);
+    return kEipStatusError;
+  } else
+    return kEipStatusOk;
 }
 }
 
 
-EIP_STATUS
-handleDataOnTCPSocket(int pa_nSocket)
-{
-  EIP_UINT8 *rxp;
+EipStatus handleDataOnTCPSocket(int pa_nSocket) {
+  EipUint8 *rxp;
   long nCheckVal;
   long nCheckVal;
   size_t unDataSize;
   size_t unDataSize;
   long nDataSent;
   long nDataSent;
@@ -344,115 +311,106 @@ handleDataOnTCPSocket(int pa_nSocket)
   /*Check how many data is here -- read the first four bytes from the connection */
   /*Check how many data is here -- read the first four bytes from the connection */
   nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, 4, 0); /*TODO we may have to set the socket to a non blocking socket */
   nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, 4, 0); /*TODO we may have to set the socket to a non blocking socket */
 
 
-  if (nCheckVal == 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-  if (nCheckVal < 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+  if (nCheckVal == 0) {
+    OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
+                     strerror(errno));
+    return kEipStatusError;
+  }
+  if (nCheckVal < 0) {
+    OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
+    return kEipStatusError;
+  }
 
 
   rxp = &g_acPCEthernetCommBuffer[2]; /* at this place EIP stores the data length */
   rxp = &g_acPCEthernetCommBuffer[2]; /* at this place EIP stores the data length */
-  unDataSize = ltohs(&rxp) + ENCAPSULATION_HEADER_LENGTH - 4; /* -4 is for the 4 bytes we have already read*/
+  unDataSize = GetIntFromMessage(&rxp) + ENCAPSULATION_HEADER_LENGTH - 4; /* -4 is for the 4 bytes we have already read*/
   /* (NOTE this advances the buffer pointer) */
   /* (NOTE this advances the buffer pointer) */
-  if (PC_OPENER_ETHERNET_BUFFER_SIZE - 4 < unDataSize)
-    { /*TODO can this be handled in a better way?*/
-      OPENER_TRACE_ERR("too large packet received will be ignored, will drop the data\n");
-      /* Currently we will drop the whole packet */
-      nDataSent = PC_OPENER_ETHERNET_BUFFER_SIZE;
-
-      do
-        {
-          nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, nDataSent, 0);
-
-          if (nCheckVal == 0) /* got error or connection closed by client */
-            {
-              OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n", strerror(errno));
-              return EIP_ERROR;
-            }
-          if (nCheckVal < 0)
-            {
-              OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-              return EIP_ERROR;
-            }
-          unDataSize -= nCheckVal;
-          if ((unDataSize < PC_OPENER_ETHERNET_BUFFER_SIZE)
-              && (unDataSize != 0))
-            {
-              nDataSent = unDataSize;
-            }
-        }
-      while (0 != unDataSize); /*TODO fragile end statement */
-      return EIP_OK;
-    }
+  if (PC_OPENER_ETHERNET_BUFFER_SIZE - 4 < unDataSize) { /*TODO can this be handled in a better way?*/
+    OPENER_TRACE_ERR(
+        "too large packet received will be ignored, will drop the data\n");
+    /* Currently we will drop the whole packet */
+    nDataSent = PC_OPENER_ETHERNET_BUFFER_SIZE;
+
+    do {
+      nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, nDataSent, 0);
+
+      if (nCheckVal == 0) /* got error or connection closed by client */
+      {
+        OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
+                         strerror(errno));
+        return kEipStatusError;
+      }
+      if (nCheckVal < 0) {
+        OPENER_TRACE_ERR("networkhandler: error on recv: %s\n",
+                         strerror(errno));
+        return kEipStatusError;
+      }
+      unDataSize -= nCheckVal;
+      if ((unDataSize < PC_OPENER_ETHERNET_BUFFER_SIZE) && (unDataSize != 0)) {
+        nDataSent = unDataSize;
+      }
+    } while (0 != unDataSize); /*TODO fragile end statement */
+    return kEipStatusOk;
+  }
 
 
   nCheckVal = recv(pa_nSocket, &g_acPCEthernetCommBuffer[4], unDataSize, 0);
   nCheckVal = recv(pa_nSocket, &g_acPCEthernetCommBuffer[4], unDataSize, 0);
 
 
   if (nCheckVal == 0) /* got error or connection closed by client */
   if (nCheckVal == 0) /* got error or connection closed by client */
-    {
-      OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n", strerror(errno));
-      return EIP_ERROR;
+  {
+    OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
+                     strerror(errno));
+    return kEipStatusError;
+  }
+  if (nCheckVal < 0) {
+    OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
+    return kEipStatusError;
+  }
+
+  if ((unsigned) nCheckVal == unDataSize) {
+    /*we got the right amount of data */
+    unDataSize += 4;
+    /*TODO handle partial packets*/
+    OPENER_TRACE_INFO("Data received on tcp:\n");
+
+    g_nCurrentActiveTCPSocket = pa_nSocket;
+
+    nCheckVal = HandleReceivedExplictTcpData(pa_nSocket,
+                                             g_acPCEthernetCommBuffer,
+                                             unDataSize, &nRemainingBytes);
+
+    g_nCurrentActiveTCPSocket = -1;
+
+    if (nRemainingBytes != 0) {
+      OPENER_TRACE_WARN(
+          "Warning: received packet was to long: %d Bytes left!\n",
+          nRemainingBytes);
     }
     }
-  if (nCheckVal < 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-
-  if ((unsigned) nCheckVal == unDataSize)
-    {
-      /*we got the right amount of data */
-      unDataSize += 4;
-      /*TODO handle partial packets*/
-      OPENER_TRACE_INFO("Data received on tcp:\n");
-
-      g_nCurrentActiveTCPSocket = pa_nSocket;
-
-      nCheckVal = handleReceivedExplictTCPData(pa_nSocket,
-          g_acPCEthernetCommBuffer, unDataSize, &nRemainingBytes);
-
-      g_nCurrentActiveTCPSocket = -1;
 
 
-      if (nRemainingBytes != 0)
-        {
-          OPENER_TRACE_WARN("Warning: received packet was to long: %d Bytes left!\n",
-              nRemainingBytes);
-        }
+    if (nCheckVal > 0) {
+      OPENER_TRACE_INFO("reply sent:\n");
 
 
-      if (nCheckVal > 0)
-        {
-          OPENER_TRACE_INFO("reply sent:\n");
-
-          nDataSent = send(pa_nSocket, (char *) g_acPCEthernetCommBuffer,
-              nCheckVal, 0);
-          if (nDataSent != nCheckVal)
-            {
-              OPENER_TRACE_WARN("TCP response was not fully sent\n");
-            }
-        }
-
-      return EIP_OK;
-    }
-  else
-    {
-      /* we got a fragmented packet currently we cannot handle this will
-       * for this we would need a network buffer per TCP socket
-       *
-       * However with typical packet sizes of EIP this should't be a big issue.
-       */
-      /*TODO handle fragmented packets */
+      nDataSent = send(pa_nSocket, (char *) g_acPCEthernetCommBuffer, nCheckVal,
+                       0);
+      if (nDataSent != nCheckVal) {
+        OPENER_TRACE_WARN("TCP response was not fully sent\n");
+      }
     }
     }
-  return EIP_ERROR;
+
+    return kEipStatusOk;
+  } else {
+    /* we got a fragmented packet currently we cannot handle this will
+     * for this we would need a network buffer per TCP socket
+     *
+     * However with typical packet sizes of EIP this should't be a big issue.
+     */
+    /*TODO handle fragmented packets */
+  }
+  return kEipStatusError;
 }
 }
 
 
 /* create a new UDP socket for the connection manager
 /* create a new UDP socket for the connection manager
  returns the fd if successful, else -1 */
  returns the fd if successful, else -1 */
-int
-IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr)
-{
+int CreateUdpSocket(UdpCommuncationDirection communication_direction,
+                    struct sockaddr_in *socket_data) {
   struct sockaddr_in stPeerAdr;
   struct sockaddr_in stPeerAdr;
   int newfd;
   int newfd;
 #ifdef WIN32
 #ifdef WIN32
@@ -463,139 +421,121 @@ IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr)
 
 
   nPeerAddrLen = sizeof(struct sockaddr_in);
   nPeerAddrLen = sizeof(struct sockaddr_in);
   /* create a new UDP socket */
   /* create a new UDP socket */
-  if ((newfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
-    {
-      OPENER_TRACE_ERR("networkhandler: cannot create UDP socket: %s\n", strerror(errno));
-      return EIP_INVALID_SOCKET;
-    }
+  if ((newfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
+    OPENER_TRACE_ERR("networkhandler: cannot create UDP socket: %s\n",
+                     strerror(errno));
+    return kEipInvalidSocket;
+  }
 
 
   OPENER_TRACE_INFO("networkhandler: UDP socket %d\n", newfd);
   OPENER_TRACE_INFO("networkhandler: UDP socket %d\n", newfd);
 
 
   /* check if it is sending or receiving */
   /* check if it is sending or receiving */
-  if (pa_nDirection == CONSUMING)
-    {
-      int nOptVal = 1;
-      if (setsockopt(newfd, SOL_SOCKET, SO_REUSEADDR, (char *)&nOptVal, sizeof(nOptVal))
-          == -1)
-        {
-          OPENER_TRACE_ERR("error setting socket option SO_REUSEADDR on consuming udp socket\n");
-          return EIP_ERROR;
-        }
-
-      /* bind is only for consuming necessary */
-      if ((bind(newfd, (struct sockaddr *) pa_pstAddr, sizeof(struct sockaddr)))
-          == -1)
-        {
-          OPENER_TRACE_ERR("error on bind udp: %s\n", strerror(errno));
-          return EIP_INVALID_SOCKET;
-        }
-
-      OPENER_TRACE_INFO("networkhandler: bind UDP socket %d\n", newfd);
+  if (communication_direction == kUdpCommuncationDirectionConsuming) {
+    int nOptVal = 1;
+    if (setsockopt(newfd, SOL_SOCKET, SO_REUSEADDR, (char *) &nOptVal,
+                   sizeof(nOptVal)) == -1) {
+      OPENER_TRACE_ERR(
+          "error setting socket option SO_REUSEADDR on consuming udp socket\n");
+      return kEipStatusError;
     }
     }
-  else
-    { /* we have a producing udp socket */
 
 
-      if (pa_pstAddr->sin_addr.s_addr == g_stMultiCastconfig.m_unMcastStartAddr)
-        {
-          if (1 != g_unTTLValue)
-            { /* we need to set a TTL value for the socket */
-              if (setsockopt(newfd, IPPROTO_IP, IP_MULTICAST_TTL,
-                  &g_unTTLValue, sizeof(g_unTTLValue) < 0))
-                {
-                  OPENER_TRACE_ERR("networkhandler: could not set the TTL to: %d, error: %s\n", g_unTTLValue, strerror(errno));
-                  return EIP_INVALID_SOCKET;
-                }
-            }
-        }
+    /* bind is only for consuming necessary */
+    if ((bind(newfd, (struct sockaddr *) socket_data, sizeof(struct sockaddr)))
+        == -1) {
+      OPENER_TRACE_ERR("error on bind udp: %s\n", strerror(errno));
+      return kEipInvalidSocket;
     }
     }
 
 
-  if ((pa_nDirection == CONSUMING) || (0 == pa_pstAddr->sin_addr.s_addr))
-    {
-      /* we have a peer to peer producer or a consuming connection*/
-      if (getpeername(g_nCurrentActiveTCPSocket, (struct sockaddr *) &stPeerAdr,
-          &nPeerAddrLen) < 0)
-        {
-          OPENER_TRACE_ERR("networkhandler: could not get peername: %s\n", strerror(errno));
-          return EIP_INVALID_SOCKET;
+    OPENER_TRACE_INFO("networkhandler: bind UDP socket %d\n", newfd);
+  } else { /* we have a producing udp socket */
+
+    if (socket_data->sin_addr.s_addr
+        == g_multicast_configuration.starting_multicast_address) {
+      if (1 != g_time_to_live_value) { /* we need to set a TTL value for the socket */
+        if (setsockopt(newfd, IPPROTO_IP, IP_MULTICAST_TTL,
+                       &g_time_to_live_value,
+                       sizeof(g_time_to_live_value) < 0)) {
+          OPENER_TRACE_ERR(
+              "networkhandler: could not set the TTL to: %d, error: %s\n",
+              g_time_to_live_value, strerror(errno));
+          return kEipInvalidSocket;
         }
         }
-      /* store the originators address */
-      pa_pstAddr->sin_addr.s_addr = stPeerAdr.sin_addr.s_addr;
+      }
+    }
+  }
+
+  if ((communication_direction == kUdpCommuncationDirectionConsuming)
+      || (0 == socket_data->sin_addr.s_addr)) {
+    /* we have a peer to peer producer or a consuming connection*/
+    if (getpeername(g_nCurrentActiveTCPSocket, (struct sockaddr *) &stPeerAdr,
+                    &nPeerAddrLen) < 0) {
+      OPENER_TRACE_ERR("networkhandler: could not get peername: %s\n",
+                       strerror(errno));
+      return kEipInvalidSocket;
     }
     }
+    /* store the originators address */
+    socket_data->sin_addr.s_addr = stPeerAdr.sin_addr.s_addr;
+  }
 
 
   /* add new fd to the master list                                             */
   /* add new fd to the master list                                             */
   FD_SET(newfd, &master);
   FD_SET(newfd, &master);
-  if (newfd > fdmax)
-    {
-      fdmax = newfd;
-    }
+  if (newfd > fdmax) {
+    fdmax = newfd;
+  }
   return newfd;
   return newfd;
 }
 }
 
 
-void
-IApp_CloseSocket_udp(int pa_nSockFd)
-{
-	IApp_CloseSocket(pa_nSockFd);
+void IApp_CloseSocket_udp(int pa_nSockFd) {
+  CloseSocket(pa_nSockFd);
 }
 }
 
 
-void
-IApp_CloseSocket_tcp(int pa_nSockFd)
-{
-	IApp_CloseSocket(pa_nSockFd);
+void IApp_CloseSocket_tcp(int pa_nSockFd) {
+  CloseSocket(pa_nSockFd);
 }
 }
 
 
-void
-IApp_CloseSocket(int pa_nSockFd)
-{
+void CloseSocket(int pa_nSockFd) {
 
 
   OPENER_TRACE_INFO("networkhandler: closing socket %d\n", pa_nSockFd);
   OPENER_TRACE_INFO("networkhandler: closing socket %d\n", pa_nSockFd);
-  if (EIP_INVALID_SOCKET != pa_nSockFd)
-    {
-      FD_CLR(pa_nSockFd, &master);
+  if (kEipInvalidSocket != pa_nSockFd) {
+    FD_CLR(pa_nSockFd, &master);
 #ifdef WIN32
 #ifdef WIN32
-      closesocket(pa_nSockFd);
+    closesocket(pa_nSockFd);
 #else
 #else
-      shutdown(pa_nSockFd, SHUT_RDWR);
-      close(pa_nSockFd);
+    shutdown(pa_nSockFd, SHUT_RDWR);
+    close(pa_nSockFd);
 #endif
 #endif
-    }
+  }
 }
 }
 
 
-void
-checkAndHandleTCPListenerSocket()
-{
+void checkAndHandleTCPListenerSocket() {
   int newfd;
   int newfd;
   /* see if this is a connection request to the TCP listener*/
   /* see if this is a connection request to the TCP listener*/
-  if (true == checkSocketSet(TheNetworkStatus.nTCPListener))
-    {
-      OPENER_TRACE_INFO("networkhandler: new TCP connection\n");
-
-      newfd = accept(TheNetworkStatus.nTCPListener, NULL, NULL);
-      if (newfd == -1)
-        {
-          OPENER_TRACE_ERR("networkhandler: error on accept: %s\n", strerror(errno));
-          return;
-        }
-
-      FD_SET(newfd, &master);
-      /* add newfd to master set */
-      if (newfd > fdmax)
-        {
-          fdmax = newfd;
-        }
+  if (true == checkSocketSet(g_network_status.nTCPListener)) {
+    OPENER_TRACE_INFO("networkhandler: new TCP connection\n");
+
+    newfd = accept(g_network_status.nTCPListener, NULL, NULL);
+    if (newfd == -1) {
+      OPENER_TRACE_ERR("networkhandler: error on accept: %s\n",
+                       strerror(errno));
+      return;
+    }
 
 
-      OPENER_TRACE_STATE(
-          "networkhandler: opened new TCP connection on fd %d\n",
-          newfd);
+    FD_SET(newfd, &master);
+    /* add newfd to master set */
+    if (newfd > fdmax) {
+      fdmax = newfd;
     }
     }
+
+    OPENER_TRACE_STATE("networkhandler: opened new TCP connection on fd %d\n",
+                       newfd);
+  }
 }
 }
 
 
-void
-checkAndHandleUDPBroadCastSocket()
-{
+void checkAndHandleUDPBroadCastSocket() {
   int nReceived_size;
   int nReceived_size;
   int nRemainingBytes;
   int nRemainingBytes;
   int nReplyLen;
   int nReplyLen;
-  EIP_UINT8 *rxp;
+  EipUint8 *rxp;
   struct sockaddr_in stFrom;
   struct sockaddr_in stFrom;
 #ifndef WIN32
 #ifndef WIN32
   socklen_t nFromLen;
   socklen_t nFromLen;
@@ -604,60 +544,53 @@ checkAndHandleUDPBroadCastSocket()
 #endif
 #endif
 
 
   /* see if this is an unsolicited inbound UDP message */
   /* see if this is an unsolicited inbound UDP message */
-  if (true == checkSocketSet(TheNetworkStatus.nUDPListener))
-    {
+  if (true == checkSocketSet(g_network_status.nUDPListener)) {
 
 
-      nFromLen = sizeof(stFrom);
+    nFromLen = sizeof(stFrom);
 
 
-      OPENER_TRACE_STATE(
-          "networkhandler: unsolicited UDP message on EIP broadcast socket\n");
+    OPENER_TRACE_STATE(
+        "networkhandler: unsolicited UDP message on EIP broadcast socket\n");
 
 
-      /*Handle udp broadcast messages */
-      nReceived_size = recvfrom(TheNetworkStatus.nUDPListener,
-          g_acPCEthernetCommBuffer, PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
-          (struct sockaddr *) &stFrom, &nFromLen);
+    /*Handle udp broadcast messages */
+    nReceived_size = recvfrom(g_network_status.nUDPListener,
+                              g_acPCEthernetCommBuffer,
+                              PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
+                              (struct sockaddr *) &stFrom, &nFromLen);
 
 
-      if (nReceived_size <= 0)
-        { /* got error */
-          OPENER_TRACE_ERR(
-              "networkhandler: error on recvfrom udp broadcast port: %s\n",
-              strerror(errno));
-          return;
-        }
+    if (nReceived_size <= 0) { /* got error */
+      OPENER_TRACE_ERR(
+          "networkhandler: error on recvfrom udp broadcast port: %s\n",
+          strerror(errno));
+      return;
+    }
 
 
-      OPENER_TRACE_INFO("Data received on udp:\n");
+    OPENER_TRACE_INFO("Data received on udp:\n");
 
 
-      rxp = &g_acPCEthernetCommBuffer[0];
-      do
-        {
-          nReplyLen = handleReceivedExplictUDPData(
-              TheNetworkStatus.nUDPListener, &stFrom, rxp, nReceived_size,
-              &nRemainingBytes);
-
-          rxp += nReceived_size - nRemainingBytes;
-          nReceived_size = nRemainingBytes;
-
-          if (nReplyLen > 0)
-            {
-              OPENER_TRACE_INFO("reply sent:\n");
-
-              /* if the active fd matches a registered UDP callback, handle a UDP packet */
-              if (sendto(TheNetworkStatus.nUDPListener,
-                  (char *) g_acPCEthernetCommBuffer, nReplyLen, 0,
-                  (struct sockaddr *) &stFrom, sizeof(stFrom)) != nReplyLen)
-                {
-                  OPENER_TRACE_INFO(
-                      "networkhandler: UDP response was not fully sent\n");
-                }
-            }
+    rxp = &g_acPCEthernetCommBuffer[0];
+    do {
+      nReplyLen = HandleReceivedExplictUdpData(g_network_status.nUDPListener,
+                                               &stFrom, rxp, nReceived_size,
+                                               &nRemainingBytes);
+
+      rxp += nReceived_size - nRemainingBytes;
+      nReceived_size = nRemainingBytes;
+
+      if (nReplyLen > 0) {
+        OPENER_TRACE_INFO("reply sent:\n");
+
+        /* if the active fd matches a registered UDP callback, handle a UDP packet */
+        if (sendto(g_network_status.nUDPListener,
+                   (char *) g_acPCEthernetCommBuffer, nReplyLen, 0,
+                   (struct sockaddr *) &stFrom, sizeof(stFrom)) != nReplyLen) {
+          OPENER_TRACE_INFO(
+              "networkhandler: UDP response was not fully sent\n");
         }
         }
-      while (nRemainingBytes > 0);
-    }
+      }
+    } while (nRemainingBytes > 0);
+  }
 }
 }
 
 
-void
-checkAndHandleConsumingUDPSockets()
-{
+void checkAndHandleConsumingUDPSockets() {
   int nReceived_size;
   int nReceived_size;
   struct sockaddr_in stFrom;
   struct sockaddr_in stFrom;
 #ifndef WIN32
 #ifndef WIN32
@@ -666,39 +599,39 @@ checkAndHandleConsumingUDPSockets()
   unsigned long nFromLen;
   unsigned long nFromLen;
 #endif
 #endif
 
 
-  S_CIP_ConnectionObject *pstRunner = g_pstActiveConnectionList;
-  S_CIP_ConnectionObject *pstCurrent;
+  ConnectionObject *pstRunner = g_active_connection_list;
+  ConnectionObject *pstCurrent;
 
 
   /* see a message on one of the registered UDP sockets has been received     */
   /* see a message on one of the registered UDP sockets has been received     */
-  while (NULL != pstRunner)
-    {
-      pstCurrent = pstRunner;
-      pstRunner = pstRunner->m_pstNext; /* do this at the beginning as the close function may can make the entry invalid */
-
-      if ((-1 != pstCurrent->sockfd[CONSUMING])
-          && (true == checkSocketSet(pstCurrent->sockfd[CONSUMING])))
-        {
-          nFromLen = sizeof(stFrom);
-          nReceived_size = recvfrom(pstCurrent->sockfd[CONSUMING],
-              g_acPCEthernetCommBuffer, PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
-              (struct sockaddr *) &stFrom, &nFromLen);
-          if (0 == nReceived_size)
-            {
-              OPENER_TRACE_STATE("connection closed by client\n");
-              pstCurrent->m_pfCloseFunc(pstCurrent);
-              continue;
-            }
-
-          if (0 > nReceived_size)
-            {
-              OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-              pstCurrent->m_pfCloseFunc(pstCurrent);
-              continue;
-            }
-
-          handleReceivedConnectedData(g_acPCEthernetCommBuffer, nReceived_size,
-              &stFrom);
+  while (NULL != pstRunner) {
+    pstCurrent = pstRunner;
+    pstRunner = pstRunner->next_connection_object; /* do this at the beginning as the close function may can make the entry invalid */
+
+    if ((-1 != pstCurrent->socket[kUdpCommuncationDirectionConsuming])
+        && (true
+            == checkSocketSet(
+                pstCurrent->socket[kUdpCommuncationDirectionConsuming]))) {
+      nFromLen = sizeof(stFrom);
+      nReceived_size = recvfrom(
+          pstCurrent->socket[kUdpCommuncationDirectionConsuming],
+          g_acPCEthernetCommBuffer, PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
+          (struct sockaddr *) &stFrom, &nFromLen);
+      if (0 == nReceived_size) {
+        OPENER_TRACE_STATE("connection closed by client\n");
+        pstCurrent->connection_close_function(pstCurrent);
+        continue;
+      }
+
+      if (0 > nReceived_size) {
+        OPENER_TRACE_ERR("networkhandler: error on recv: %s\n",
+                         strerror(errno));
+        pstCurrent->connection_close_function(pstCurrent);
+        continue;
+      }
+
+      HandleReceivedConnectedData(g_acPCEthernetCommBuffer, nReceived_size,
+                                  &stFrom);
 
 
-        }
     }
     }
+  }
 }
 }

+ 3 - 4
source/src/ports/POSIX/networkhandler.h

@@ -8,13 +8,12 @@
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 
 
-
 /*! Start a TCP/UDP listening socket, accept connections, receive data in select loop, call manageConnections periodically.
 /*! Start a TCP/UDP listening socket, accept connections, receive data in select loop, call manageConnections periodically.
  *  @return status
  *  @return status
  *          EIP_ERROR .. error
  *          EIP_ERROR .. error
  */
  */
-EIP_STATUS NetworkHandler_Init(void);
-EIP_STATUS NetworkHandler_ProcessOnce(void);
-EIP_STATUS NetworkHandler_Finish(void);
+EipStatus NetworkHandler_Init(void);
+EipStatus NetworkHandler_ProcessOnce(void);
+EipStatus NetworkHandler_Finish(void);
 
 
 #endif /*NETWORKHANDLER_H_*/
 #endif /*NETWORKHANDLER_H_*/

+ 9 - 20
source/src/ports/POSIX/sample_application/opener_user_conf.h

@@ -48,7 +48,7 @@ typedef unsigned short in_port_t;
 
 
 /*! Define the number of supported explicit connections.
 /*! Define the number of supported explicit connections.
  *  According to ODVA's PUB 70 this number should be greater than 6.
  *  According to ODVA's PUB 70 this number should be greater than 6.
- */  
+ */
 #define OPENER_CIP_NUM_EXPLICIT_CONNS 6
 #define OPENER_CIP_NUM_EXPLICIT_CONNS 6
 
 
 /*! Define the number of supported exclusive owner connections.
 /*! Define the number of supported exclusive owner connections.
@@ -69,7 +69,6 @@ typedef unsigned short in_port_t;
  */
  */
 #define OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH 3
 #define OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH 3
 
 
-
 /*! Define the number of supported listen only connections.
 /*! Define the number of supported listen only connections.
  *  Each of these connections has to be configured with the function
  *  Each of these connections has to be configured with the function
  *  void configureListenOnlyConnectionPoint(unsigned int pa_unConnNum, unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly, unsigned int pa_unConfigAssembly)
  *  void configureListenOnlyConnectionPoint(unsigned int pa_unConnNum, unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly, unsigned int pa_unConfigAssembly)
@@ -81,34 +80,30 @@ typedef unsigned short in_port_t;
  */
  */
 #define OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH   3
 #define OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH   3
 
 
-
 /*! The number of bytes used for the buffer that will be used for generating any
 /*! The number of bytes used for the buffer that will be used for generating any
  *  reply data of messages. There are two uses in OpENer:
  *  reply data of messages. There are two uses in OpENer:
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    2. I/O Connections will use this buffer for the produced data
  *    2. I/O Connections will use this buffer for the produced data
- */ 
+ */
 #define OPENER_MESSAGE_DATA_REPLY_BUFFER 100
 #define OPENER_MESSAGE_DATA_REPLY_BUFFER 100
 
 
 /*! Number of sessions that can be handled at the same time
 /*! Number of sessions that can be handled at the same time
- */ 
+ */
 #define OPENER_NUMBER_OF_SUPPORTED_SESSIONS 20
 #define OPENER_NUMBER_OF_SUPPORTED_SESSIONS 20
 
 
 /*! The time in ms of the timer used in this implementations
 /*! The time in ms of the timer used in this implementations
- */ 
-#define OPENER_TIMER_TICK 10 
-
+ */
+static const int kOpenerTimerTickInMilliSeconds = 10;
 
 
 /*! Define if RUN IDLE data is sent with consumed data
 /*! Define if RUN IDLE data is sent with consumed data
- */ 
-#define OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER 1
+ */
+static const int kOpenerConsumedDataHasRunIdleHeader = 1;
 
 
 /*! Define if RUN IDLE data is to be sent with produced data
 /*! Define if RUN IDLE data is to be sent with produced data
  *
  *
  * Per default we don't send run idle headers with produced data
  * Per default we don't send run idle headers with produced data
  */
  */
-#define OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER 0
-
-
+static const int kOpenerProducedDataHasRunIdleHeader = 0;
 
 
 #ifdef OPENER_WITH_TRACES
 #ifdef OPENER_WITH_TRACES
 /* If we have tracing enabled provide print tracing macro */
 /* If we have tracing enabled provide print tracing macro */
@@ -118,7 +113,6 @@ typedef unsigned short in_port_t;
 
 
 /*#define PRINT_TRACE(args...)  fprintf(stderr,args);*/
 /*#define PRINT_TRACE(args...)  fprintf(stderr,args);*/
 
 
-
 /*! A specialized assertion command that will log the assertion and block
 /*! A specialized assertion command that will log the assertion and block
  *  further execution in an while(1) loop.
  *  further execution in an while(1) loop.
  */
  */
@@ -134,7 +128,6 @@ typedef unsigned short in_port_t;
 //#include <assert.h>
 //#include <assert.h>
 //#include <stdio.h>
 //#include <stdio.h>
 //#define OPENER_ASSERT(assertion) assert(assertion)
 //#define OPENER_ASSERT(assertion) assert(assertion)
-
 #else
 #else
 
 
 /* for release builds execute the assertion, but don't test it */
 /* for release builds execute the assertion, but don't test it */
@@ -145,16 +138,13 @@ typedef unsigned short in_port_t;
  *  macro can be used as below
  *  macro can be used as below
  */
  */
 //#define OPENER_ASSERT(assertion)
 //#define OPENER_ASSERT(assertion)
-
 /* else if you still want assertions to stop execution but without tracing, use the following */
 /* else if you still want assertions to stop execution but without tracing, use the following */
 //#define OPENER_ASSERT(assertion) do { if(!(assertion)) { while(1){;} } } while (0)
 //#define OPENER_ASSERT(assertion) do { if(!(assertion)) { while(1){;} } } while (0)
-
 /* else use standard assert() */
 /* else use standard assert() */
 //#include <assert.h>
 //#include <assert.h>
 //#include <stdio.h>
 //#include <stdio.h>
 //#define OPENER_ASSERT(assertion) assert(assertion)
 //#define OPENER_ASSERT(assertion) assert(assertion)
 
 
-
 #endif
 #endif
 
 
 /*! The number of bytes used for the Ethernet message buffer on
 /*! The number of bytes used for the Ethernet message buffer on
@@ -163,10 +153,9 @@ typedef unsigned short in_port_t;
  *
  *
  *  This buffer size will be used for any received message.
  *  This buffer size will be used for any received message.
  *  The same buffer is used for the replied explicit message.
  *  The same buffer is used for the replied explicit message.
- */ 
+ */
 #define PC_OPENER_ETHERNET_BUFFER_SIZE 512
 #define PC_OPENER_ETHERNET_BUFFER_SIZE 512
 
 
-
 /*! If this define is here opener will enable 64Bit data type support.
 /*! If this define is here opener will enable 64Bit data type support.
  *
  *
  */
  */

+ 71 - 89
source/src/ports/POSIX/sample_application/sampleapplication.c

@@ -8,7 +8,6 @@
 #include <string.h>
 #include <string.h>
 #include <stdlib.h>
 #include <stdlib.h>
 
 
-
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
@@ -18,145 +17,128 @@
 
 
 /* global variables for demo application (4 assembly data fields)  ************/
 /* global variables for demo application (4 assembly data fields)  ************/
 
 
-EIP_UINT8 g_assemblydata064[32]; /* Input */
-EIP_UINT8 g_assemblydata096[32]; /* Output */
-EIP_UINT8 g_assemblydata097[10]; /* Config */
-EIP_UINT8 g_assemblydata09A[32]; /* Explicit */
+EipUint8 g_assemblydata064[32]; /* Input */
+EipUint8 g_assemblydata096[32]; /* Output */
+EipUint8 g_assemblydata097[10]; /* Config */
+EipUint8 g_assemblydata09A[32]; /* Explicit */
 
 
-EIP_STATUS
-IApp_Init(void)
-{
+EipStatus ApplicationInitialization(void) {
   /* create 3 assembly object instances*/
   /* create 3 assembly object instances*/
   /*INPUT*/
   /*INPUT*/
-  createAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, &g_assemblydata064[0],
-      sizeof(g_assemblydata064));
+  CreateAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, &g_assemblydata064[0],
+                       sizeof(g_assemblydata064));
 
 
   /*OUTPUT*/
   /*OUTPUT*/
-  createAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, &g_assemblydata096[0],
-      sizeof(g_assemblydata096));
+  CreateAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, &g_assemblydata096[0],
+                       sizeof(g_assemblydata096));
 
 
   /*CONFIG*/
   /*CONFIG*/
-  createAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, &g_assemblydata097[0],
-      sizeof(g_assemblydata097));
+  CreateAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, &g_assemblydata097[0],
+                       sizeof(g_assemblydata097));
 
 
   /*Heart-beat output assembly for Input only connections */
   /*Heart-beat output assembly for Input only connections */
-  createAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /*Heart-beat output assembly for Listen only connections */
   /*Heart-beat output assembly for Listen only connections */
-  createAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /* assembly for explicit messaging */
   /* assembly for explicit messaging */
-  createAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assemblydata09A[0],
-      sizeof(g_assemblydata09A));
-
-  configureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM,
-      DEMO_APP_INPUT_ASSEMBLY_NUM, DEMO_APP_CONFIG_ASSEMBLY_NUM);
-  configureInputOnlyConnectionPoint(0,
-      DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, DEMO_APP_INPUT_ASSEMBLY_NUM,
-      DEMO_APP_CONFIG_ASSEMBLY_NUM);
-  configureListenOnlyConnectionPoint(0,
-      DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, DEMO_APP_INPUT_ASSEMBLY_NUM,
-      DEMO_APP_CONFIG_ASSEMBLY_NUM);
-
-  return EIP_OK;
+  CreateAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assemblydata09A[0],
+                       sizeof(g_assemblydata09A));
+
+  ConfigureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM,
+  DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                         DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  ConfigureInputOnlyConnectionPoint(0,
+  DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM,
+                                    DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                    DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  ConfigureListenOnlyConnectionPoint(0,
+  DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM,
+                                     DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                     DEMO_APP_CONFIG_ASSEMBLY_NUM);
+
+  return kEipStatusOk;
 }
 }
 
 
-void
-IApp_HandleApplication(void)
-{
+void HandleApplication(void) {
   /* check if application needs to trigger an connection */
   /* check if application needs to trigger an connection */
 }
 }
 
 
-void
-IApp_IOConnectionEvent(unsigned int pa_unOutputAssembly,
-    unsigned int pa_unInputAssembly, EIOConnectionEvent pa_eIOConnectionEvent)
-{
+void IoConnectionEvent(unsigned int output_assembly_id,
+                       unsigned int input_assembly_id,
+                       IoConnectionEvents io_connection_event) {
   /* maintain a correct output state according to the connection state*/
   /* maintain a correct output state according to the connection state*/
 
 
-  (void) pa_unOutputAssembly; /* suppress compiler warning */
-  (void) pa_unInputAssembly; /* suppress compiler warning */
-  (void) pa_eIOConnectionEvent; /* suppress compiler warning */
+  (void) output_assembly_id; /* suppress compiler warning */
+  (void) input_assembly_id; /* suppress compiler warning */
+  (void) io_connection_event; /* suppress compiler warning */
 }
 }
 
 
-EIP_STATUS
-IApp_AfterAssemblyDataReceived(S_CIP_Instance *pa_pstInstance)
-{
-  EIP_STATUS nRetVal = EIP_OK;
+EipStatus AfterAssemblyDataReceived(CipInstance *pa_pstInstance) {
+  EipStatus nRetVal = kEipStatusOk;
 
 
   /*handle the data received e.g., update outputs of the device */
   /*handle the data received e.g., update outputs of the device */
-  switch (pa_pstInstance->nInstanceNr)
-    {
-  case DEMO_APP_OUTPUT_ASSEMBLY_NUM:
-    /* Data for the output assembly has been received.
-     * Mirror it to the inputs */
-    memcpy(&g_assemblydata064[0], &g_assemblydata096[0],
-        sizeof(g_assemblydata064));
-    break;
-  case DEMO_APP_EXPLICT_ASSEMBLY_NUM:
-    /* do something interesting with the new data from
-     * the explicit set-data-attribute message */
-    break;
-  case DEMO_APP_CONFIG_ASSEMBLY_NUM:
-    /* Add here code to handle configuration data and check if it is ok
-     * The demo application does not handle config data.
-     * However in order to pass the test we accept any data given.
-     * EIP_ERROR
-     */
-    nRetVal = EIP_OK;
-    break;
-    }
+  switch (pa_pstInstance->instance_number) {
+    case DEMO_APP_OUTPUT_ASSEMBLY_NUM:
+      /* Data for the output assembly has been received.
+       * Mirror it to the inputs */
+      memcpy(&g_assemblydata064[0], &g_assemblydata096[0],
+             sizeof(g_assemblydata064));
+      break;
+    case DEMO_APP_EXPLICT_ASSEMBLY_NUM:
+      /* do something interesting with the new data from
+       * the explicit set-data-attribute message */
+      break;
+    case DEMO_APP_CONFIG_ASSEMBLY_NUM:
+      /* Add here code to handle configuration data and check if it is ok
+       * The demo application does not handle config data.
+       * However in order to pass the test we accept any data given.
+       * EIP_ERROR
+       */
+      nRetVal = kEipStatusOk;
+      break;
+  }
   return nRetVal;
   return nRetVal;
 }
 }
 
 
-EIP_BOOL8
-IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance)
-{
+EipBool8 BeforeAssemblyDataSend(CipInstance *pa_pstInstance) {
   /*update data to be sent e.g., read inputs of the device */
   /*update data to be sent e.g., read inputs of the device */
   /*In this sample app we mirror the data from out to inputs on data receive
   /*In this sample app we mirror the data from out to inputs on data receive
    * therefore we need nothing to do here. Just return true to inform that
    * therefore we need nothing to do here. Just return true to inform that
    * the data is new.
    * the data is new.
    */
    */
 
 
-  if (pa_pstInstance->nInstanceNr == DEMO_APP_EXPLICT_ASSEMBLY_NUM)
-    {
-      /* do something interesting with the existing data
-       * for the explicit get-data-attribute message */
-    }
+  if (pa_pstInstance->instance_number == DEMO_APP_EXPLICT_ASSEMBLY_NUM) {
+    /* do something interesting with the existing data
+     * for the explicit get-data-attribute message */
+  }
   return true;
   return true;
 }
 }
 
 
-EIP_STATUS
-IApp_ResetDevice(void)
-{
+EipStatus ResetDevice(void) {
   /* add reset code here*/
   /* add reset code here*/
-  return EIP_OK;
+  return kEipStatusOk;
 }
 }
 
 
-EIP_STATUS
-IApp_ResetDeviceToInitialConfiguration(void)
-{
+EipStatus ResetDeviceToInitialConfiguration(void) {
   /*rest the parameters */
   /*rest the parameters */
 
 
   /*than perform device reset*/
   /*than perform device reset*/
-  IApp_ResetDevice();
-  return EIP_OK;
+  ResetDevice();
+  return kEipStatusOk;
 }
 }
 
 
 void *
 void *
-IApp_CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement)
-{
+CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement) {
   return calloc(pa_nNumberOfElements, pa_nSizeOfElement);
   return calloc(pa_nNumberOfElements, pa_nSizeOfElement);
 }
 }
 
 
-void
-IApp_CipFree(void *pa_poData)
-{
+void CipFree(void *pa_poData) {
   free(pa_poData);
   free(pa_poData);
 }
 }
 
 
-void
-IApp_RunIdleChanged(EIP_UINT32 pa_nRunIdleValue)
-{
+void RunIdleChanged(EipUint32 pa_nRunIdleValue) {
   (void) pa_nRunIdleValue;
   (void) pa_nRunIdleValue;
 }
 }
 
 

+ 43 - 55
source/src/ports/WIN32/main.c

@@ -12,8 +12,6 @@
 #include "cipcommon.h"
 #include "cipcommon.h"
 #include "trace.h"
 #include "trace.h"
 
 
-
-
 extern int newfd;
 extern int newfd;
 
 
 /******************************************************************************/
 /******************************************************************************/
@@ -30,40 +28,35 @@ leaveStack(int pa_nSig);
 int g_nEndStack = 0;
 int g_nEndStack = 0;
 
 
 /******************************************************************************/
 /******************************************************************************/
-int
-main(int argc, char *arg[])
-{
-  EIP_UINT8 acMyMACAddress[6];
-  EIP_UINT16 nUniqueConnectionID;
-
-  if (argc != 12)
-    {
-      printf("Wrong number of command line parameters!\n");
-      printf("The correct command line parameters are:\n");
-      printf(
-          "./OpENer ipaddress subnetmask gateway domainname hostaddress macaddress\n");
-      printf(
-          "    e.g. ./OpENer 192.168.0.2 255.255.255.0 192.168.0.1 test.com testdevice 00 15 C5 BF D0 87\n");
-      exit(0);
-    }
-  else
-    {
-      /* fetch Internet address info from the platform */
-      configureNetworkInterface(arg[1], arg[2], arg[3]);
-      configureDomainName(arg[4]);
-      configureHostName(arg[5]);
-
-      acMyMACAddress[0] = (EIP_UINT8) strtoul(arg[6], NULL, 16);
-      acMyMACAddress[1] = (EIP_UINT8) strtoul(arg[7], NULL, 16);
-      acMyMACAddress[2] = (EIP_UINT8) strtoul(arg[8], NULL, 16);
-      acMyMACAddress[3] = (EIP_UINT8) strtoul(arg[9], NULL, 16);
-      acMyMACAddress[4] = (EIP_UINT8) strtoul(arg[10], NULL, 16);
-      acMyMACAddress[5] = (EIP_UINT8) strtoul(arg[11], NULL, 16);
-      configureMACAddress(acMyMACAddress);
-    }
+int main(int argc, char *arg[]) {
+  EipUint8 acMyMACAddress[6];
+  EipUint16 nUniqueConnectionID;
+
+  if (argc != 12) {
+    printf("Wrong number of command line parameters!\n");
+    printf("The correct command line parameters are:\n");
+    printf(
+        "./OpENer ipaddress subnetmask gateway domainname hostaddress macaddress\n");
+    printf(
+        "    e.g. ./OpENer 192.168.0.2 255.255.255.0 192.168.0.1 test.com testdevice 00 15 C5 BF D0 87\n");
+    exit(0);
+  } else {
+    /* fetch Internet address info from the platform */
+    ConfigureNetworkInterface(arg[1], arg[2], arg[3]);
+    ConfigureDomainName(arg[4]);
+    ConfigureHostName(arg[5]);
+
+    acMyMACAddress[0] = (EipUint8) strtoul(arg[6], NULL, 16);
+    acMyMACAddress[1] = (EipUint8) strtoul(arg[7], NULL, 16);
+    acMyMACAddress[2] = (EipUint8) strtoul(arg[8], NULL, 16);
+    acMyMACAddress[3] = (EipUint8) strtoul(arg[9], NULL, 16);
+    acMyMACAddress[4] = (EipUint8) strtoul(arg[10], NULL, 16);
+    acMyMACAddress[5] = (EipUint8) strtoul(arg[11], NULL, 16);
+    ConfigureMacAddress(acMyMACAddress);
+  }
 
 
   /*for a real device the serial number should be unique per device */
   /*for a real device the serial number should be unique per device */
-  setDeviceSerialNumber(123456789);
+  SetDeviceSerialNumber(123456789);
 
 
   /* nUniqueConnectionID should be sufficiently random or incremented and stored
   /* nUniqueConnectionID should be sufficiently random or incremented and stored
    *  in non-volatile memory each time the device boots.
    *  in non-volatile memory each time the device boots.
@@ -71,38 +64,33 @@ main(int argc, char *arg[])
   nUniqueConnectionID = rand();
   nUniqueConnectionID = rand();
 
 
   /* Setup the CIP Layer */
   /* Setup the CIP Layer */
-  CIP_Init(nUniqueConnectionID);
+  CipStackInit(nUniqueConnectionID);
 
 
   /* Setup Network Handles */
   /* Setup Network Handles */
-  if (EIP_OK == NetworkHandler_Init())
-    {
-      g_nEndStack = 0;
+  if (EIP_OK == NetworkHandler_Init()) {
+    g_nEndStack = 0;
 #ifndef WIN32
 #ifndef WIN32
-      /* register for closing signals so that we can trigger the stack to end */
-      signal(SIGHUP, leaveStack);
+    /* register for closing signals so that we can trigger the stack to end */
+    signal(SIGHUP, leaveStack);
 #endif
 #endif
 
 
-      /* The event loop. Put other processing you need done continually in here */
-      while (1 != g_nEndStack)
-        {
-          if( EIP_OK != NetworkHandler_ProcessOnce())
-            {
-              break;
-            }
-        }
-
-      /* clean up network state */
-      NetworkHandler_Finish();
+    /* The event loop. Put other processing you need done continually in here */
+    while (1 != g_nEndStack) {
+      if (EIP_OK != NetworkHandler_ProcessOnce()) {
+        break;
+      }
     }
     }
+
+    /* clean up network state */
+    NetworkHandler_Finish();
+  }
   /* close remaining sessions and connections, cleanup used data */
   /* close remaining sessions and connections, cleanup used data */
-  shutdownCIP();
+  ShutdownCipStack();
 
 
   return -1;
   return -1;
 }
 }
 
 
-void
-leaveStack(int pa_nSig)
-{
+void leaveStack(int pa_nSig) {
   (void) pa_nSig; /* kill unused parameter warning */
   (void) pa_nSig; /* kill unused parameter warning */
   OPENER_TRACE_STATE("got signal HUP\n");
   OPENER_TRACE_STATE("got signal HUP\n");
   g_nEndStack = 1;
   g_nEndStack = 1;

+ 347 - 419
source/src/ports/WIN32/networkhandler.c

@@ -26,8 +26,8 @@
 #include <ciptcpipinterface.h>
 #include <ciptcpipinterface.h>
 
 
 /* values needed from the connection manager */
 /* values needed from the connection manager */
-extern S_CIP_ConnectionObject *g_pstActiveConnectionList;
-/* communication buffer */EIP_UINT8 g_acPCEthernetCommBuffer[PC_OPENER_ETHERNET_BUFFER_SIZE];
+extern ConnectionObject *g_active_connection_list;
+/* communication buffer */EipUint8 g_acPCEthernetCommBuffer[PC_OPENER_ETHERNET_BUFFER_SIZE];
 
 
 #define MAX_NO_OF_TCP_SOCKETS 10
 #define MAX_NO_OF_TCP_SOCKETS 10
 
 
@@ -67,26 +67,24 @@ void
 checkAndHandleConsumingUDPSockets();
 checkAndHandleConsumingUDPSockets();
 /*! \brief check if the given socket is set in the read set
 /*! \brief check if the given socket is set in the read set
  *
  *
- */EIP_BOOL8
+ */EipBool8
 checkSocketSet(int pa_nSocket);
 checkSocketSet(int pa_nSocket);
 
 
 /*!
 /*!
  *
  *
  */
  */
-EIP_STATUS
+EipStatus
 handleDataOnTCPSocket(int pa_nSocket);
 handleDataOnTCPSocket(int pa_nSocket);
 
 
-static MICROSECONDS
-getMicroseconds()
-{
+static MICROSECONDS getMicroseconds() {
 #ifdef WIN32
 #ifdef WIN32
-    LARGE_INTEGER lPerformanceCouner;
-    LARGE_INTEGER lPerformanceFrequency;
+  LARGE_INTEGER lPerformanceCouner;
+  LARGE_INTEGER lPerformanceFrequency;
 
 
-    QueryPerformanceCounter(&lPerformanceCouner);
-    QueryPerformanceFrequency(&lPerformanceFrequency);
+  QueryPerformanceCounter(&lPerformanceCouner);
+  QueryPerformanceFrequency(&lPerformanceFrequency);
 
 
-    return (MICROSECONDS) (lPerformanceCouner.QuadPart * 1000000LL / lPerformanceFrequency.QuadPart);
+  return (MICROSECONDS) (lPerformanceCouner.QuadPart * 1000000LL / lPerformanceFrequency.QuadPart);
 #else
 #else
   struct timeval tv;
   struct timeval tv;
   gettimeofday(&tv, 0);
   gettimeofday(&tv, 0);
@@ -94,10 +92,8 @@ getMicroseconds()
 #endif
 #endif
 }
 }
 
 
-static MILLISECONDS
-getmilliseconds(void)
-{
-    return (MILLISECONDS) ( getMicroseconds() / 1000ULL );
+static MILLISECONDS getmilliseconds(void) {
+  return (MILLISECONDS) (getMicroseconds() / 1000ULL);
 }
 }
 
 
 /* INT8 Start_NetworkHandler()
 /* INT8 Start_NetworkHandler()
@@ -106,18 +102,15 @@ getmilliseconds(void)
  * 			-1 .. error
  * 			-1 .. error
  */
  */
 
 
-struct NetworkStatus
-{
+struct NetworkStatus {
   int nTCPListener;
   int nTCPListener;
   int nUDPListener;
   int nUDPListener;
   MILLISECONDS elapsedtime;
   MILLISECONDS elapsedtime;
 } PACKED;
 } PACKED;
 
 
-struct NetworkStatus TheNetworkStatus;
+struct NetworkStatus g_network_status;
 
 
-EIP_STATUS
-NetworkHandler_Init(void)
-{
+EipStatus NetworkHandler_Init(void) {
   struct sockaddr_in my_addr;
   struct sockaddr_in my_addr;
   int y;
   int y;
   int nOptVal;
   int nOptVal;
@@ -134,33 +127,31 @@ NetworkHandler_Init(void)
   FD_ZERO(&read_fds);
   FD_ZERO(&read_fds);
 
 
   /* create a new TCP socket */
   /* create a new TCP socket */
-  if ((TheNetworkStatus.nTCPListener = socket(PF_INET, SOCK_STREAM, 0)) == -1)
-    {
-      OPENER_TRACE_ERR("error allocating socket stream listener, %d\n", errno);
-      return EIP_ERROR;
-    }
+  if ((g_network_status.nTCPListener = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
+    OPENER_TRACE_ERR("error allocating socket stream listener, %d\n", errno);
+    return EIP_ERROR;
+  }
 
 
   nOptVal = 1;
   nOptVal = 1;
-  if (setsockopt(TheNetworkStatus.nTCPListener, SOL_SOCKET, SO_REUSEADDR,
-      (char *)&nOptVal, sizeof(nOptVal)) == -1)
-    {
-      OPENER_TRACE_ERR("error setting socket option SO_REUSEADDR on nTCPListener\n");
-      return EIP_ERROR;
-    }
+  if (setsockopt(g_network_status.nTCPListener, SOL_SOCKET, SO_REUSEADDR,
+                 (char *) &nOptVal, sizeof(nOptVal)) == -1) {
+    OPENER_TRACE_ERR(
+        "error setting socket option SO_REUSEADDR on nTCPListener\n");
+    return EIP_ERROR;
+  }
 
 
   /* create a new UDP socket */
   /* create a new UDP socket */
-  if ((TheNetworkStatus.nUDPListener = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
-    {
-      OPENER_TRACE_ERR("error allocating udp listener socket, %d\n", errno);
-      return EIP_ERROR;
-    }
-
-  if (setsockopt(TheNetworkStatus.nUDPListener, SOL_SOCKET, SO_REUSEADDR,
-      (char *)&nOptVal, sizeof(nOptVal)) == -1)
-    {
-      OPENER_TRACE_ERR("error setting socket option SO_REUSEADDR on nUDPListener\n");
-      return EIP_ERROR;
-    }
+  if ((g_network_status.nUDPListener = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
+    OPENER_TRACE_ERR("error allocating udp listener socket, %d\n", errno);
+    return EIP_ERROR;
+  }
+
+  if (setsockopt(g_network_status.nUDPListener, SOL_SOCKET, SO_REUSEADDR,
+                 (char *) &nOptVal, sizeof(nOptVal)) == -1) {
+    OPENER_TRACE_ERR(
+        "error setting socket option SO_REUSEADDR on nUDPListener\n");
+    return EIP_ERROR;
+  }
 
 
   my_addr.sin_family = AF_INET;
   my_addr.sin_family = AF_INET;
   my_addr.sin_port = htons(OPENER_ETHERNET_PORT);
   my_addr.sin_port = htons(OPENER_ETHERNET_PORT);
@@ -168,55 +159,52 @@ NetworkHandler_Init(void)
   memset(&my_addr.sin_zero, 0, sizeof(my_addr.sin_zero));
   memset(&my_addr.sin_zero, 0, sizeof(my_addr.sin_zero));
 
 
   /* bind the new socket to port 0xAF12 (CIP) */
   /* bind the new socket to port 0xAF12 (CIP) */
-  if ((bind(TheNetworkStatus.nTCPListener, (struct sockaddr *) &my_addr,
-      sizeof(struct sockaddr))) == -1)
-    {
-      OPENER_TRACE_ERR("error with bind: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+  if ((bind(g_network_status.nTCPListener, (struct sockaddr *) &my_addr,
+            sizeof(struct sockaddr))) == -1) {
+    OPENER_TRACE_ERR("error with bind: %s\n", strerror(errno));
+    return EIP_ERROR;
+  }
 
 
   /* enable the udp socket to receive broadcast messages*/
   /* enable the udp socket to receive broadcast messages*/
   y = 1;
   y = 1;
   if (0
   if (0
-      > setsockopt(TheNetworkStatus.nUDPListener, SOL_SOCKET, SO_BROADCAST, (char *)&y,
-          sizeof(int)))
-    {
-      OPENER_TRACE_ERR("error with setting broadcast receive for udp socket: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-
-  if ((bind(TheNetworkStatus.nUDPListener, (struct sockaddr *) &my_addr,
-      sizeof(struct sockaddr))) == -1)
-    {
-      OPENER_TRACE_ERR("error with udp bind: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+      > setsockopt(g_network_status.nUDPListener, SOL_SOCKET, SO_BROADCAST,
+                   (char *) &y, sizeof(int))) {
+    OPENER_TRACE_ERR(
+        "error with setting broadcast receive for udp socket: %s\n",
+        strerror(errno));
+    return EIP_ERROR;
+  }
+
+  if ((bind(g_network_status.nUDPListener, (struct sockaddr *) &my_addr,
+            sizeof(struct sockaddr))) == -1) {
+    OPENER_TRACE_ERR("error with udp bind: %s\n", strerror(errno));
+    return EIP_ERROR;
+  }
 
 
   /* switch socket in listen mode */
   /* switch socket in listen mode */
-  if ((listen(TheNetworkStatus.nTCPListener, MAX_NO_OF_TCP_SOCKETS)) == -1)
-    {
-      OPENER_TRACE_ERR("networkhandler: error with listen: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+  if ((listen(g_network_status.nTCPListener, MAX_NO_OF_TCP_SOCKETS)) == -1) {
+    OPENER_TRACE_ERR("networkhandler: error with listen: %s\n",
+                     strerror(errno));
+    return EIP_ERROR;
+  }
 
 
   /* add the listener socket to the master set */FD_SET(
   /* add the listener socket to the master set */FD_SET(
-      TheNetworkStatus.nTCPListener, &master);
-  FD_SET(TheNetworkStatus.nUDPListener, &master);
+      g_network_status.nTCPListener, &master);
+  FD_SET(g_network_status.nUDPListener, &master);
 
 
   /* keep track of the biggest file descriptor */
   /* keep track of the biggest file descriptor */
   fdmax =
   fdmax =
-      (TheNetworkStatus.nTCPListener > TheNetworkStatus.nUDPListener) ? TheNetworkStatus.nTCPListener :
-          TheNetworkStatus.nUDPListener;
+      (g_network_status.nTCPListener > g_network_status.nUDPListener) ?
+          g_network_status.nTCPListener : g_network_status.nUDPListener;
 
 
   lasttime = getmilliseconds(); /* initialize time keeping */
   lasttime = getmilliseconds(); /* initialize time keeping */
-  TheNetworkStatus.elapsedtime = 0;
+  g_network_status.elapsedtime = 0;
 
 
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-EIP_STATUS
-NetworkHandler_ProcessOnce(void)
-{
+EipStatus NetworkHandler_ProcessOnce(void) {
   int fd;
   int fd;
   int res;
   int res;
 
 
@@ -224,118 +212,96 @@ NetworkHandler_ProcessOnce(void)
 
 
   tv.tv_sec = 0;
   tv.tv_sec = 0;
   tv.tv_usec = (
   tv.tv_usec = (
-      TheNetworkStatus.elapsedtime < OPENER_TIMER_TICK ? OPENER_TIMER_TICK
-          - TheNetworkStatus.elapsedtime :
-          0) * 1000; /* 10 ms */
+      g_network_status.elapsedtime < OPENER_TIMER_TICK ?
+          OPENER_TIMER_TICK - g_network_status.elapsedtime : 0) * 1000; /* 10 ms */
 
 
   res = select(fdmax + 1, &read_fds, 0, 0, &tv);
   res = select(fdmax + 1, &read_fds, 0, 0, &tv);
 
 
-  if (res == -1)
+  if (res == -1) {
+    if (EINTR == errno) /* we have somehow been interrupted. The default behavior is to go back into the select loop. */
     {
     {
-      if (EINTR == errno) /* we have somehow been interrupted. The default behavior is to go back into the select loop. */
-        {
-          return EIP_OK;
-        }
-      else
-        {
-          OPENER_TRACE_ERR("networkhandler: error with select: %s\n", strerror(errno));
-          return EIP_ERROR;
-        }
+      return EIP_OK;
+    } else {
+      OPENER_TRACE_ERR("networkhandler: error with select: %s\n",
+                       strerror(errno));
+      return EIP_ERROR;
     }
     }
+  }
 
 
-  if (res > 0)
-    {
+  if (res > 0) {
 
 
-      checkAndHandleTCPListenerSocket();
-      checkAndHandleUDPBroadCastSocket();
-      checkAndHandleConsumingUDPSockets();
+    checkAndHandleTCPListenerSocket();
+    checkAndHandleUDPBroadCastSocket();
+    checkAndHandleConsumingUDPSockets();
 
 
-      for (fd = 0; fd <= fdmax; fd++)
+    for (fd = 0; fd <= fdmax; fd++) {
+      if (true == checkSocketSet(fd)) {
+        /* if it is still checked it is a TCP receive */
+        if (EIP_ERROR == handleDataOnTCPSocket(fd)) /* if error */
         {
         {
-          if (true == checkSocketSet(fd))
-            {
-              /* if it is still checked it is a TCP receive */
-              if (EIP_ERROR == handleDataOnTCPSocket(fd)) /* if error */
-                {
-                  IApp_CloseSocket(fd);
-                  closeSession(fd); /* clean up session and close the socket */
-                }
-            }
+          CloseSocket(fd);
+          CloseSession(fd); /* clean up session and close the socket */
         }
         }
+      }
     }
     }
+  }
 
 
   actualtime = getmilliseconds();
   actualtime = getmilliseconds();
-  TheNetworkStatus.elapsedtime += actualtime - lasttime;
+  g_network_status.elapsedtime += actualtime - lasttime;
   lasttime = actualtime;
   lasttime = actualtime;
 
 
   /* check if we had been not able to update the connection manager for several OPENER_TIMER_TICK.
   /* check if we had been not able to update the connection manager for several OPENER_TIMER_TICK.
    * This should compensate the jitter of the windows timer
    * This should compensate the jitter of the windows timer
    */
    */
-  while (TheNetworkStatus.elapsedtime >= OPENER_TIMER_TICK)
-    {
-      /* call manage_connections() in connection manager every OPENER_TIMER_TICK ms */
-      manageConnections();
-      TheNetworkStatus.elapsedtime -= OPENER_TIMER_TICK;
-    }
+  while (g_network_status.elapsedtime >= OPENER_TIMER_TICK) {
+    /* call manage_connections() in connection manager every OPENER_TIMER_TICK ms */
+    ManageConnections();
+    g_network_status.elapsedtime -= OPENER_TIMER_TICK;
+  }
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-EIP_STATUS
-NetworkHandler_Finish(void)
-{
-  IApp_CloseSocket(TheNetworkStatus.nTCPListener);
-  IApp_CloseSocket(TheNetworkStatus.nUDPListener);
+EipStatus NetworkHandler_Finish(void) {
+  CloseSocket(g_network_status.nTCPListener);
+  CloseSocket(g_network_status.nUDPListener);
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-EIP_BOOL8
-checkSocketSet(int pa_nSocket)
-{
-  EIP_BOOL8 nRetVal = false;
-  if (FD_ISSET(pa_nSocket, &read_fds))
-    {
-      if (FD_ISSET(pa_nSocket, &master))
-        {
-          nRetVal = true;
-        }
-      else
-        {
-          OPENER_TRACE_INFO("socket: %d closed with pending message\n", pa_nSocket);
-        }
-      FD_CLR(pa_nSocket, &read_fds);
-      /* remove it from the read set so that later checks will not find it */
+EipBool8 checkSocketSet(int pa_nSocket) {
+  EipBool8 nRetVal = false;
+  if (FD_ISSET(pa_nSocket, &read_fds)) {
+    if (FD_ISSET(pa_nSocket, &master)) {
+      nRetVal = true;
+    } else {
+      OPENER_TRACE_INFO("socket: %d closed with pending message\n", pa_nSocket);
     }
     }
+    FD_CLR(pa_nSocket, &read_fds);
+    /* remove it from the read set so that later checks will not find it */
+  }
 
 
   return nRetVal;
   return nRetVal;
 }
 }
-EIP_STATUS
-IApp_SendUDPData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
-    EIP_UINT8 *pa_acData, EIP_UINT16 pa_nDataLength)
-{
+EipStatus SendUdpData(struct sockaddr_in *pa_pstAddr, int pa_nSockFd,
+                      EipUint8 *pa_acData, EipUint16 pa_nDataLength) {
   int sentlength;
   int sentlength;
 
 
   sentlength = sendto(pa_nSockFd, (char *) pa_acData, pa_nDataLength, 0,
   sentlength = sendto(pa_nSockFd, (char *) pa_acData, pa_nDataLength, 0,
-      (struct sockaddr *) pa_pstAddr, sizeof(*pa_pstAddr));
-
-  if (sentlength < 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: error with sendto in sendUDPData: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-  else if (sentlength != pa_nDataLength)
-    {
-      OPENER_TRACE_WARN("not all data was sent in sendUDPData, sent %d of %d\n",
-          sentlength, pa_nDataLength);
-      return EIP_ERROR;
-    }
-  else
+                      (struct sockaddr *) pa_pstAddr, sizeof(*pa_pstAddr));
+
+  if (sentlength < 0) {
+    OPENER_TRACE_ERR("networkhandler: error with sendto in sendUDPData: %s\n",
+                     strerror(errno));
+    return EIP_ERROR;
+  } else if (sentlength != pa_nDataLength) {
+    OPENER_TRACE_WARN("not all data was sent in sendUDPData, sent %d of %d\n",
+                      sentlength, pa_nDataLength);
+    return EIP_ERROR;
+  } else
     return EIP_OK;
     return EIP_OK;
 }
 }
 
 
-EIP_STATUS
-handleDataOnTCPSocket(int pa_nSocket)
-{
-  EIP_UINT8 *rxp;
+EipStatus handleDataOnTCPSocket(int pa_nSocket) {
+  EipUint8 *rxp;
   long nCheckVal;
   long nCheckVal;
   size_t unDataSize;
   size_t unDataSize;
   long nDataSent;
   long nDataSent;
@@ -350,115 +316,105 @@ handleDataOnTCPSocket(int pa_nSocket)
   /*Check how many data is here -- read the first four bytes from the connection */
   /*Check how many data is here -- read the first four bytes from the connection */
   nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, 4, 0); /*TODO we may have to set the socket to a non blocking socket */
   nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, 4, 0); /*TODO we may have to set the socket to a non blocking socket */
 
 
-  if (nCheckVal == 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-  if (nCheckVal < 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
+  if (nCheckVal == 0) {
+    OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
+                     strerror(errno));
+    return EIP_ERROR;
+  }
+  if (nCheckVal < 0) {
+    OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
+    return EIP_ERROR;
+  }
 
 
   rxp = &g_acPCEthernetCommBuffer[2]; /* at this place EIP stores the data length */
   rxp = &g_acPCEthernetCommBuffer[2]; /* at this place EIP stores the data length */
-  unDataSize = ltohs(&rxp) + ENCAPSULATION_HEADER_LENGTH - 4; /* -4 is for the 4 bytes we have already read*/
+  unDataSize = GetIntFromMessage(&rxp) + ENCAPSULATION_HEADER_LENGTH - 4; /* -4 is for the 4 bytes we have already read*/
   /* (NOTE this advances the buffer pointer) */
   /* (NOTE this advances the buffer pointer) */
-  if (PC_OPENER_ETHERNET_BUFFER_SIZE - 4 < unDataSize)
-    { /*TODO can this be handled in a better way?*/
-      OPENER_TRACE_ERR("too large packet received will be ignored, will drop the data\n");
-      /* Currently we will drop the whole packet */
-      nDataSent = PC_OPENER_ETHERNET_BUFFER_SIZE;
-
-      do
-        {
-          nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, nDataSent, 0);
-
-          if (nCheckVal == 0) /* got error or connection closed by client */
-            {
-              OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n", strerror(errno));
-              return EIP_ERROR;
-            }
-          if (nCheckVal < 0)
-            {
-              OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-              return EIP_ERROR;
-            }
-          unDataSize -= nCheckVal;
-          if ((unDataSize < PC_OPENER_ETHERNET_BUFFER_SIZE)
-              && (unDataSize != 0))
-            {
-              nDataSent = unDataSize;
-            }
-        }
-      while (0 != unDataSize); /*TODO fragile end statement */
-      return EIP_OK;
-    }
+  if (PC_OPENER_ETHERNET_BUFFER_SIZE - 4 < unDataSize) { /*TODO can this be handled in a better way?*/
+    OPENER_TRACE_ERR(
+        "too large packet received will be ignored, will drop the data\n");
+    /* Currently we will drop the whole packet */
+    nDataSent = PC_OPENER_ETHERNET_BUFFER_SIZE;
+
+    do {
+      nCheckVal = recv(pa_nSocket, g_acPCEthernetCommBuffer, nDataSent, 0);
+
+      if (nCheckVal == 0) /* got error or connection closed by client */
+      {
+        OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
+                         strerror(errno));
+        return EIP_ERROR;
+      }
+      if (nCheckVal < 0) {
+        OPENER_TRACE_ERR("networkhandler: error on recv: %s\n",
+                         strerror(errno));
+        return EIP_ERROR;
+      }
+      unDataSize -= nCheckVal;
+      if ((unDataSize < PC_OPENER_ETHERNET_BUFFER_SIZE) && (unDataSize != 0)) {
+        nDataSent = unDataSize;
+      }
+    } while (0 != unDataSize); /*TODO fragile end statement */
+    return EIP_OK;
+  }
 
 
   nCheckVal = recv(pa_nSocket, &g_acPCEthernetCommBuffer[4], unDataSize, 0);
   nCheckVal = recv(pa_nSocket, &g_acPCEthernetCommBuffer[4], unDataSize, 0);
 
 
   if (nCheckVal == 0) /* got error or connection closed by client */
   if (nCheckVal == 0) /* got error or connection closed by client */
-    {
-      OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n", strerror(errno));
-      return EIP_ERROR;
-    }
-  if (nCheckVal < 0)
-    {
-      OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-      return EIP_ERROR;
+  {
+    OPENER_TRACE_ERR("networkhandler: connection closed by client: %s\n",
+                     strerror(errno));
+    return EIP_ERROR;
+  }
+  if (nCheckVal < 0) {
+    OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
+    return EIP_ERROR;
+  }
+
+  if ((unsigned) nCheckVal == unDataSize) {
+    /*we got the right amount of data */
+    unDataSize += 4;
+    /*TODO handle partial packets*/
+    OPENER_TRACE_INFO("Data received on tcp:\n");
+
+    g_nCurrentActiveTCPSocket = pa_nSocket;
+
+    nCheckVal = HandleReceivedExplictTcpData(pa_nSocket,
+                                             g_acPCEthernetCommBuffer,
+                                             unDataSize, &nRemainingBytes);
+
+    g_nCurrentActiveTCPSocket = -1;
+
+    if (nRemainingBytes != 0) {
+      OPENER_TRACE_WARN(
+          "Warning: received packet was to long: %d Bytes left!\n",
+          nRemainingBytes);
     }
     }
 
 
-  if ((unsigned) nCheckVal == unDataSize)
-    {
-      /*we got the right amount of data */
-      unDataSize += 4;
-      /*TODO handle partial packets*/
-      OPENER_TRACE_INFO("Data received on tcp:\n");
-
-      g_nCurrentActiveTCPSocket = pa_nSocket;
-
-      nCheckVal = handleReceivedExplictTCPData(pa_nSocket,
-          g_acPCEthernetCommBuffer, unDataSize, &nRemainingBytes);
-
-      g_nCurrentActiveTCPSocket = -1;
+    if (nCheckVal > 0) {
+      OPENER_TRACE_INFO("reply sent:\n");
 
 
-      if (nRemainingBytes != 0)
-        {
-          OPENER_TRACE_WARN("Warning: received packet was to long: %d Bytes left!\n",
-              nRemainingBytes);
-        }
-
-      if (nCheckVal > 0)
-        {
-          OPENER_TRACE_INFO("reply sent:\n");
-
-          nDataSent = send(pa_nSocket, (char *) g_acPCEthernetCommBuffer,
-              nCheckVal, 0);
-          if (nDataSent != nCheckVal)
-            {
-              OPENER_TRACE_WARN("TCP response was not fully sent\n");
-            }
-        }
-
-      return EIP_OK;
-    }
-  else
-    {
-      /* we got a fragmented packet currently we cannot handle this will
-       * for this we would need a network buffer per TCP socket
-       *
-       * However with typical packet sizes of EIP this should't be a big issue.
-       */
-      /*TODO handle fragmented packets */
+      nDataSent = send(pa_nSocket, (char *) g_acPCEthernetCommBuffer, nCheckVal,
+                       0);
+      if (nDataSent != nCheckVal) {
+        OPENER_TRACE_WARN("TCP response was not fully sent\n");
+      }
     }
     }
+
+    return EIP_OK;
+  } else {
+    /* we got a fragmented packet currently we cannot handle this will
+     * for this we would need a network buffer per TCP socket
+     *
+     * However with typical packet sizes of EIP this should't be a big issue.
+     */
+    /*TODO handle fragmented packets */
+  }
   return EIP_ERROR;
   return EIP_ERROR;
 }
 }
 
 
 /* create a new UDP socket for the connection manager
 /* create a new UDP socket for the connection manager
  returns the fd if successful, else -1 */
  returns the fd if successful, else -1 */
-int
-IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr)
-{
+int CreateUdpSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr) {
   struct sockaddr_in stPeerAdr;
   struct sockaddr_in stPeerAdr;
   int newfd;
   int newfd;
 #ifdef WIN32
 #ifdef WIN32
@@ -469,139 +425,120 @@ IApp_CreateUDPSocket(int pa_nDirection, struct sockaddr_in *pa_pstAddr)
 
 
   nPeerAddrLen = sizeof(struct sockaddr_in);
   nPeerAddrLen = sizeof(struct sockaddr_in);
   /* create a new UDP socket */
   /* create a new UDP socket */
-  if ((newfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
-    {
-      OPENER_TRACE_ERR("networkhandler: cannot create UDP socket: %s\n", strerror(errno));
-      return EIP_INVALID_SOCKET;
-    }
+  if ((newfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
+    OPENER_TRACE_ERR("networkhandler: cannot create UDP socket: %s\n",
+                     strerror(errno));
+    return EIP_INVALID_SOCKET;
+  }
 
 
   OPENER_TRACE_INFO("networkhandler: UDP socket %d\n", newfd);
   OPENER_TRACE_INFO("networkhandler: UDP socket %d\n", newfd);
 
 
   /* check if it is sending or receiving */
   /* check if it is sending or receiving */
-  if (pa_nDirection == CONSUMING)
-    {
-      int nOptVal = 1;
-      if (setsockopt(newfd, SOL_SOCKET, SO_REUSEADDR, (char *)&nOptVal, sizeof(nOptVal))
-          == -1)
-        {
-          OPENER_TRACE_ERR("error setting socket option SO_REUSEADDR on consuming udp socket\n");
-          return EIP_ERROR;
-        }
-
-      /* bind is only for consuming necessary */
-      if ((bind(newfd, (struct sockaddr *) pa_pstAddr, sizeof(struct sockaddr)))
-          == -1)
-        {
-          OPENER_TRACE_ERR("error on bind udp: %s\n", strerror(errno));
-          return EIP_INVALID_SOCKET;
-        }
-
-      OPENER_TRACE_INFO("networkhandler: bind UDP socket %d\n", newfd);
+  if (pa_nDirection == CONSUMING) {
+    int nOptVal = 1;
+    if (setsockopt(newfd, SOL_SOCKET, SO_REUSEADDR, (char *) &nOptVal,
+                   sizeof(nOptVal)) == -1) {
+      OPENER_TRACE_ERR(
+          "error setting socket option SO_REUSEADDR on consuming udp socket\n");
+      return EIP_ERROR;
     }
     }
-  else
-    { /* we have a producing udp socket */
 
 
-      if (pa_pstAddr->sin_addr.s_addr == g_stMultiCastconfig.m_unMcastStartAddr)
-        {
-          if (1 != g_unTTLValue)
-            { /* we need to set a TTL value for the socket */
-              if (setsockopt(newfd, IPPROTO_IP, IP_MULTICAST_TTL,
-                  &g_unTTLValue, sizeof(g_unTTLValue) < 0))
-                {
-                  OPENER_TRACE_ERR("networkhandler: could not set the TTL to: %d, error: %s\n", g_unTTLValue, strerror(errno));
-                  return EIP_INVALID_SOCKET;
-                }
-            }
-        }
+    /* bind is only for consuming necessary */
+    if ((bind(newfd, (struct sockaddr *) pa_pstAddr, sizeof(struct sockaddr)))
+        == -1) {
+      OPENER_TRACE_ERR("error on bind udp: %s\n", strerror(errno));
+      return EIP_INVALID_SOCKET;
     }
     }
 
 
-  if ((pa_nDirection == CONSUMING) || (0 == pa_pstAddr->sin_addr.s_addr))
-    {
-      /* we have a peer to peer producer or a consuming connection*/
-      if (getpeername(g_nCurrentActiveTCPSocket, (struct sockaddr *) &stPeerAdr,
-          &nPeerAddrLen) < 0)
-        {
-          OPENER_TRACE_ERR("networkhandler: could not get peername: %s\n", strerror(errno));
+    OPENER_TRACE_INFO("networkhandler: bind UDP socket %d\n", newfd);
+  } else { /* we have a producing udp socket */
+
+    if (pa_pstAddr->sin_addr.s_addr
+        == g_multicast_configuration.starting_multicast_address) {
+      if (1 != g_time_to_live_value) { /* we need to set a TTL value for the socket */
+        if (setsockopt(newfd, IPPROTO_IP, IP_MULTICAST_TTL,
+                       &g_time_to_live_value,
+                       sizeof(g_time_to_live_value) < 0)) {
+          OPENER_TRACE_ERR(
+              "networkhandler: could not set the TTL to: %d, error: %s\n",
+              g_time_to_live_value, strerror(errno));
           return EIP_INVALID_SOCKET;
           return EIP_INVALID_SOCKET;
         }
         }
-      /* store the originators address */
-      pa_pstAddr->sin_addr.s_addr = stPeerAdr.sin_addr.s_addr;
+      }
     }
     }
+  }
+
+  if ((pa_nDirection == CONSUMING) || (0 == pa_pstAddr->sin_addr.s_addr)) {
+    /* we have a peer to peer producer or a consuming connection*/
+    if (getpeername(g_nCurrentActiveTCPSocket, (struct sockaddr *) &stPeerAdr,
+                    &nPeerAddrLen) < 0) {
+      OPENER_TRACE_ERR("networkhandler: could not get peername: %s\n",
+                       strerror(errno));
+      return EIP_INVALID_SOCKET;
+    }
+    /* store the originators address */
+    pa_pstAddr->sin_addr.s_addr = stPeerAdr.sin_addr.s_addr;
+  }
 
 
   /* add new fd to the master list                                             */
   /* add new fd to the master list                                             */
   FD_SET(newfd, &master);
   FD_SET(newfd, &master);
-  if (newfd > fdmax)
-    {
-      fdmax = newfd;
-    }
+  if (newfd > fdmax) {
+    fdmax = newfd;
+  }
   return newfd;
   return newfd;
 }
 }
 
 
-void
-IApp_CloseSocket_udp(int pa_nSockFd)
-{
-	IApp_CloseSocket(pa_nSockFd);
+void IApp_CloseSocket_udp(int pa_nSockFd) {
+  CloseSocket(pa_nSockFd);
 }
 }
 
 
-void
-IApp_CloseSocket_tcp(int pa_nSockFd)
-{
-	IApp_CloseSocket(pa_nSockFd);
+void IApp_CloseSocket_tcp(int pa_nSockFd) {
+  CloseSocket(pa_nSockFd);
 }
 }
 
 
-void
-IApp_CloseSocket(int pa_nSockFd)
-{
+void CloseSocket(int pa_nSockFd) {
 
 
   OPENER_TRACE_INFO("networkhandler: closing socket %d\n", pa_nSockFd);
   OPENER_TRACE_INFO("networkhandler: closing socket %d\n", pa_nSockFd);
-  if (EIP_INVALID_SOCKET != pa_nSockFd)
-    {
-      FD_CLR(pa_nSockFd, &master);
+  if (EIP_INVALID_SOCKET != pa_nSockFd) {
+    FD_CLR(pa_nSockFd, &master);
 #ifdef WIN32
 #ifdef WIN32
-      closesocket(pa_nSockFd);
+    closesocket(pa_nSockFd);
 #else
 #else
-      shutdown(pa_nSockFd, SHUT_RDWR);
-      close(pa_nSockFd);
+    shutdown(pa_nSockFd, SHUT_RDWR);
+    close(pa_nSockFd);
 #endif
 #endif
-    }
+  }
 }
 }
 
 
-void
-checkAndHandleTCPListenerSocket()
-{
+void checkAndHandleTCPListenerSocket() {
   int newfd;
   int newfd;
   /* see if this is a connection request to the TCP listener*/
   /* see if this is a connection request to the TCP listener*/
-  if (true == checkSocketSet(TheNetworkStatus.nTCPListener))
-    {
-      OPENER_TRACE_INFO("networkhandler: new TCP connection\n");
-
-      newfd = accept(TheNetworkStatus.nTCPListener, NULL, NULL);
-      if (newfd == -1)
-        {
-          OPENER_TRACE_ERR("networkhandler: error on accept: %s\n", strerror(errno));
-          return;
-        }
-
-      FD_SET(newfd, &master);
-      /* add newfd to master set */
-      if (newfd > fdmax)
-        {
-          fdmax = newfd;
-        }
+  if (true == checkSocketSet(g_network_status.nTCPListener)) {
+    OPENER_TRACE_INFO("networkhandler: new TCP connection\n");
+
+    newfd = accept(g_network_status.nTCPListener, NULL, NULL);
+    if (newfd == -1) {
+      OPENER_TRACE_ERR("networkhandler: error on accept: %s\n",
+                       strerror(errno));
+      return;
+    }
 
 
-      OPENER_TRACE_STATE(
-          "networkhandler: opened new TCP connection on fd %d\n",
-          newfd);
+    FD_SET(newfd, &master);
+    /* add newfd to master set */
+    if (newfd > fdmax) {
+      fdmax = newfd;
     }
     }
+
+    OPENER_TRACE_STATE("networkhandler: opened new TCP connection on fd %d\n",
+                       newfd);
+  }
 }
 }
 
 
-void
-checkAndHandleUDPBroadCastSocket()
-{
+void checkAndHandleUDPBroadCastSocket() {
   int nReceived_size;
   int nReceived_size;
   int nRemainingBytes;
   int nRemainingBytes;
   int nReplyLen;
   int nReplyLen;
-  EIP_UINT8 *rxp;
+  EipUint8 *rxp;
   struct sockaddr_in stFrom;
   struct sockaddr_in stFrom;
 #ifndef WIN32
 #ifndef WIN32
   socklen_t nFromLen;
   socklen_t nFromLen;
@@ -610,60 +547,53 @@ checkAndHandleUDPBroadCastSocket()
 #endif
 #endif
 
 
   /* see if this is an unsolicited inbound UDP message */
   /* see if this is an unsolicited inbound UDP message */
-  if (true == checkSocketSet(TheNetworkStatus.nUDPListener))
-    {
+  if (true == checkSocketSet(g_network_status.nUDPListener)) {
 
 
-      nFromLen = sizeof(stFrom);
+    nFromLen = sizeof(stFrom);
 
 
-      OPENER_TRACE_STATE(
-          "networkhandler: unsolicited UDP message on EIP broadcast socket\n");
+    OPENER_TRACE_STATE(
+        "networkhandler: unsolicited UDP message on EIP broadcast socket\n");
 
 
-      /*Handle udp broadcast messages */
-      nReceived_size = recvfrom(TheNetworkStatus.nUDPListener,
-          g_acPCEthernetCommBuffer, PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
-          (struct sockaddr *) &stFrom, &nFromLen);
+    /*Handle udp broadcast messages */
+    nReceived_size = recvfrom(g_network_status.nUDPListener,
+                              g_acPCEthernetCommBuffer,
+                              PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
+                              (struct sockaddr *) &stFrom, &nFromLen);
 
 
-      if (nReceived_size <= 0)
-        { /* got error */
-          OPENER_TRACE_ERR(
-              "networkhandler: error on recvfrom udp broadcast port: %s\n",
-              strerror(errno));
-          return;
-        }
+    if (nReceived_size <= 0) { /* got error */
+      OPENER_TRACE_ERR(
+          "networkhandler: error on recvfrom udp broadcast port: %s\n",
+          strerror(errno));
+      return;
+    }
 
 
-      OPENER_TRACE_INFO("Data received on udp:\n");
+    OPENER_TRACE_INFO("Data received on udp:\n");
 
 
-      rxp = &g_acPCEthernetCommBuffer[0];
-      do
-        {
-          nReplyLen = handleReceivedExplictUDPData(
-              TheNetworkStatus.nUDPListener, &stFrom, rxp, nReceived_size,
-              &nRemainingBytes);
-
-          rxp += nReceived_size - nRemainingBytes;
-          nReceived_size = nRemainingBytes;
-
-          if (nReplyLen > 0)
-            {
-              OPENER_TRACE_INFO("reply sent:\n");
-
-              /* if the active fd matches a registered UDP callback, handle a UDP packet */
-              if (sendto(TheNetworkStatus.nUDPListener,
-                  (char *) g_acPCEthernetCommBuffer, nReplyLen, 0,
-                  (struct sockaddr *) &stFrom, sizeof(stFrom)) != nReplyLen)
-                {
-                  OPENER_TRACE_INFO(
-                      "networkhandler: UDP response was not fully sent\n");
-                }
-            }
+    rxp = &g_acPCEthernetCommBuffer[0];
+    do {
+      nReplyLen = HandleReceivedExplictUdpData(g_network_status.nUDPListener,
+                                               &stFrom, rxp, nReceived_size,
+                                               &nRemainingBytes);
+
+      rxp += nReceived_size - nRemainingBytes;
+      nReceived_size = nRemainingBytes;
+
+      if (nReplyLen > 0) {
+        OPENER_TRACE_INFO("reply sent:\n");
+
+        /* if the active fd matches a registered UDP callback, handle a UDP packet */
+        if (sendto(g_network_status.nUDPListener,
+                   (char *) g_acPCEthernetCommBuffer, nReplyLen, 0,
+                   (struct sockaddr *) &stFrom, sizeof(stFrom)) != nReplyLen) {
+          OPENER_TRACE_INFO(
+              "networkhandler: UDP response was not fully sent\n");
         }
         }
-      while (nRemainingBytes > 0);
-    }
+      }
+    } while (nRemainingBytes > 0);
+  }
 }
 }
 
 
-void
-checkAndHandleConsumingUDPSockets()
-{
+void checkAndHandleConsumingUDPSockets() {
   int nReceived_size;
   int nReceived_size;
   struct sockaddr_in stFrom;
   struct sockaddr_in stFrom;
 #ifndef WIN32
 #ifndef WIN32
@@ -672,39 +602,37 @@ checkAndHandleConsumingUDPSockets()
   unsigned long nFromLen;
   unsigned long nFromLen;
 #endif
 #endif
 
 
-  S_CIP_ConnectionObject *pstRunner = g_pstActiveConnectionList;
-  S_CIP_ConnectionObject *pstCurrent;
+  ConnectionObject *pstRunner = g_active_connection_list;
+  ConnectionObject *pstCurrent;
 
 
   /* see a message on one of the registered UDP sockets has been received     */
   /* see a message on one of the registered UDP sockets has been received     */
-  while (NULL != pstRunner)
-    {
-      pstCurrent = pstRunner;
-      pstRunner = pstRunner->m_pstNext; /* do this at the beginning as the close function may can make the entry invalid */
+  while (NULL != pstRunner) {
+    pstCurrent = pstRunner;
+    pstRunner = pstRunner->next_connection_object; /* do this at the beginning as the close function may can make the entry invalid */
 
 
-      if ((-1 != pstCurrent->sockfd[CONSUMING])
-          && (true == checkSocketSet(pstCurrent->sockfd[CONSUMING])))
-        {
-          nFromLen = sizeof(stFrom);
-          nReceived_size = recvfrom(pstCurrent->sockfd[CONSUMING],
-              g_acPCEthernetCommBuffer, PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
-              (struct sockaddr *) &stFrom, &nFromLen);
-          if (0 == nReceived_size)
-            {
-              OPENER_TRACE_STATE("connection closed by client\n");
-              pstCurrent->m_pfCloseFunc(pstCurrent);
-              continue;
-            }
-
-          if (0 > nReceived_size)
-            {
-              OPENER_TRACE_ERR("networkhandler: error on recv: %s\n", strerror(errno));
-              pstCurrent->m_pfCloseFunc(pstCurrent);
-              continue;
-            }
-
-          handleReceivedConnectedData(g_acPCEthernetCommBuffer, nReceived_size,
-              &stFrom);
+    if ((-1 != pstCurrent->socket[CONSUMING])
+        && (true == checkSocketSet(pstCurrent->socket[CONSUMING]))) {
+      nFromLen = sizeof(stFrom);
+      nReceived_size = recvfrom(pstCurrent->socket[CONSUMING],
+                                g_acPCEthernetCommBuffer,
+                                PC_OPENER_ETHERNET_BUFFER_SIZE, 0,
+                                (struct sockaddr *) &stFrom, &nFromLen);
+      if (0 == nReceived_size) {
+        OPENER_TRACE_STATE("connection closed by client\n");
+        pstCurrent->connection_close_function(pstCurrent);
+        continue;
+      }
+
+      if (0 > nReceived_size) {
+        OPENER_TRACE_ERR("networkhandler: error on recv: %s\n",
+                         strerror(errno));
+        pstCurrent->connection_close_function(pstCurrent);
+        continue;
+      }
+
+      HandleReceivedConnectedData(g_acPCEthernetCommBuffer, nReceived_size,
+                                  &stFrom);
 
 
-        }
     }
     }
+  }
 }
 }

+ 3 - 4
source/src/ports/WIN32/networkhandler.h

@@ -8,13 +8,12 @@
 
 
 #include "typedefs.h"
 #include "typedefs.h"
 
 
-
 /*! Start a TCP/UDP listening socket, accept connections, receive data in select loop, call manageConnections periodically.
 /*! Start a TCP/UDP listening socket, accept connections, receive data in select loop, call manageConnections periodically.
  *  @return status
  *  @return status
  *          EIP_ERROR .. error
  *          EIP_ERROR .. error
  */
  */
-EIP_STATUS NetworkHandler_Init(void);
-EIP_STATUS NetworkHandler_ProcessOnce(void);
-EIP_STATUS NetworkHandler_Finish(void);
+EipStatus NetworkHandler_Init(void);
+EipStatus NetworkHandler_ProcessOnce(void);
+EipStatus NetworkHandler_Finish(void);
 
 
 #endif /*NETWORKHANDLER_H_*/
 #endif /*NETWORKHANDLER_H_*/

+ 6 - 17
source/src/ports/WIN32/sample_application/opener_user_conf.h

@@ -48,7 +48,7 @@ typedef unsigned short in_port_t;
 
 
 /*! Define the number of supported explicit connections.
 /*! Define the number of supported explicit connections.
  *  According to ODVA's PUB 70 this number should be greater than 6.
  *  According to ODVA's PUB 70 this number should be greater than 6.
- */  
+ */
 #define OPENER_CIP_NUM_EXPLICIT_CONNS 6
 #define OPENER_CIP_NUM_EXPLICIT_CONNS 6
 
 
 /*! Define the number of supported exclusive owner connections.
 /*! Define the number of supported exclusive owner connections.
@@ -69,7 +69,6 @@ typedef unsigned short in_port_t;
  */
  */
 #define OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH 3
 #define OPENER_CIP_NUM_INPUT_ONLY_CONNS_PER_CON_PATH 3
 
 
-
 /*! Define the number of supported listen only connections.
 /*! Define the number of supported listen only connections.
  *  Each of these connections has to be configured with the function
  *  Each of these connections has to be configured with the function
  *  void configureListenOnlyConnectionPoint(unsigned int pa_unConnNum, unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly, unsigned int pa_unConfigAssembly)
  *  void configureListenOnlyConnectionPoint(unsigned int pa_unConnNum, unsigned int pa_unOutputAssembly, unsigned int pa_unInputAssembly, unsigned int pa_unConfigAssembly)
@@ -81,25 +80,23 @@ typedef unsigned short in_port_t;
  */
  */
 #define OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH   3
 #define OPENER_CIP_NUM_LISTEN_ONLY_CONNS_PER_CON_PATH   3
 
 
-
 /*! The number of bytes used for the buffer that will be used for generating any
 /*! The number of bytes used for the buffer that will be used for generating any
  *  reply data of messages. There are two uses in OpENer:
  *  reply data of messages. There are two uses in OpENer:
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    1. Explicit messages will use this buffer to store the data generated by the request
  *    2. I/O Connections will use this buffer for the produced data
  *    2. I/O Connections will use this buffer for the produced data
- */ 
+ */
 #define OPENER_MESSAGE_DATA_REPLY_BUFFER 100
 #define OPENER_MESSAGE_DATA_REPLY_BUFFER 100
 
 
 /*! Number of sessions that can be handled at the same time
 /*! Number of sessions that can be handled at the same time
- */ 
+ */
 #define OPENER_NUMBER_OF_SUPPORTED_SESSIONS 20
 #define OPENER_NUMBER_OF_SUPPORTED_SESSIONS 20
 
 
 /*! The time in ms of the timer used in this implementations
 /*! The time in ms of the timer used in this implementations
- */ 
+ */
 #define OPENER_TIMER_TICK 10 
 #define OPENER_TIMER_TICK 10 
 
 
-
 /*! Define if RUN IDLE data is sent with consumed data
 /*! Define if RUN IDLE data is sent with consumed data
- */ 
+ */
 #define OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER 1
 #define OPENER_CONSUMED_DATA_HAS_RUN_IDLE_HEADER 1
 
 
 /*! Define if RUN IDLE data is to be sent with produced data
 /*! Define if RUN IDLE data is to be sent with produced data
@@ -108,8 +105,6 @@ typedef unsigned short in_port_t;
  */
  */
 #define OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER 0
 #define OPENER_PRODUCED_DATA_HAS_RUN_IDLE_HEADER 0
 
 
-
-
 #ifdef OPENER_WITH_TRACES
 #ifdef OPENER_WITH_TRACES
 /* If we have tracing enabled provide print tracing macro */
 /* If we have tracing enabled provide print tracing macro */
 #include <stdio.h>
 #include <stdio.h>
@@ -118,7 +113,6 @@ typedef unsigned short in_port_t;
 
 
 /*#define PRINT_TRACE(args...)  fprintf(stderr,args);*/
 /*#define PRINT_TRACE(args...)  fprintf(stderr,args);*/
 
 
-
 /*! A specialized assertion command that will log the assertion and block
 /*! A specialized assertion command that will log the assertion and block
  *  further execution in an while(1) loop.
  *  further execution in an while(1) loop.
  */
  */
@@ -134,7 +128,6 @@ typedef unsigned short in_port_t;
 //#include <assert.h>
 //#include <assert.h>
 //#include <stdio.h>
 //#include <stdio.h>
 //#define OPENER_ASSERT(assertion) assert(assertion)
 //#define OPENER_ASSERT(assertion) assert(assertion)
-
 #else
 #else
 
 
 /* for release builds execute the assertion, but don't test it */
 /* for release builds execute the assertion, but don't test it */
@@ -145,16 +138,13 @@ typedef unsigned short in_port_t;
  *  macro can be used as below
  *  macro can be used as below
  */
  */
 //#define OPENER_ASSERT(assertion)
 //#define OPENER_ASSERT(assertion)
-
 /* else if you still want assertions to stop execution but without tracing, use the following */
 /* else if you still want assertions to stop execution but without tracing, use the following */
 //#define OPENER_ASSERT(assertion) do { if(!(assertion)) { while(1){;} } } while (0)
 //#define OPENER_ASSERT(assertion) do { if(!(assertion)) { while(1){;} } } while (0)
-
 /* else use standard assert() */
 /* else use standard assert() */
 //#include <assert.h>
 //#include <assert.h>
 //#include <stdio.h>
 //#include <stdio.h>
 //#define OPENER_ASSERT(assertion) assert(assertion)
 //#define OPENER_ASSERT(assertion) assert(assertion)
 
 
-
 #endif
 #endif
 
 
 /*! The number of bytes used for the Ethernet message buffer on
 /*! The number of bytes used for the Ethernet message buffer on
@@ -163,10 +153,9 @@ typedef unsigned short in_port_t;
  *
  *
  *  This buffer size will be used for any received message.
  *  This buffer size will be used for any received message.
  *  The same buffer is used for the replied explicit message.
  *  The same buffer is used for the replied explicit message.
- */ 
+ */
 #define PC_OPENER_ETHERNET_BUFFER_SIZE 512
 #define PC_OPENER_ETHERNET_BUFFER_SIZE 512
 
 
-
 /*! If this define is here opener will enable 64Bit data type support.
 /*! If this define is here opener will enable 64Bit data type support.
  *
  *
  */
  */

+ 64 - 82
source/src/ports/WIN32/sample_application/sampleapplication.c

@@ -8,7 +8,6 @@
 #include <string.h>
 #include <string.h>
 #include <stdlib.h>
 #include <stdlib.h>
 
 
-
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_INPUT_ASSEMBLY_NUM                100 //0x064
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_OUTPUT_ASSEMBLY_NUM               150 //0x096
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
 #define DEMO_APP_CONFIG_ASSEMBLY_NUM               151 //0x097
@@ -18,59 +17,57 @@
 
 
 /* global variables for demo application (4 assembly data fields)  ************/
 /* global variables for demo application (4 assembly data fields)  ************/
 
 
-EIP_UINT8 g_assemblydata064[32]; /* Input */
-EIP_UINT8 g_assemblydata096[32]; /* Output */
-EIP_UINT8 g_assemblydata097[10]; /* Config */
-EIP_UINT8 g_assemblydata09A[32]; /* Explicit */
+EipUint8 g_assemblydata064[32]; /* Input */
+EipUint8 g_assemblydata096[32]; /* Output */
+EipUint8 g_assemblydata097[10]; /* Config */
+EipUint8 g_assemblydata09A[32]; /* Explicit */
 
 
-EIP_STATUS
-IApp_Init(void)
-{
+EipStatus ApplicationInitialization(void) {
   /* create 3 assembly object instances*/
   /* create 3 assembly object instances*/
   /*INPUT*/
   /*INPUT*/
-  createAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, &g_assemblydata064[0],
-      sizeof(g_assemblydata064));
+  CreateAssemblyObject(DEMO_APP_INPUT_ASSEMBLY_NUM, &g_assemblydata064[0],
+                       sizeof(g_assemblydata064));
 
 
   /*OUTPUT*/
   /*OUTPUT*/
-  createAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, &g_assemblydata096[0],
-      sizeof(g_assemblydata096));
+  CreateAssemblyObject(DEMO_APP_OUTPUT_ASSEMBLY_NUM, &g_assemblydata096[0],
+                       sizeof(g_assemblydata096));
 
 
   /*CONFIG*/
   /*CONFIG*/
-  createAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, &g_assemblydata097[0],
-      sizeof(g_assemblydata097));
+  CreateAssemblyObject(DEMO_APP_CONFIG_ASSEMBLY_NUM, &g_assemblydata097[0],
+                       sizeof(g_assemblydata097));
 
 
   /*Heart-beat output assembly for Input only connections */
   /*Heart-beat output assembly for Input only connections */
-  createAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /*Heart-beat output assembly for Listen only connections */
   /*Heart-beat output assembly for Listen only connections */
-  createAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
+  CreateAssemblyObject(DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, 0, 0);
 
 
   /* assembly for explicit messaging */
   /* assembly for explicit messaging */
-  createAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assemblydata09A[0],
-      sizeof(g_assemblydata09A));
-
-  configureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM,
-      DEMO_APP_INPUT_ASSEMBLY_NUM, DEMO_APP_CONFIG_ASSEMBLY_NUM);
-  configureInputOnlyConnectionPoint(0,
-      DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM, DEMO_APP_INPUT_ASSEMBLY_NUM,
-      DEMO_APP_CONFIG_ASSEMBLY_NUM);
-  configureListenOnlyConnectionPoint(0,
-      DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM, DEMO_APP_INPUT_ASSEMBLY_NUM,
-      DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  CreateAssemblyObject(DEMO_APP_EXPLICT_ASSEMBLY_NUM, &g_assemblydata09A[0],
+                       sizeof(g_assemblydata09A));
+
+  ConfigureExclusiveOwnerConnectionPoint(0, DEMO_APP_OUTPUT_ASSEMBLY_NUM,
+  DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                         DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  ConfigureInputOnlyConnectionPoint(0,
+  DEMO_APP_HEARBEAT_INPUT_ONLY_ASSEMBLY_NUM,
+                                    DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                    DEMO_APP_CONFIG_ASSEMBLY_NUM);
+  ConfigureListenOnlyConnectionPoint(0,
+  DEMO_APP_HEARBEAT_LISTEN_ONLY_ASSEMBLY_NUM,
+                                     DEMO_APP_INPUT_ASSEMBLY_NUM,
+                                     DEMO_APP_CONFIG_ASSEMBLY_NUM);
 
 
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-void
-IApp_HandleApplication(void)
-{
+void HandleApplication(void) {
   /* check if application needs to trigger an connection */
   /* check if application needs to trigger an connection */
 }
 }
 
 
-void
-IApp_IOConnectionEvent(unsigned int pa_unOutputAssembly,
-    unsigned int pa_unInputAssembly, EIOConnectionEvent pa_eIOConnectionEvent)
-{
+void IoConnectionEvent(unsigned int pa_unOutputAssembly,
+                       unsigned int pa_unInputAssembly,
+                       EIOConnectionEvent pa_eIOConnectionEvent) {
   /* maintain a correct output state according to the connection state*/
   /* maintain a correct output state according to the connection state*/
 
 
   (void) pa_unOutputAssembly; /* suppress compiler warning */
   (void) pa_unOutputAssembly; /* suppress compiler warning */
@@ -78,85 +75,70 @@ IApp_IOConnectionEvent(unsigned int pa_unOutputAssembly,
   (void) pa_eIOConnectionEvent; /* suppress compiler warning */
   (void) pa_eIOConnectionEvent; /* suppress compiler warning */
 }
 }
 
 
-EIP_STATUS
-IApp_AfterAssemblyDataReceived(S_CIP_Instance *pa_pstInstance)
-{
-  EIP_STATUS nRetVal = EIP_OK;
+EipStatus AfterAssemblyDataReceived(CipInstance *pa_pstInstance) {
+  EipStatus nRetVal = EIP_OK;
 
 
   /*handle the data received e.g., update outputs of the device */
   /*handle the data received e.g., update outputs of the device */
-  switch (pa_pstInstance->nInstanceNr)
-    {
-  case DEMO_APP_OUTPUT_ASSEMBLY_NUM:
-    /* Data for the output assembly has been received.
-     * Mirror it to the inputs */
-    memcpy(&g_assemblydata064[0], &g_assemblydata096[0],
-        sizeof(g_assemblydata064));
-    break;
-  case DEMO_APP_EXPLICT_ASSEMBLY_NUM:
-    /* do something interesting with the new data from
-     * the explicit set-data-attribute message */
-    break;
-  case DEMO_APP_CONFIG_ASSEMBLY_NUM:
-    /* Add here code to handle configuration data and check if it is ok
-     * The demo application does not handle config data.
-     * However in order to pass the test we accept any data given.
-     * EIP_ERROR
-     */
-    nRetVal = EIP_OK;
-    break;
-    }
+  switch (pa_pstInstance->instance_number) {
+    case DEMO_APP_OUTPUT_ASSEMBLY_NUM:
+      /* Data for the output assembly has been received.
+       * Mirror it to the inputs */
+      memcpy(&g_assemblydata064[0], &g_assemblydata096[0],
+             sizeof(g_assemblydata064));
+      break;
+    case DEMO_APP_EXPLICT_ASSEMBLY_NUM:
+      /* do something interesting with the new data from
+       * the explicit set-data-attribute message */
+      break;
+    case DEMO_APP_CONFIG_ASSEMBLY_NUM:
+      /* Add here code to handle configuration data and check if it is ok
+       * The demo application does not handle config data.
+       * However in order to pass the test we accept any data given.
+       * EIP_ERROR
+       */
+      nRetVal = EIP_OK;
+      break;
+  }
   return nRetVal;
   return nRetVal;
 }
 }
 
 
-EIP_BOOL8
-IApp_BeforeAssemblyDataSend(S_CIP_Instance *pa_pstInstance)
-{
+EipBool8 BeforeAssemblyDataSend(CipInstance *pa_pstInstance) {
   /*update data to be sent e.g., read inputs of the device */
   /*update data to be sent e.g., read inputs of the device */
   /*In this sample app we mirror the data from out to inputs on data receive
   /*In this sample app we mirror the data from out to inputs on data receive
    * therefore we need nothing to do here. Just return true to inform that
    * therefore we need nothing to do here. Just return true to inform that
    * the data is new.
    * the data is new.
    */
    */
 
 
-  if (pa_pstInstance->nInstanceNr == DEMO_APP_EXPLICT_ASSEMBLY_NUM)
-    {
-      /* do something interesting with the existing data
-       * for the explicit get-data-attribute message */
-    }
+  if (pa_pstInstance->instance_number == DEMO_APP_EXPLICT_ASSEMBLY_NUM) {
+    /* do something interesting with the existing data
+     * for the explicit get-data-attribute message */
+  }
   return true;
   return true;
 }
 }
 
 
-EIP_STATUS
-IApp_ResetDevice(void)
-{
+EipStatus ResetDevice(void) {
   /* add reset code here*/
   /* add reset code here*/
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
-EIP_STATUS
-IApp_ResetDeviceToInitialConfiguration(void)
-{
+EipStatus ResetDeviceToInitialConfiguration(void) {
   /*rest the parameters */
   /*rest the parameters */
 
 
   /*than perform device reset*/
   /*than perform device reset*/
-  IApp_ResetDevice();
+  ResetDevice();
   return EIP_OK;
   return EIP_OK;
 }
 }
 
 
 void *
 void *
-IApp_CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement)
-{
+CipCalloc(unsigned pa_nNumberOfElements, unsigned pa_nSizeOfElement) {
   return calloc(pa_nNumberOfElements, pa_nSizeOfElement);
   return calloc(pa_nNumberOfElements, pa_nSizeOfElement);
 }
 }
 
 
-void
-IApp_CipFree(void *pa_poData)
-{
+void CipFree(void *pa_poData) {
   free(pa_poData);
   free(pa_poData);
 }
 }
 
 
-void
-IApp_RunIdleChanged(EIP_UINT32 pa_nRunIdleValue)
-{
+void RunIdleChanged(EipUint32 pa_nRunIdleValue) {
   (void) pa_nRunIdleValue;
   (void) pa_nRunIdleValue;
 }
 }
 
 

+ 44 - 31
source/src/trace.h

@@ -3,68 +3,81 @@
  * All rights reserved.
  * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef TRACE_H_
-#define TRACE_H_
+#ifndef OPENER_TRACE_H_
+#define OPENER_TRACE_H_
 
 
 #include <opener_user_conf.h>
 #include <opener_user_conf.h>
 
 
-/*!\file
- * \brief Tracing infrastructure for OpENer
+/** @file trace.h
+ * @brief Tracing infrastructure for OpENer
  */
  */
 
 
 #ifdef OPENER_WITH_TRACES
 #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
+/** @def OPENER_TRACE_LEVEL_ERROR 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
+/** @def OPENER_TRACE_LEVEL_WARNING Enable tracing of warning messages */
+#define OPENER_TRACE_LEVEL_WARNING 0x02
 
 
-/*! Enable tracing of state messages*/
-#define OPENER_TRACE_LEVEL_STATE    0x04
+/** @def OPENER_TRACE_LEVEL_WARNING Enable tracing of state messages */
+#define OPENER_TRACE_LEVEL_STATE 0x04
 
 
-/*! Enable tracing of info messages*/
-#define OPENER_TRACE_LEVEL_INFO     0x08
+/** @def OPENER_TRACE_LEVEL_INFO Enable tracing of info messages*/
+#define OPENER_TRACE_LEVEL_INFO 0x08
 
 
 #ifndef OPENER_TRACE_LEVEL
 #ifndef OPENER_TRACE_LEVEL
 #ifdef WIN32
 #ifdef WIN32
-	#pragma message ("OPENER_TRACE_LEVEL was not defined setting it to OPENER_TRACE_LEVEL_ERROR")
+#pragma message( \
+    "OPENER_TRACE_LEVEL was not defined setting it to OPENER_TRACE_LEVEL_ERROR")
 #else
 #else
-	#warning OPENER_TRACE_LEVEL was not defined setting it to OPENER_TRACE_LEVEL_ERROR
+#warning OPENER_TRACE_LEVEL was not defined setting it to OPENER_TRACE_LEVEL_ERROR
 #endif
 #endif
 
 
 #define OPENER_TRACE_LEVEL OPENER_TRACE_LEVEL_ERROR
 #define OPENER_TRACE_LEVEL OPENER_TRACE_LEVEL_ERROR
 #endif
 #endif
 
 
-#define OPENER_TRACE_ENABLED      /* can be used for conditional code compilation */
+/* @def OPENER_TRACE_ENABLED Can be used for conditional code compilation */
+#define OPENER_TRACE_ENABLED
 
 
-/*! Trace error messages.
+/** @def OPENER_TRACE_ERR(...) Trace error messages.
  *  In order to activate this trace level set the OPENER_TRACE_LEVEL_ERROR flag
  *  In order to activate this trace level set the OPENER_TRACE_LEVEL_ERROR flag
  *  in OPENER_TRACE_LEVEL.
  *  in OPENER_TRACE_LEVEL.
  */
  */
-#define OPENER_TRACE_ERR(...)   do { if (OPENER_TRACE_LEVEL_ERROR & OPENER_TRACE_LEVEL) \
-      LOG_TRACE(__VA_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_ERR(...)                                                  \
+  do {                                                                         \
+    if (OPENER_TRACE_LEVEL_ERROR & OPENER_TRACE_LEVEL) LOG_TRACE(__VA_ARGS__); \
+  } while (0)
+
+/** @def OPENER_TRACE_WARN(...) 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(...)  do { if (OPENER_TRACE_LEVEL_WARNING & OPENER_TRACE_LEVEL) \
-      LOG_TRACE(__VA_ARGS__); } while(0)
+#define OPENER_TRACE_WARN(...)                           \
+  do {                                                   \
+    if (OPENER_TRACE_LEVEL_WARNING & OPENER_TRACE_LEVEL) \
+      LOG_TRACE(__VA_ARGS__);                            \
+  } while (0)
 
 
-/*! Trace state messages.
+/** @def OPENER_TRACE_STATE(...) Trace state messages.
  *  In order to activate this trace level set the OPENER_TRACE_LEVEL_STATE flag
  *  In order to activate this trace level set the OPENER_TRACE_LEVEL_STATE flag
  *  in OPENER_TRACE_LEVEL.
  *  in OPENER_TRACE_LEVEL.
  */
  */
-#define OPENER_TRACE_STATE(...) do { if (OPENER_TRACE_LEVEL_STATE & OPENER_TRACE_LEVEL) \
-      LOG_TRACE(__VA_ARGS__); } while(0)
+#define OPENER_TRACE_STATE(...)                                                \
+  do {                                                                         \
+    if (OPENER_TRACE_LEVEL_STATE & OPENER_TRACE_LEVEL) LOG_TRACE(__VA_ARGS__); \
+  } while (0)
 
 
-/*! Trace information messages.
+/** @def OPENER_TRACE_INFO(...) Trace information messages.
  *  In order to activate this trace level set the OPENER_TRACE_LEVEL_INFO flag
  *  In order to activate this trace level set the OPENER_TRACE_LEVEL_INFO flag
  *  in OPENER_TRACE_LEVEL.
  *  in OPENER_TRACE_LEVEL.
  */
  */
-#define OPENER_TRACE_INFO(...)  do { if (OPENER_TRACE_LEVEL_INFO & OPENER_TRACE_LEVEL) \
-      LOG_TRACE(__VA_ARGS__); } while(0)
+#define OPENER_TRACE_INFO(...)                                                \
+  do {                                                                        \
+    if (OPENER_TRACE_LEVEL_INFO & OPENER_TRACE_LEVEL) LOG_TRACE(__VA_ARGS__); \
+  } while (0)
 
 
 #else
 #else
 /* define the tracing macros empty in order to save space */
 /* define the tracing macros empty in order to save space */
@@ -76,4 +89,4 @@
 #endif
 #endif
 /* TRACING *******************************************************************/
 /* TRACING *******************************************************************/
 
 
-#endif /*TRACE_H_*/
+#endif /*OPENER_TRACE_H_*/

+ 69 - 33
source/src/typedefs.h

@@ -1,16 +1,17 @@
 /*******************************************************************************
 /*******************************************************************************
  * Copyright (c) 2009, Rockwell Automation, Inc.
  * Copyright (c) 2009, Rockwell Automation, Inc.
- * All rights reserved. 
+ * All rights reserved.
  *
  *
  ******************************************************************************/
  ******************************************************************************/
-#ifndef TYPEDEFS_H_
-#define TYPEDEFS_H_
+#ifndef OPENER_TYPEDEFS_H_
+#define OPENER_TYPEDEFS_H_
 
 
-#include <opener_user_conf.h>
 #include <inttypes.h>
 #include <inttypes.h>
 #include <stddef.h>
 #include <stddef.h>
 
 
-/**
+#include "opener_user_conf.h"
+
+/** @file typedefs.h
  Do not use interface types for internal variables, such as "int i;", which is
  Do not use interface types for internal variables, such as "int i;", which is
  commonly used for loop counters or counting things.
  commonly used for loop counters or counting things.
 
 
@@ -23,26 +24,47 @@
  for data buffers can occasionally blow up in your face rather nastily.
  for data buffers can occasionally blow up in your face rather nastily.
  */
  */
 
 
-#define EIP_BYTE 	uint8_t
-#define EIP_INT8 	int8_t
-#define EIP_INT16	int16_t
-#define EIP_INT32	int32_t
-#define EIP_UINT8	uint8_t
-#define EIP_UINT16	uint16_t
-#define EIP_UINT32	uint32_t
-#define EIP_FLOAT	float
-#define EIP_DFLOAT	double
-#define EIP_BOOL8	int
+/** @brief EIP Data type definitions
+ */
+typedef uint8_t EipByte; /**< 8-bit bit string */
+typedef int8_t EipInt8; /**< 8-bit signed number */
+typedef int16_t EipInt16; /**< 16-bit signed number */
+typedef int32_t EipInt32; /**< 32-bit signed number */
+typedef uint8_t EipUint8; /**< 8-bit unsigned number */
+typedef uint16_t EipUint16; /**< 16-bit unsigned number */
+typedef uint32_t EipUint32; /**< 32-bit unsigned number */
+typedef float EipFloat; /**< IEEE 754 32-bit floating point number */
+typedef double EipDfloat; /**< IEEE 754 64-bit floating point number */
+typedef uint8_t EipBool8; /**< bool data types */
+
+/** @brief Data types as defined in the CIP Specification Vol 1 Appendix C
+ */
+typedef uint8_t CipOctet; /**< 8 bit value that indicates particular data type */
+typedef uint8_t CipBool; /**< Boolean data type */
+typedef uint8_t CipByte; /**< 8-bit bit string */
+typedef uint16_t CipWord; /**< 16-bit bit string */
+typedef uint32_t CipDword; /**< 32-bit bit string */
+typedef uint8_t CipUsint; /**< 8-bit unsigned integer */
+typedef uint16_t CipUint; /**< CipUint 16-bit unsigned integer */
+typedef uint32_t CipUdint; /**< CipUdint 32-bit unsigned integer */
+typedef int8_t CipSint; /**< 8-bit signed integer */
+typedef int16_t CipInt; /**< 16-bit signed integer */
+typedef int32_t CipDint; /**< 32-bit signed integer */
+typedef float CipReal; /**< 32-bit IEEE 754 floating point */
+typedef double CipLreal; /**< 64-bit IEEE 754 floating point */
 
 
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
 #ifdef OPENER_SUPPORT_64BIT_DATATYPES
-#define EIP_INT64       int64_t
-#define EIP_UINT64      uint64_t
-#endif
-#endif
+typedef int64_t EipInt64; /**< 64-bit signed number */
+typedef uint64_t EipUint64; /**< 64-bit unsigned number */
+
+typedef int64_t CipLint; /**< 64-bit signed integer */
+typedef uint64_t CipUlint; /**< 64-bit unsigned integer */
+typedef uint64_t CipLword; /**< 64-bit bit string */
+#endif /* OPENER_SUPPORT_64BIT_DATATYPES */
 
 
-/*! Constant identifying if a socket descriptor is invalid
+/** @brief Constant identifying if a socket descriptor is invalid
  */
  */
-#define EIP_INVALID_SOCKET      -1
+static const int kEipInvalidSocket = -1;
 
 
 /**
 /**
 
 
@@ -63,18 +85,32 @@
 
 
  */
  */
 
 
-typedef enum
-{
-  EIP_OK = 0,
-  EIP_OK_SEND = 1,
-  EIP_ERROR = -1
-} EIP_STATUS;
+/** @brief EIP stack status enum
+ *
+ */
+typedef enum {
+  kEipStatusOk = 0, /**< Stack is ok */
+  kEipStatusOkSend = 1, /**< Stack is ok, after send */
+  kEipStatusError = -1 /**< Stack is in error */
+} EipStatus;
+
+/** @brief Communication direction of an UDP socket; consuming is receiver,
+ * producing is sender
+ *
+ * These are used as array indexes, watch out if changing these values
+ */
+typedef enum {
+  kUdpCommuncationDirectionConsuming = 0, /**< Consuming direction; receiver */
+  kUdpCommuncationDirectionProducing = 1 /**< Producing direction; sender */
+} UdpCommuncationDirection;
 
 
 #ifndef __cplusplus
 #ifndef __cplusplus
-/*! If we don't have C++ define a C++ -like "bool" keyword defines*/
-#define false 0
-#define true 1
-
-#endif
+/** @brief If we don't have C++ define a C++ -like "bool" keyword defines
+ */
+typedef enum {
+  false = 0, /**< defines "false" as 0 */
+  true = 1 /**< defines "true" as 1 */
+} BoolKeywords;
+#endif /* __cplusplus */
 
 
-#endif /*TYPEDEFS_H_*/
+#endif /* OPENER_TYPEDEFS_H_ */

+ 4 - 5
source/src/utils/random.c

@@ -7,9 +7,8 @@
 
 
 #include "random.h"
 #include "random.h"
 
 
-Random* random_new(setSeedfn pa_fnpSetSeed, getNextUInt32fn pa_fnGetNextUInt32)
-{
-	Random* out = malloc(sizeof(Random));
-	*out = (Random){.setSeed = pa_fnpSetSeed, .getNextUInt32 = pa_fnGetNextUInt32};
-	return out;
+Random *RandomNew(SetSeed set_seed, GetNextUInt32 get_next_uint32) {
+  Random *out = malloc(sizeof(Random));
+  *out = (Random ) { .set_seed = set_seed, .get_next_uint32 = get_next_uint32 };
+  return out;
 }
 }

+ 10 - 11
source/src/utils/random.h

@@ -5,21 +5,20 @@
  *      Author: mmm
  *      Author: mmm
  */
  */
 
 
-#ifndef RANDOM_H_
-#define RANDOM_H_
+#ifndef OPENER_RANDOM_H_
+#define OPENER_RANDOM_H_
 
 
 #include <stdint.h>
 #include <stdint.h>
 
 
-typedef void (*setSeedfn)(uint32_t pa_nSeed);
-typedef uint32_t (*getNextUInt32fn)(void);
+typedef void (*SetSeed)(uint32_t seed);
+typedef uint32_t (*GetNextUInt32)(void);
 
 
-typedef struct
-{
-	uint32_t nXorShiftSeed; /**< Holds the current seed/random value */
-	setSeedfn setSeed; /**< Function pointer to setSeed function */
-	getNextUInt32fn getNextUInt32; /**< Function pointer to getNextUInt32 function */
+typedef struct {
+  uint32_t current_seed_value; /**< Holds the current seed/random value */
+  SetSeed set_seed; /**< Function pointer to SetSeed function */
+  GetNextUInt32 get_next_uint32; /**< Function pointer to GetNextUInt32 function */
 } Random;
 } Random;
 
 
-Random* random_new(setSeedfn, getNextUInt32fn);
+Random* RandomNew(SetSeed, GetNextUInt32);
 
 
-#endif /* RANDOM_H_ */
+#endif /* OPENER_RANDOM_H_ */

+ 11 - 14
source/src/utils/xorshiftrandom.c

@@ -7,26 +7,23 @@
 
 
 #include "xorshiftrandom.h"
 #include "xorshiftrandom.h"
 
 
-static uint32_t nXorShiftSeed; /*! < File-global variable holding the current seed*/
+static uint32_t xor_shift_seed; /** < File-global variable holding the current seed*/
 
 
-void setXorShiftSeed(uint32_t pa_nSeed)
-{
-	nXorShiftSeed = pa_nSeed;
+void SetXorShiftSeed(uint32_t seed) {
+  xor_shift_seed = seed;
 }
 }
 
 
-/*!
+/** @brief Pseudo-random number algorithm
  * The algorithm used to create the pseudo-random numbers.
  * The algorithm used to create the pseudo-random numbers.
  * Works directly on the file global variable
  * Works directly on the file global variable
  */
  */
-void calculateNextSeed(void)
-{
-	nXorShiftSeed ^= nXorShiftSeed << 13;
-	nXorShiftSeed ^= nXorShiftSeed >> 17;
-	nXorShiftSeed ^= nXorShiftSeed << 5;
+void CalculateNextSeed(void) {
+  xor_shift_seed ^= xor_shift_seed << 13;
+  xor_shift_seed ^= xor_shift_seed >> 17;
+  xor_shift_seed ^= xor_shift_seed << 5;
 }
 }
 
 
-uint32_t nextXorShiftUInt32(void)
-{
-	calculateNextSeed();
-	return nXorShiftSeed;
+uint32_t NextXorShiftUInt32(void) {
+  CalculateNextSeed();
+  return xor_shift_seed;
 }
 }

+ 13 - 13
source/src/utils/xorshiftrandom.h

@@ -5,26 +5,26 @@
  *      Author: mmm
  *      Author: mmm
  */
  */
 
 
-/*!
- * \file xorshiftrandom.h
+/**
+ * @file xorshiftrandom.h
  *
  *
  * The public interface of the XOR shift pseudo-random number generator
  * The public interface of the XOR shift pseudo-random number generator
  */
  */
 #include <stdint.h>
 #include <stdint.h>
 
 
-#ifndef XORSHIFTRANDOM_H_
-#define XORSHIFTRANDOM_H_
+#ifndef OPENER_XORSHIFTRANDOM_H_
+#define OPENER_XORSHIFTRANDOM_H_
 
 
-/*!
- * Sets the initial seed for the XOR shift pseudo-random algorithm
- * \param pa_nSeed The initial seed value
+/**
+ * @brief Sets the initial seed for the XOR shift pseudo-random algorithm
+ * @param pa_nSeed The initial seed value
  */
  */
-void setXorShiftSeed(uint32_t pa_nSeed);
+void SetXorShiftSeed(uint32_t seed);
 
 
-/*!
- * Returns the next generated pseudo-random number
- * \return The next pseudo-random number
+/**
+ * @brief Returns the next generated pseudo-random number
+ * @return The next pseudo-random number
  */
  */
-uint32_t nextXorShiftUInt32(void);
+uint32_t NextXorShiftUint32(void);
 
 
-#endif /* XORSHIFTRANDOM_H_ */
+#endif /* OPENER__XORSHIFTRANDOM_H_ */

+ 3 - 3
source/tests/utils/randomTests.cpp

@@ -22,7 +22,7 @@ TEST(RandomClass, CreateXOrShiftObject)
 {
 {
 	Random* pRandom;
 	Random* pRandom;
 	uint32_t nResult = 0;
 	uint32_t nResult = 0;
-	pRandom = random_new(setXorShiftSeed, nextXorShiftUInt32);
-	POINTERS_EQUAL(setXorShiftSeed, pRandom->setSeed);
-	POINTERS_EQUAL(nextXorShiftUInt32, pRandom->getNextUInt32);
+	pRandom = random_new(SetXorShiftSeed, NextXorShiftUint32);
+	POINTERS_EQUAL(SetXorShiftSeed, pRandom->setSeed);
+	POINTERS_EQUAL(NextXorShiftUint32, pRandom->getNextUInt32);
 }
 }

+ 7 - 7
source/tests/utils/xorshiftrandomtests.cpp

@@ -22,8 +22,8 @@ TEST(XorShiftRandom, SeedZeroInitResult)
 {
 {
 	uint32_t nResult;
 	uint32_t nResult;
 	nResult = 1;
 	nResult = 1;
-	setXorShiftSeed(0);
-	nResult = nextXorShiftUInt32();
+	SetXorShiftSeed(0);
+	nResult = NextXorShiftUint32();
 	LONGS_EQUAL(0, nResult);
 	LONGS_EQUAL(0, nResult);
 }
 }
 
 
@@ -31,13 +31,13 @@ TEST(XorShiftRandom, SeedZeroInitResult)
 TEST(XorShiftRandom, SeedOneCharacterization)
 TEST(XorShiftRandom, SeedOneCharacterization)
 {
 {
 	uint32_t nResult;
 	uint32_t nResult;
-	setXorShiftSeed(1);
-	nResult = nextXorShiftUInt32();
+	SetXorShiftSeed(1);
+	nResult = NextXorShiftUint32();
 	LONGS_EQUAL(270369, nResult);
 	LONGS_EQUAL(270369, nResult);
-	nResult = nextXorShiftUInt32();
+	nResult = NextXorShiftUint32();
 	LONGS_EQUAL(67634689, nResult);
 	LONGS_EQUAL(67634689, nResult);
-	nResult = nextXorShiftUInt32();
+	nResult = NextXorShiftUint32();
 	LONGS_EQUAL(2647435461, nResult);
 	LONGS_EQUAL(2647435461, nResult);
-	nResult = nextXorShiftUInt32();
+	nResult = NextXorShiftUint32();
 	LONGS_EQUAL(307599695, nResult);
 	LONGS_EQUAL(307599695, nResult);
 }
 }

部分文件因文件數量過多而無法顯示