### Build Examples with Makefiles Source: https://github.com/mz-automation/libiec61850/blob/v1.6/README.md Builds all examples included with the library using the provided makefiles. The resulting binaries will be in the project root directory. ```bash make examples ``` -------------------------------- ### Install libiec61850 using Make Source: https://github.com/mz-automation/libiec61850/blob/v1.6/README.md Installs the API header files and static library to a specified directory. The default installation directory for the make build script is '.install'. ```bash make install ``` ```bash make INSTALL_PREFIX=/usr/local install ``` -------------------------------- ### Install and Configure Report Handler in C Source: https://context7.com/mz-automation/libiec61850/llms.txt Defines a callback function for report reception and demonstrates the setup process, including reading dataset values, configuring RCB parameters, and enabling reporting. ```c #include "iec61850_client.h" #include "hal_thread.h" #include /* Report callback function - called when report is received */ void reportCallbackFunction(void* parameter, ClientReport report) { MmsValue* dataSetValues = ClientReport_getDataSetValues(report); printf("Received report for %s\n", ClientReport_getRcbReference(report)); /* Iterate through data set values */ int i; for (i = 0; i < 4; i++) { ReasonForInclusion reason = ClientReport_getReasonForInclusion(report, i); if (reason != IEC61850_REASON_NOT_INCLUDED) { printf(" GGIO1.SPCSO%d.stVal: %d (reason: %d)\n", i, MmsValue_getBoolean(MmsValue_getElement(dataSetValues, i)), reason); } } } /* Setup reporting for a client connection */ void setupReporting(IedConnection con) { IedClientError error; /* Read data set values */ ClientDataSet clientDataSet = IedConnection_readDataSetValues(con, &error, "simpleIOGenericIO/LLN0.Events", NULL); if (clientDataSet == NULL) { printf("Failed to read dataset\n"); return; } /* Get RCB values from server */ ClientReportControlBlock rcb = IedConnection_getRCBValues(con, &error, "simpleIOGenericIO/LLN0.RP.EventsRCB01", NULL); if (rcb) { /* Install report handler */ IedConnection_installReportHandler(con, "simpleIOGenericIO/LLN0.RP.EventsRCB01", ClientReportControlBlock_getRptId(rcb), reportCallbackFunction, NULL); /* Configure and enable report */ ClientReportControlBlock_setTrgOps(rcb, TRG_OPT_DATA_UPDATE | TRG_OPT_INTEGRITY | TRG_OPT_GI); ClientReportControlBlock_setRptEna(rcb, true); ClientReportControlBlock_setIntgPd(rcb, 5000); /* 5 second integrity period */ IedConnection_setRCBValues(con, &error, rcb, RCB_ELEMENT_RPT_ENA | RCB_ELEMENT_TRG_OPS | RCB_ELEMENT_INTG_PD, true); if (error != IED_ERROR_OK) printf("Report activation failed (code: %d)\n", error); /* Trigger General Interrogation report */ Thread_sleep(1000); ClientReportControlBlock_setGI(rcb, true); IedConnection_setRCBValues(con, &error, rcb, RCB_ELEMENT_GI, true); /* Wait for reports... */ Thread_sleep(60000); /* Disable reporting */ ClientReportControlBlock_setRptEna(rcb, false); IedConnection_setRCBValues(con, &error, rcb, RCB_ELEMENT_RPT_ENA, true); ClientReportControlBlock_destroy(rcb); } ClientDataSet_destroy(clientDataSet); } ``` -------------------------------- ### Run Basic Server Example Source: https://github.com/mz-automation/libiec61850/blob/v1.6/README.md Executes the basic server example application. This is typically run with sudo on Linux to ensure proper permissions. ```bash cd examples/server_example_basic_io sudo ./server_example_basic_io ``` -------------------------------- ### Configure Client Example Log Executable Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/iec61850_client_example_log/CMakeLists.txt Defines the source files for the client example log executable and links it against the iec61850 library. Conditional compilation for MSVC is included. ```cmake set(iec61850_client_example_log_SRCS client_example_log.c ) IF(MSVC) set_source_files_properties(${iec61850_client_example_log_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(iec61850_client_example_log ${iec61850_client_example_log_SRCS} ) target_link_libraries(iec61850_client_example_log iec61850 ) ``` -------------------------------- ### Install Development Packages on Ubuntu Source: https://github.com/mz-automation/libiec61850/blob/v1.6/pyiec61850/README.md Install the minimum required packages for compiling libiec61850 and its Python wrapper on Ubuntu systems. ```sh sudo apt-get update sudo apt-get install g++ cmake swig git python3 python3-all-dev ``` -------------------------------- ### Install Development Packages on Alpine Source: https://github.com/mz-automation/libiec61850/blob/v1.6/pyiec61850/README.md Install the minimum required packages for compiling libIEC61850 and its Python wrapper on Alpine Linux. ```sh apk update apk add git g++ swig make cmake python3 python3-dev linux-headers ``` -------------------------------- ### Configure CMake for server_example_service_tracking Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_service_tracking/CMakeLists.txt Defines source files and build targets for the server example, including conditional handling for MSVC compilers. ```cmake include_directories( . ) set(server_example_SRCS server_example_service_tracking.c static_model.c ) IF(MSVC) set_source_files_properties(${server_example_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_service_tracking ${server_example_SRCS} ) target_link_libraries(server_example_service_tracking iec61850 ) ``` -------------------------------- ### Configure CMake for server_example_password_auth Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_password_auth/CMakeLists.txt Defines the build target for the password authentication server example, including source file properties and library linking. ```cmake include_directories( . ) set(server_example_SRCS server_example_password_auth.c static_model.c ) IF(MSVC) set_source_files_properties(${server_example_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_password_auth ${server_example_SRCS} ) target_link_libraries(server_example_password_auth iec61850 ) ``` -------------------------------- ### CMake Build Configuration for IEC 61850 Server Example Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_config_file/CMakeLists.txt This CMake script configures the build for the IEC 61850 server example. It specifies include directories, source files, and links the 'iec61850' library. Conditional compilation for MSVC is included. ```cmake include_directories( .) set(server_example_config_file_SRCS server_example_config_file.c ) IF(MSVC) set_source_files_properties(${server_example_config_file_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_config_file ${server_example_config_file_SRCS} ) target_link_libraries(server_example_config_file iec61850 ) ``` -------------------------------- ### Initialize and Start an IEC 61850 Server Source: https://context7.com/mz-automation/libiec61850/llms.txt Demonstrates creating a server instance with specific configuration parameters, including report buffer sizes, edition compliance, and service enablement. The server must be explicitly stopped and destroyed to ensure proper resource cleanup. ```c #include "iec61850_server.h" #include "hal_thread.h" #include #include #include #include "static_model.h" static int running = 0; static IedServer iedServer = NULL; void sigint_handler(int signalId) { running = 0; } int main(int argc, char** argv) { int tcpPort = 102; printf("Using libIEC61850 version %s\n", LibIEC61850_getVersionString()); /* Create new server configuration object */ IedServerConfig config = IedServerConfig_create(); /* Set buffer size for buffered report control blocks */ IedServerConfig_setReportBufferSize(config, 200000); /* Set stack compliance to IEC 61850 edition 2 */ IedServerConfig_setEdition(config, IEC_61850_EDITION_2); /* Configure file service base path */ IedServerConfig_setFileServiceBasePath(config, "./vmd-filestore/"); /* Enable/disable various services */ IedServerConfig_enableFileService(config, false); IedServerConfig_enableDynamicDataSetService(config, true); IedServerConfig_enableLogService(config, false); /* Set maximum number of client connections */ IedServerConfig_setMaxMmsConnections(config, 5); /* Create IEC 61850 server with configuration */ iedServer = IedServer_createWithConfig(&iedModel, NULL, config); /* Configuration object no longer needed */ IedServerConfig_destroy(config); /* Set server identity for MMS identify service */ IedServer_setServerIdentity(iedServer, "Vendor", "Model", "1.0.0"); /* Start server listening on specified TCP port */ IedServer_start(iedServer, tcpPort); if (!IedServer_isRunning(iedServer)) { printf("Starting server failed!\n"); IedServer_destroy(iedServer); exit(-1); } running = 1; signal(SIGINT, sigint_handler); while (running) { Thread_sleep(100); } /* Stop and cleanup */ IedServer_stop(iedServer); IedServer_destroy(iedServer); return 0; } ``` -------------------------------- ### Configure Executable Target with Source Files Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_files/CMakeLists.txt Defines an executable target named 'server_example_files' and links it with the 'iec61850' library. Ensure the 'iec61850' library is correctly installed or available in the build environment. ```cmake include_directories( .) set(server_example_SRCS server_example_files.c static_model.c ) IF(MSVC) set_source_files_properties(${server_example_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_files ${server_example_SRCS} ) target_link_libraries(server_example_files iec61850 ) ``` -------------------------------- ### Build libiec61850 on Linux using CMake Source: https://github.com/mz-automation/libiec61850/blob/v1.6/README.md Builds the library on Linux using CMake. Requires build tools and CMake to be installed. Optionally installs the library and header files to system directories. ```bash mkdir build cd build cmake .. make ``` ```bash sudo make install ``` -------------------------------- ### Configure IedServer Access Control Policies Source: https://context7.com/mz-automation/libiec61850/llms.txt Demonstrates setting default access policies for functional constraints and installing custom write access handlers for specific data attributes. ```c #include "iec61850_server.h" #include /* Write access handler callback */ static MmsDataAccessError writeAccessHandler(DataAttribute* dataAttribute, MmsValue* value, ClientConnection connection, void* parameter) { const char* clientAddr = ClientConnection_getPeerAddress(connection); printf("Write access from %s\n", clientAddr); /* Allow write only from specific client */ if (strcmp(clientAddr, "192.168.1.100") == 0) { return DATA_ACCESS_ERROR_SUCCESS; } /* Deny access from other clients */ return DATA_ACCESS_ERROR_OBJECT_ACCESS_DENIED; } /* Connection indication handler */ static void connectionHandler(IedServer self, ClientConnection connection, bool connected, void* parameter) { if (connected) printf("Client connected: %s\n", ClientConnection_getPeerAddress(connection)); else printf("Client disconnected: %s\n", ClientConnection_getPeerAddress(connection)); } void setupAccessControl(IedServer server) { /* Set connection indication handler */ IedServer_setConnectionIndicationHandler(server, connectionHandler, NULL); /* Allow write access for DC (description) functional constraint by default */ IedServer_setWriteAccessPolicy(server, IEC61850_FC_DC, ACCESS_POLICY_ALLOW); /* Deny write access for CF (configuration) by default */ IedServer_setWriteAccessPolicy(server, IEC61850_FC_CF, ACCESS_POLICY_DENY); /* Install custom write access handler for specific data attributes */ IedServer_handleWriteAccess(server, IEDMODEL_GenericIO_GGIO1_NamPlt_vendor, writeAccessHandler, NULL); /* Install handler for all attributes of a complex data attribute */ IedServer_handleWriteAccessForComplexAttribute(server, IEDMODEL_GenericIO_GGIO1_AnIn1_mag, writeAccessHandler, NULL); } ``` -------------------------------- ### Configure IEC 61850 Client Executable in CMake Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/iec61850_client_example2/CMakeLists.txt Defines the source files and build dependencies for the client example. Includes a conditional check to set the language to CXX when using MSVC. ```cmake set(iec61850_client_example2_SRCS client_example2.c ) IF(MSVC) set_source_files_properties(${iec61850_client_example2_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(iec61850_client_example2 ${iec61850_client_example2_SRCS} ) target_link_libraries(iec61850_client_example2 iec61850 ) ``` -------------------------------- ### Configure SQLite Logging Driver Build Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_logging/CMakeLists.txt This CMake script configures the build process to include the SQLite logging driver for the server example. It checks for the presence of SQLite headers and includes the necessary source files and compiler flags. Use this when building the server example with SQLite support. ```cmake if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/../../third_party/sqlite/sqlite3.h") message("Found sqlite source code -> compile sqlite-log driver with static sqlite library") include_directories( . ${CMAKE_SOURCE_DIR}/third_party/sqlite ) set(server_example_SRCS server_example_logging.c static_model.c ${CMAKE_CURRENT_LIST_DIR}/../../src/logging/drivers/sqlite/log_storage_sqlite.c ) set(sqlite_SRCS ${CMAKE_CURRENT_LIST_DIR}/../../third_party/sqlite/sqlite3.c ) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION") IF(MSVC) set_source_files_properties(${server_example_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_logging ${server_example_SRCS} ${sqlite_SRCS} ) target_link_libraries(server_example_logging iec61850 ) ELSE() message("server-example-logging: sqlite not found") ENDIF() ``` -------------------------------- ### Build Python Bindings with CMake Source: https://github.com/mz-automation/libiec61850/blob/v1.6/pyiec61850/README.md Build the Python bindings for libIEC61850 by enabling the BUILD_PYTHON_BINDINGS flag in CMake and then compiling and installing the library. ```sh mkdir build && cd build cmake -DBUILD_PYTHON_BINDINGS=ON .. make sudo make install ``` -------------------------------- ### IedServer_handleWriteAccess Source: https://context7.com/mz-automation/libiec61850/llms.txt Installs a custom write access handler callback for a specific data attribute. ```APIDOC ## IedServer_handleWriteAccess ### Description Installs a custom write access handler for specific data attributes to allow or deny write operations based on custom logic. ### Method C Function ### Parameters - **server** (IedServer) - Required - The IedServer instance. - **dataAttribute** (DataAttribute*) - Required - The specific data attribute to monitor. - **handler** (MmsDataAccessError) - Required - The callback function to execute when a write is attempted. - **parameter** (void*) - Optional - User-defined parameter passed to the handler. ``` -------------------------------- ### Create and Publish GOOSE Messages Source: https://context7.com/mz-automation/libiec61850/llms.txt Use this snippet to create a GOOSE publisher, configure its parameters, and send real-time event messages. Ensure you have root permissions for network interface access. The example publishes 10 messages with a 1-second delay between each. ```c #include "goose_publisher.h" #include "mms_value.h" #include "hal_thread.h" #include int main(int argc, char** argv) { char* interface = "eth0"; if (argc > 1) interface = argv[1]; printf("Using interface %s\n", interface); /* Create data set with values to publish */ LinkedList dataSetValues = LinkedList_create(); LinkedList_add(dataSetValues, MmsValue_newIntegerFromInt32(1234)); LinkedList_add(dataSetValues, MmsValue_newBinaryTime(false)); LinkedList_add(dataSetValues, MmsValue_newIntegerFromInt32(5678)); LinkedList_add(dataSetValues, MmsValue_newBoolean(false)); /* Configure GOOSE communication parameters */ CommParameters gooseCommParameters; gooseCommParameters.appId = 1000; gooseCommParameters.dstAddress[0] = 0x01; gooseCommParameters.dstAddress[1] = 0x0c; gooseCommParameters.dstAddress[2] = 0xcd; gooseCommParameters.dstAddress[3] = 0x01; gooseCommParameters.dstAddress[4] = 0x00; gooseCommParameters.dstAddress[5] = 0x01; gooseCommParameters.vlanId = 0; gooseCommParameters.vlanPriority = 4; /* Create GOOSE publisher */ GoosePublisher publisher = GoosePublisher_create(&gooseCommParameters, interface); if (publisher) { /* Configure publisher */ GoosePublisher_setGoCbRef(publisher, "simpleIOGenericIO/LLN0$GO$gcbAnalogValues"); GoosePublisher_setConfRev(publisher, 1); GoosePublisher_setDataSetRef(publisher, "simpleIOGenericIO/LLN0$AnalogValues"); GoosePublisher_setTimeAllowedToLive(publisher, 500); /* Publish messages */ int i; for (i = 0; i < 10; i++) { if (GoosePublisher_publish(publisher, dataSetValues) == -1) { printf("Error sending GOOSE message!\n"); } else { printf("GOOSE message sent (stNum=%llu)\n", (unsigned long long)GoosePublisher_increaseStNum(publisher)); } Thread_sleep(1000); } GoosePublisher_destroy(publisher); } else { printf("Failed to create GOOSE publisher (root permissions required)\n"); } /* Cleanup data set values */ LinkedList_destroyDeep(dataSetValues, (LinkedListValueDeleteFunction) MmsValue_delete); return 0; } ``` -------------------------------- ### CMake Build Configuration for Python Bindings Source: https://github.com/mz-automation/libiec61850/blob/v1.6/pyiec61850/CMakeLists.txt Configures the build environment to generate Python bindings for libiec61850. Requires SWIG and Python development headers to be installed on the system. ```cmake cmake_minimum_required(VERSION 3.12) cmake_policy(SET CMP0078 NEW) if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.14.0") cmake_policy(SET CMP0086 NEW) endif() find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) find_package(Python COMPONENTS Interpreter Development REQUIRED) include_directories(${Python_INCLUDE_DIRS}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set(CMAKE_SWIG_FLAGS "") set_property(SOURCE iec61850.i PROPERTY CPLUSPLUS ON) set_property(SOURCE iec61850.i PROPERTY SWIG_MODULE_NAME pyiec61850) if(WIN32) set(LIBS iec61850 ws2_32) else() set(LIBS iec61850-shared) endif() swig_add_library(pyiec61850 LANGUAGE python SOURCES iec61850.i ) swig_link_libraries(pyiec61850 ${LIBS}) # Finding python modules install path execute_process( COMMAND ${Python_EXECUTABLE} -c "from sysconfig import get_path; import sys; sys.stdout.write(get_path('platlib'))" OUTPUT_VARIABLE PYTHON_SITE_DIR ) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/pyiec61850.py DESTINATION ${PYTHON_SITE_DIR}) install(TARGETS pyiec61850 LIBRARY DESTINATION ${PYTHON_SITE_DIR}) add_test(test_pyiec61850 ${Python_EXECUTABLE} ${CMAKE_CURRENT_LIST_DIR}/test_pyiec61850.py) ``` -------------------------------- ### Import pyiec61850 Library Source: https://github.com/mz-automation/libiec61850/blob/v1.6/pyiec61850/README.md Import the pyiec61850 library in your Python script to start using its functionalities. ```python import pyiec61850 as iec61850 ``` -------------------------------- ### IedServer_setControlHandler Source: https://context7.com/mz-automation/libiec61850/llms.txt Installs a callback handler for control operations on controllable data objects, supporting direct control and select-before-operate models. ```APIDOC ## IedServer_setControlHandler ### Description Installs a callback handler for control operations on controllable data objects. Supports all IEC 61850 control models including direct control and select-before-operate. ### Parameters - **server** (IedServer) - Required - The server instance. - **dataObject** (DataObject*) - Required - The controllable data object to attach the handler to. - **handler** (ControlHandler) - Required - The callback function to execute. - **parameter** (void*) - Required - User-defined parameter passed to the handler. ``` -------------------------------- ### Install Control Handlers in C Source: https://context7.com/mz-automation/libiec61850/llms.txt Registers a callback function to handle control operations for data objects. The handler must return a ControlHandlerResult and can be used for both direct and select-before-operate control models. ```c #include "iec61850_server.h" static IedServer iedServer = NULL; /* Control handler callback for binary output operations */ static ControlHandlerResult controlHandlerForBinaryOutput(ControlAction action, void* parameter, MmsValue* value, bool test) { /* Reject test operations */ if (test) return CONTROL_RESULT_FAILED; /* Verify value type is boolean */ if (MmsValue_getType(value) != MMS_BOOLEAN) return CONTROL_RESULT_FAILED; printf("Received control command: %s\n", MmsValue_getBoolean(value) ? "ON" : "OFF"); /* Get current timestamp */ uint64_t timeStamp = Hal_getTimeInMs(); /* Update data model based on which control object was operated */ DataObject* ctlObject = (DataObject*) parameter; if (ctlObject == IEDMODEL_GenericIO_GGIO1_SPCSO1) { IedServer_updateUTCTimeAttributeValue(iedServer, IEDMODEL_GenericIO_GGIO1_SPCSO1_t, timeStamp); IedServer_updateAttributeValue(iedServer, IEDMODEL_GenericIO_GGIO1_SPCSO1_stVal, value); } else if (ctlObject == IEDMODEL_GenericIO_GGIO1_SPCSO2) { IedServer_updateUTCTimeAttributeValue(iedServer, IEDMODEL_GenericIO_GGIO1_SPCSO2_t, timeStamp); IedServer_updateAttributeValue(iedServer, IEDMODEL_GenericIO_GGIO1_SPCSO2_stVal, value); } return CONTROL_RESULT_OK; } /* Setup control handlers */ void setupControlHandlers(IedServer server) { iedServer = server; /* Install handler for direct control (control model 1) */ IedServer_setControlHandler(server, IEDMODEL_GenericIO_GGIO1_SPCSO1, (ControlHandler) controlHandlerForBinaryOutput, IEDMODEL_GenericIO_GGIO1_SPCSO1); /* Install handler for SBO control (control model 2) */ IedServer_setControlHandler(server, IEDMODEL_GenericIO_GGIO1_SPCSO2, (ControlHandler) controlHandlerForBinaryOutput, IEDMODEL_GenericIO_GGIO1_SPCSO2); } ``` -------------------------------- ### Configure Makefiles with CMake Source: https://github.com/mz-automation/libiec61850/blob/v1.6/src/doxygen/mainpage_net.md Configure and create makefiles for building the native IEC 61850 library. This command should be run from within the 'build' directory. ```bash cd build cmake .. ``` -------------------------------- ### Create and Configure SV Receiver and Subscriber Source: https://context7.com/mz-automation/libiec61850/llms.txt Demonstrates initializing an SV receiver, binding it to an Ethernet interface, and attaching a subscriber with a callback listener to process incoming ASDU data. ```c #include "sv_subscriber.h" #include "hal_thread.h" #include #include static bool running = true; void sigint_handler(int signalId) { running = 0; } /* SV update callback - called for each received ASDU */ static void svUpdateListener(SVSubscriber subscriber, void* parameter, SVSubscriber_ASDU asdu) { printf("SV message received:\n"); /* Get SV ID string */ const char* svID = SVSubscriber_ASDU_getSvId(asdu); if (svID != NULL) printf(" svID: %s\n", svID); /* Get sample counter and configuration revision */ printf(" smpCnt: %d\n", SVSubscriber_ASDU_getSmpCnt(asdu)); printf(" confRev: %u\n", SVSubscriber_ASDU_getConfRev(asdu)); /* Check sample synchronization */ uint8_t smpSynch = SVSubscriber_ASDU_getSmpSynch(asdu); printf(" smpSynch: %d\n", smpSynch); /* Access data values - requires knowledge of data set structure * This example assumes FLOAT32 values at known byte offsets */ int dataSize = SVSubscriber_ASDU_getDataSize(asdu); printf(" dataSize: %d bytes\n", dataSize); if (dataSize >= 8) { /* Read two FLOAT32 values (4 bytes each) */ float value1 = SVSubscriber_ASDU_getFLOAT32(asdu, 0); float value2 = SVSubscriber_ASDU_getFLOAT32(asdu, 4); printf(" DATA[0]: %f\n", value1); printf(" DATA[1]: %f\n", value2); } if (dataSize >= 16) { /* Read additional INT32 values */ int32_t iValue1 = SVSubscriber_ASDU_getINT32(asdu, 8); int32_t iValue2 = SVSubscriber_ASDU_getINT32(asdu, 12); printf(" DATA[2]: %d\n", iValue1); printf(" DATA[3]: %d\n", iValue2); } /* Get timestamp if available */ if (SVSubscriber_ASDU_hasRefrTm(asdu)) { uint64_t timestamp = SVSubscriber_ASDU_getRefrTmAsMs(asdu); printf(" refrTm: %llu ms\n", (unsigned long long)timestamp); } } int main(int argc, char** argv) { /* Create SV receiver */ SVReceiver receiver = SVReceiver_create(); /* Set Ethernet interface */ if (argc > 1) { SVReceiver_setInterfaceId(receiver, argv[1]); printf("Using interface: %s\n", argv[1]); } else { SVReceiver_setInterfaceId(receiver, "eth0"); } /* Create subscriber for specific APPID (0x4000) */ SVSubscriber subscriber = SVSubscriber_create(NULL, 0x4000); /* Install callback handler */ SVSubscriber_setListener(subscriber, svUpdateListener, NULL); /* Connect subscriber to receiver */ SVReceiver_addSubscriber(receiver, subscriber); /* Start receiver (creates background thread) */ SVReceiver_start(receiver); if (SVReceiver_isRunning(receiver)) { signal(SIGINT, sigint_handler); while (running) { Thread_sleep(1); } SVReceiver_stop(receiver); } else { printf("Failed to start SV receiver (root permissions required)\n"); } /* Cleanup */ SVReceiver_destroy(receiver); return 0; } ``` -------------------------------- ### Run mz-automation/libiec61850 Tool Source: https://github.com/mz-automation/libiec61850/blob/v1.6/tools/model_generator_dotnet/README.md Use this command format to run the tool from the command line. Replace placeholders with your specific file and names. The first argument specifies the model type: 1 for Static Model, 2 for Dynamic Model. ```bash dotnet Tools.dll 1 ICDFiles/genericIO.icd -ied simpleIO -ap accessPoint1 -out static_model -modelprefix iedModel ``` -------------------------------- ### Configure r_goose_subscriber_example in CMake Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/r_goose_receiver_example/CMakeLists.txt Defines the source files, sets CXX language properties for MSVC, and links the iec61850 library. ```cmake set(r_goose_subscriber_example_SRCS r_goose_subscriber_example.c ) IF(MSVC) set_source_files_properties(${r_goose_subscriber_example_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(r_goose_subscriber_example ${r_goose_subscriber_example_SRCS} ) target_link_libraries(r_goose_subscriber_example iec61850 ) ``` -------------------------------- ### Build Native Library with Make Source: https://github.com/mz-automation/libiec61850/blob/v1.6/src/doxygen/mainpage_net.md Build the native IEC 61850 library using make. This command is typically run after configuring the build with CMake. ```bash make ``` -------------------------------- ### Create and Connect IEC 61850 Client in C Source: https://context7.com/mz-automation/libiec61850/llms.txt Initializes a client connection, configures timeouts, and performs read/write operations on a server. Ensure resources are cleaned up using IedConnection_destroy after closing the connection. ```c #include "iec61850_client.h" #include #include int main(int argc, char** argv) { char* hostname = "localhost"; int tcpPort = 102; if (argc > 1) hostname = argv[1]; if (argc > 2) tcpPort = atoi(argv[2]); IedClientError error; /* Create new client connection instance */ IedConnection con = IedConnection_create(); /* Optional: bind to local IP address/interface */ /* IedConnection_setLocalAddress(con, "192.168.1.100", -1); */ /* Set connection and request timeouts */ IedConnection_setConnectTimeout(con, 10000); IedConnection_setRequestTimeout(con, 5000); /* Connect to server */ IedConnection_connect(con, &error, hostname, tcpPort); if (error == IED_ERROR_OK) { printf("Connected to %s:%d\n", hostname, tcpPort); /* Read an analog measurement value */ MmsValue* value = IedConnection_readObject(con, &error, "simpleIOGenericIO/GGIO1.AnIn1.mag.f", IEC61850_FC_MX); if (value != NULL) { if (MmsValue_getType(value) == MMS_FLOAT) { float fval = MmsValue_toFloat(value); printf("Read float value: %f\n", fval); } MmsValue_delete(value); } /* Write a variable to the server */ value = MmsValue_newVisibleString("libiec61850.com"); IedConnection_writeObject(con, &error, "simpleIOGenericIO/GGIO1.NamPlt.vendor", IEC61850_FC_DC, value); if (error != IED_ERROR_OK) printf("Write failed! Error: %d\n", error); MmsValue_delete(value); /* Close connection */ IedConnection_close(con); } else { printf("Connection failed! Error: %s\n", IedClientError_toString(error)); } /* Cleanup resources */ IedConnection_destroy(con); return 0; } ``` -------------------------------- ### Implement a GOOSE Subscriber and Receiver in C Source: https://context7.com/mz-automation/libiec61850/llms.txt Demonstrates setting up a GOOSE receiver, configuring network interface and filters, and attaching a listener callback to process incoming GOOSE messages. ```c #include "goose_receiver.h" #include "goose_subscriber.h" #include "hal_thread.h" #include #include static int running = 1; static void sigint_handler(int signalId) { running = 0; } /* GOOSE message callback handler */ static void gooseListener(GooseSubscriber subscriber, void* parameter) { printf("GOOSE event received:\n"); printf(" stNum: %u sqNum: %u\n", GooseSubscriber_getStNum(subscriber), GooseSubscriber_getSqNum(subscriber)); printf(" timeToLive: %u ms\n", GooseSubscriber_getTimeAllowedToLive(subscriber)); uint64_t timestamp = GooseSubscriber_getTimestamp(subscriber); printf(" timestamp: %u.%03u\n", (uint32_t)(timestamp / 1000), (uint32_t)(timestamp % 1000)); printf(" message is %s\n", GooseSubscriber_isValid(subscriber) ? "valid" : "INVALID"); /* Access data set values */ MmsValue* values = GooseSubscriber_getDataSetValues(subscriber); char buffer[1024]; MmsValue_printToBuffer(values, buffer, 1024); printf(" allData: %s\n", buffer); } int main(int argc, char** argv) { /* Create GOOSE receiver */ GooseReceiver receiver = GooseReceiver_create(); /* Set Ethernet interface */ if (argc > 1) { printf("Using interface: %s\n", argv[1]); GooseReceiver_setInterfaceId(receiver, argv[1]); } else { GooseReceiver_setInterfaceId(receiver, "eth0"); } /* Create subscriber for specific GoCB reference */ GooseSubscriber subscriber = GooseSubscriber_create( "simpleIOGenericIO/LLN0$GO$gcbAnalogValues", NULL); /* Set destination MAC address filter */ uint8_t dstMac[6] = {0x01, 0x0c, 0xcd, 0x01, 0x00, 0x01}; GooseSubscriber_setDstMac(subscriber, dstMac); /* Set APPID filter */ GooseSubscriber_setAppId(subscriber, 1000); /* Install callback handler */ GooseSubscriber_setListener(subscriber, gooseListener, NULL); /* Add subscriber to receiver */ GooseReceiver_addSubscriber(receiver, subscriber); /* Start receiving GOOSE messages (creates background thread) */ GooseReceiver_start(receiver); if (GooseReceiver_isRunning(receiver)) { signal(SIGINT, sigint_handler); while (running) { Thread_sleep(100); } } else { printf("Failed to start GOOSE receiver (root permissions required)\n"); } /* Cleanup */ GooseReceiver_stop(receiver); GooseReceiver_destroy(receiver); return 0; } ``` -------------------------------- ### Configure CMake for server_example_substitution Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_substitution/CMakeLists.txt Defines the executable target and links the necessary iec61850 library. It includes logic to force C++ compilation for source files when using the MSVC compiler. ```cmake include_directories( . ) set(server_example_SRCS server_example_substitution.c static_model.c ) IF(MSVC) set_source_files_properties(${server_example_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_substitution ${server_example_SRCS} ) target_link_libraries(server_example_substitution iec61850 ) ``` -------------------------------- ### Build Library with mbedtls 2.28 TLS Support Source: https://github.com/mz-automation/libiec61850/blob/v1.6/README.md Compiles the libIEC61850 library with TLS support using mbedtls version 2.28. Ensure the mbedtls-2.28 folder is present in third_party/mbedtls. ```bash make WITH_MBEDTLS=1 ``` -------------------------------- ### Configure 64-bit Build with Visual Studio Generator Source: https://github.com/mz-automation/libiec61850/blob/v1.6/src/doxygen/mainpage_net.md Configure the build for a 64-bit version of the native library using CMake with the Visual Studio 2015 Win64 generator. Run from the 'build' directory. ```bash cd build cmake -G "Visual Studio 14 2015 Win64" .. ``` -------------------------------- ### Configure 32-bit Build with Visual Studio Generator Source: https://github.com/mz-automation/libiec61850/blob/v1.6/src/doxygen/mainpage_net.md Configure the build for a 32-bit version of the native library using CMake with the Visual Studio 2015 generator. Run from the 'build' directory. ```bash cd build cmake -G "Visual Studio 14 2015" .. ``` -------------------------------- ### Build Library with mbedtls 3.6 TLS Support Source: https://github.com/mz-automation/libiec61850/blob/v1.6/README.md Compiles the libIEC61850 library with TLS support using mbedtls version 3.6. Ensure the mbedtls-3.6.0 folder is present in third_party/mbedtls. ```bash make WITH_MBEDTLS3=1 ``` -------------------------------- ### Configure GOOSE Server Executable in CMake Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_goose/CMakeLists.txt Defines the source files and build dependencies for the server_example_goose executable, including specific handling for MSVC compilers. ```cmake include_directories( . ) set(server_example_goose_SRCS server_example_goose.c static_model.c ) IF(MSVC) set_source_files_properties(${server_example_goose_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_goose ${server_example_goose_SRCS} ) target_link_libraries(server_example_goose iec61850 ) ``` -------------------------------- ### Configure CMake for IEC 61850 Server Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/server_example_61400_25/CMakeLists.txt Defines the executable, source files, and library dependencies for the server_example_61400_25 project. ```cmake include_directories( . ) set(server_example_61400_25_SRCS server_example_61400_25.c static_model.c ) IF(MSVC) set_source_files_properties(${server_example_61400_25_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(server_example_61400_25 ${server_example_61400_25_SRCS} ) target_link_libraries(server_example_61400_25 iec61850 ) ``` -------------------------------- ### Generate Visual Studio Projects with CMake on Windows Source: https://github.com/mz-automation/libiec61850/blob/v1.6/README.md Generates project files for Visual Studio using CMake. Use the '-G' option to specify the generator and optionally 'Win64' for 64-bit builds. The '..' argument points to the CMakeLists.txt file. ```bash cmake -G "Visual Studio 14 2015" .. ``` ```bash cmake -G "Visual Studio 14 2015 Win64" .. ``` ```bash cmake -G "Visual Studio 15 2017 Win64" .. ``` ```bash cmake -G "Visual Studio 16 2019" .. -A x64 ``` -------------------------------- ### Perform IEC 61850 Control Operations in C Source: https://context7.com/mz-automation/libiec61850/llms.txt Demonstrates direct control, select-before-operate, and enhanced security control with command termination handling. ```c #include "iec61850_client.h" #include "hal_thread.h" #include /* Command termination handler for enhanced security control */ static void commandTerminationHandler(void *parameter, ControlObjectClient connection) { LastApplError lastApplError = ControlObjectClient_getLastApplError(connection); if (lastApplError.error != 0) { printf("Received CommandTermination-\n"); printf(" LastApplError: %d\n", lastApplError.error); printf(" addCause: %d\n", lastApplError.addCause); } else { printf("Received CommandTermination+\n"); } } /* Execute direct control operation */ void executeDirectControl(IedConnection con) { IedClientError error; /* Create control object client */ ControlObjectClient control = ControlObjectClient_create( "simpleIOGenericIO/GGIO1.SPCSO1", con); if (control) { /* Create control value */ MmsValue* ctlVal = MmsValue_newBoolean(true); /* Set originator information */ ControlObjectClient_setOrigin(control, NULL, CONTROL_ORCAT_REMOTE_CONTROL); /* Execute operate command (0 = operate now, not time-activated) */ if (ControlObjectClient_operate(control, ctlVal, 0)) { printf("Control operated successfully\n"); } else { printf("Control operation failed\n"); } MmsValue_delete(ctlVal); ControlObjectClient_destroy(control); /* Verify status changed */ MmsValue* stVal = IedConnection_readObject(con, &error, "simpleIOGenericIO/GGIO1.SPCSO1.stVal", IEC61850_FC_ST); if (error == IED_ERROR_OK) { printf("New status: %d\n", MmsValue_getBoolean(stVal)); MmsValue_delete(stVal); } } } /* Execute select-before-operate control */ void executeSBOControl(IedConnection con) { ControlObjectClient control = ControlObjectClient_create( "simpleIOGenericIO/GGIO1.SPCSO2", con); if (control) { /* Select the control object first */ if (ControlObjectClient_select(control)) { MmsValue* ctlVal = MmsValue_newBoolean(true); /* Operate after successful select */ if (ControlObjectClient_operate(control, ctlVal, 0)) { printf("SBO control operated successfully\n"); } else { printf("SBO operate failed\n"); } MmsValue_delete(ctlVal); } else { printf("Select failed\n"); } ControlObjectClient_destroy(control); } } /* Execute direct control with enhanced security */ void executeEnhancedControl(IedConnection con) { ControlObjectClient control = ControlObjectClient_create( "simpleIOGenericIO/GGIO1.SPCSO3", con); if (control) { /* Install command termination handler */ ControlObjectClient_setCommandTerminationHandler(control, commandTerminationHandler, NULL); MmsValue* ctlVal = MmsValue_newBoolean(true); if (ControlObjectClient_operate(control, ctlVal, 0)) { printf("Enhanced control operated successfully\n"); } MmsValue_delete(ctlVal); /* Wait for command termination message */ Thread_sleep(1000); ControlObjectClient_destroy(control); } } ``` -------------------------------- ### IedServer_create Source: https://context7.com/mz-automation/libiec61850/llms.txt Creates and initializes a new IEC 61850 server instance from a data model definition. The server handles client connections, data model access, reporting, GOOSE publishing, and control operations. ```APIDOC ## IedServer_create ### Description Creates and initializes a new IEC 61850 server instance from a data model definition. The server handles client connections, data model access, reporting, GOOSE publishing, and control operations. ### Method (Implicitly a constructor/initializer, not a direct HTTP method) ### Endpoint (Not applicable, this is a library function) ### Parameters (No explicit parameters listed in the provided text for the creation function itself, but it uses `iedModel` and `config` which are defined elsewhere in the example.) ### Request Example (Not applicable, this is a library function) ### Response (Returns an `IedServer` instance) #### Success Response (200) (Not applicable) #### Response Example (Not applicable) ``` -------------------------------- ### Iterate Over Logical Devices Source: https://github.com/mz-automation/libiec61850/blob/v1.6/pyiec61850/README.md Retrieve a list of logical devices from an IED connection and iterate through them. Remember to destroy the linked list when done. ```python [deviceList, error] = iec61850.IedConnection_getLogicalDeviceList(con) device = iec61850.LinkedList_getNext(deviceList) while device: print("LD: %s" % iec61850.toCharP(device.data)) [logicalNodes, error] = iec61850.IedConnection_getLogicalDeviceDirectory( con, iec61850.toCharP(device.data)) device = iec61850.LinkedList_getNext(device) iec61850.LinkedList_destroy(deviceList) ``` -------------------------------- ### Set Source Files for file-tool Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/iec61850_client_example_files/CMakeLists.txt Defines the source files for the 'file-tool' executable. This is typically used in build systems like CMake. ```cmake set(iec61850_client_example_files_SRCS file-tool.c ) ``` -------------------------------- ### Create and Connect IED Connection Source: https://github.com/mz-automation/libiec61850/blob/v1.6/pyiec61850/README.md Create an IED connection object and establish a connection to an IED server. Ensure to check the error code for successful connection. ```python con = iec61850.IedConnection_create() error = iec61850.IedConnection_connect(con, "localhost", 102) if (error == iec61850.IED_ERROR_OK): # Do some work iec61850.IedConnection_close(con) iec61850.IedConnection_destroy(con) ``` -------------------------------- ### Link Target Libraries Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/iec61850_client_example_files/CMakeLists.txt Links the 'file-tool' executable against the 'iec61850' library. This ensures that the executable can use functions and symbols from the 'iec61850' library. ```cmake target_link_libraries(file-tool iec61850 ) ``` -------------------------------- ### IedConnection_create and IedConnection_connect Source: https://context7.com/mz-automation/libiec61850/llms.txt Functions to create and establish a connection from an IEC 61850 client to a server. ```APIDOC ## IedConnection_create ### Description Creates a new client connection instance. ## IedConnection_connect ### Description Connects the client to the specified server. ### Parameters - **con** (IedConnection) - Required - The connection instance. - **error** (IedClientError*) - Required - Pointer to store the connection error status. - **hostname** (char*) - Required - The server hostname or IP address. - **tcpPort** (int) - Required - The TCP port number. ``` -------------------------------- ### Configure CMake for GOOSE Publisher Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/r_goose_publisher_example/CMakeLists.txt Defines the executable target and links the required iec61850 library. Includes conditional logic to set the source language to CXX when using MSVC. ```cmake set(r_goose_publisher_example_SRCS r_goose_publisher_example.c ) IF(MSVC) set_source_files_properties(${r_goose_publisher_example_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) add_executable(r_goose_publisher_example ${r_goose_publisher_example_SRCS} ) target_link_libraries(r_goose_publisher_example iec61850 ) ``` -------------------------------- ### Add Executable Target Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/iec61850_client_example_files/CMakeLists.txt Adds an executable target named 'file-tool' using the specified source files. This is a common build system command. ```cmake add_executable(file-tool ${iec61850_client_example_files_SRCS} ) ``` -------------------------------- ### Set Source Files Properties for MSVC Source: https://github.com/mz-automation/libiec61850/blob/v1.6/examples/iec61850_client_example_files/CMakeLists.txt Configures source files for the Microsoft Visual C++ (MSVC) compiler. It explicitly sets the language to CXX. ```cmake IF(MSVC) set_source_files_properties(${iec61850_client_example_files_SRCS} PROPERTIES LANGUAGE CXX) ENDIF(MSVC) ```