Method and system for synchronizing data of EtherCAT control layer and service layer based on shared memory
By employing a dynamic creation and partitioning design of a shared memory layer between the EtherCAT control layer and service layer, combined with zero-copy writing, timestamp verification, and mutex locks, the latency and compatibility issues of data synchronization between the EtherCAT control layer and service layer are resolved, achieving efficient and reliable data synchronization and meeting the real-time data interaction needs of industrial automation equipment.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-19
- Publication Date
- 2026-03-10
AI Technical Summary
Existing EtherCAT control and service layer data synchronization solutions based on shared memory are difficult to fully adapt to the high reliability and high adaptability requirements of industrial scenarios. Traditional methods suffer from high data transmission latency, limited adaptability, and data consistency issues.
The EtherCAT control and service layers are synchronized using a shared memory-based method. The shared memory layer is dynamically created and divided into a system status area, a slave status area, a PDO data area, and a configuration information area. Zero-copy writing is performed using memory mapping, and data integrity and reliability are ensured by combining timestamp verification, CRC verification, and mutex locks.
It achieves low-latency, high-reliability, and dynamically adaptable real-time data synchronization between the control layer and the service layer, meeting the needs of real-time data interaction and flexible system configuration in industrial automation scenarios.
Smart Images

Figure CN121644594A_ABST
Abstract
Description
TECHNICAL FIELD
[0001] The present application relates to the technical field of industrial automation control, and in particular to an EtherCAT control layer and service layer data synchronization method and system based on shared memory. BACKGROUND
[0002] In the field of industrial automation, EtherCAT, as a kind of efficient real-time Ethernet technology, is widely used in robot control, numerical control machine tool, intelligent production line and other scenes. In the modern EtherCAT real-time control system based on Web technology, a hierarchical architecture design is usually adopted, including a display layer (Web interface), a service layer (business logic, non-real-time) and a control layer (EtherCAT communication, real-time motion control). The control layer runs on a real-time operating system (such as RT-PREEMPT Linux), which requires high-precision deterministic response; while the service layer runs in a non-real-time environment, responsible for processing user requests and business logic. Efficient and reliable data synchronization between the two layers is the key to the performance of the entire system.
[0003] However, the existing EtherCAT control layer and service layer data synchronization scheme based on shared memory has the following problems, which is difficult to fully adapt to the high reliability and high adaptation requirements of industrial scenarios. In the prior art, the data synchronization between the EtherCAT control layer and the service layer is mostly achieved by Socket communication, special protocol (such as ADS protocol) or database middleware. Socket communication needs to be processed by the operating system kernel protocol stack, so the data transmission delay is high; the special protocol has limited adaptability, and it is difficult to be compatible with EtherCAT devices of different manufacturers or service layer systems of different architectures; the database middleware needs to go through multiple links of data writing-storage-reading, which not only increases the delay, but also may cause data consistency problems due to data caching or concurrent access. SUMMARY
[0004] The main purpose of the present application is to provide an EtherCAT control layer and service layer data synchronization method and system based on shared memory, which aims to solve the technical problems proposed in the background technology.
[0005] The present application provides an EtherCAT control layer and service layer data synchronization method based on shared memory, comprising: According to the EtherCAT network configuration and the number of slave stations, a shared memory layer is dynamically created, which is divided into a system state area, a slave station state area, a PDO data area and a configuration information area. The control layer interface module reads PDO data of the slave station and state data of the slave station from the EtherCAT master station in each control cycle through a real-time thread, and writes the PDO data of the slave station and the state data of the slave station directly into a PDO data area and a slave state area in the shared memory layer through memory mapping for zero-copy writing, while updating a timestamp and a synchronization flag of the system state area; The service layer interface module reads device data in the PDO data area and the slave state area in the shared memory layer through memory mapping, converts the binary device data into JSON format for use by the service layer, and establishes a local cache to reduce shared memory access frequency, wherein the device data includes PDO data of the slave station and state data of the slave station; The service layer interface module calculates a difference between a device data reading time and the timestamp of the system state area in the shared memory layer, and if the difference exceeds a preset synchronization threshold, determines that the device data is expired, triggers re-reading, and verifies data integrity through CRC checking; When writing configuration parameters into the configuration information area of the shared memory layer, the service layer interface module uses a mutex to ensure atomic writing, and verifies whether writing is successful by reading an acknowledgment flag of the system state area, and if not, retries until a maximum number of retries.
[0006] Preferably, the step of dynamically creating the shared memory layer according to the EtherCAT network configuration and the number of slave stations comprises: calculating a total capacity of the shared memory layer according to the number of EtherCAT slave stations and data types; calling a shared memory interface provided by an operating system to create a physical carrier of the shared memory layer, and setting access permissions to be readable and writable for the control layer and the service layer; configuring an internal structure of the shared memory layer according to a preset partition layout, and dividing an address space in an order of a system state area, a slave state area, a PDO data area, and a configuration information area; mapping the shared memory layer to an address space of the control layer and the service layer to establish a direct access channel; initializing initial state values of the system state area, the slave state area, the PDO data area, and the configuration information area in the shared memory layer, including setting a synchronization flag of the system state area to an unsynchronized state.
[0007] Preferably, the control layer interface module reads PDO data of the slave station and state data of the slave station from the EtherCAT master station in each control cycle through a real-time thread, and writes the PDO data of the slave station and the state data of the slave station into the PDO data area and the slave station state area of the shared memory layer through memory mapping for zero-copy writing, while updating the time stamp and synchronization flag of the system state area, and the step of updating the time stamp and synchronization flag of the system state area in the shared memory layer comprises: configuring a real-time execution environment of the control layer interface module, including setting a real-time scheduling strategy and processor binding; acquiring PDO data of the slave station through the EtherCAT communication protocol at the beginning of each control cycle, the PDO data including input PDO data and output PDO data; acquiring state data of the slave station through an EtherCAT master station interface function, the state data of the slave station including at least an online state of the slave station and an AL state code; writing the PDO data into the PDO data area of the shared memory layer through memory mapping, while writing the state data of the slave station into the slave station state area of the shared memory layer, and updating device state information in the slave station state area of the shared memory layer; updating a data time stamp and a synchronization state identifier in the system state area of the shared memory layer.
[0008] Preferably, the service layer interface module reads device data in the PDO data area and the slave station state area of the shared memory layer through memory mapping, and converts the binary device data into a JSON format for use by the service layer, while establishing a local cache to reduce shared memory access frequency, and the step of establishing a memory mapping connection between the service layer interface module and the shared memory layer comprises: establishing a memory mapping connection between the service layer interface module and the shared memory layer; acquiring device data from the PDO data area and the slave station state area of the shared memory layer according to a preset reading strategy; analyzing and processing the device data to convert it into an internal data structure; converting the analyzed device data into a structured data format suitable for the service layer; providing the processed device data to the service layer application through a data interface, and updating the local cache.
[0009] Preferably, the service layer interface module calculates the difference between the device data reading time and the time stamp of the system state area in the shared memory layer according to the time stamp, and if the difference exceeds a preset synchronization threshold, it is determined that the device data is expired, triggering re-reading, and verifying data integrity through CRC checking, and the step of verifying data integrity through CRC checking comprises: acquiring a data update time stamp from the system state area of the shared memory layer; acquiring a device data reading time, calculating a difference between the device data reading time and the timestamp; comparing the difference with a preset synchronization threshold to determine data timeliness; when the difference exceeds the synchronization threshold, determining that the device data is expired, and triggering a process of re-reading the device data; performing integrity verification on the read device data through CRC checking, recording synchronization abnormal conditions and triggering an alarm mechanism.
[0010] Preferably, when the service layer interface module writes configuration parameters to the configuration information area of the shared memory layer, a mutex is used to ensure atomic writing, and whether the writing is successful is verified by reading the confirmation flag of the system state area, and if it fails, the step of retrying until the maximum number of retries includes: receiving configuration parameters sent by a service layer application, and performing parameter validity verification; acquiring a mutex of the shared memory layer to ensure atomicity of writing of the configuration parameters; writing the verified configuration parameters to the configuration information area of the shared memory layer; updating the configuration version identifier and the verification information; releasing the mutex and reading the confirmation flag of the system state area, if the confirmation flag is 1, it is determined that the writing is successful, and if it fails, it is retried until the maximum number of retries.
[0011] The application also provides an EtherCAT control layer and service layer data synchronization system based on shared memory, comprising: a shared memory layer module, configured to dynamically create a shared memory layer according to EtherCAT network configuration and the number of slaves, and the shared memory layer is divided into a system state area, a slave state area, a PDO data area and a configuration information area; a control layer interface module, configured to let the control layer interface module read PDO data of slaves and state data of slaves from an EtherCAT master station through a real-time thread in each control cycle, and write the PDO data of slaves and the state data of slaves into the PDO data area and the slave state area of the shared memory layer through memory mapping for zero-copy writing, and update a timestamp and a synchronization flag of the system state area; a service layer first module, configured to let a service layer interface module read device data in the PDO data area and the slave state area of the shared memory layer through memory mapping, and convert the binary device data into JSON format for use by the service layer, and establish a local cache to reduce shared memory access frequency, wherein the device data includes PDO data of slaves and state data of slaves; The service layer second module is configured to let the service layer interface module calculate a difference between the device data reading time and a time stamp in the system state area of the shared memory layer, and if the difference exceeds a preset synchronization threshold, determine that the device data is expired, trigger re-reading, and verify data integrity through CRC checking. The service layer third module is configured to let the service layer interface module use a mutex to ensure atomic writing when writing configuration parameters to the configuration information area of the shared memory layer, and verify whether writing is successful by reading the confirmation flag of the system state area, and if not, retry until a maximum number of retries.
[0012] In one embodiment of the application, the control layer interface module comprises: A configuration unit is configured to configure a real-time execution environment of the control layer interface module, including setting a real-time scheduling strategy and processor binding. A data acquisition unit is configured to acquire PDO data of a slave station through an EtherCAT communication protocol at the beginning of each control cycle, wherein the PDO data includes input PDO data and output PDO data. A state monitoring unit is configured to acquire state data of the slave station through an EtherCAT master station interface function, wherein the state data of the slave station at least includes an online state and an AL state code of the slave station. A data writing and state updating unit is configured to directly write the PDO data to a PDO data area of the shared memory layer through memory mapping, and write the state data of the slave station to a slave station state area of the shared memory layer, and update device state information in the slave station state area of the shared memory layer. A synchronization updating unit is configured to update a data time stamp and a synchronization state identifier in a system state area of the shared memory layer.
[0013] The application further provides a computer device comprising a memory and a processor, wherein the memory stores a computer program, and the processor implements the steps of the EtherCAT control layer and service layer data synchronization method based on shared memory when executing the computer program.
[0014] The application further provides a computer readable storage medium storing a computer program, wherein the computer program implements the steps of the EtherCAT control layer and service layer data synchronization method based on shared memory when executed by a processor.
[0015] The application has the advantages that: the application takes a shared memory layer as a core carrier, dynamically creates an adaptive memory space, performs zero-copy data transmission, performs layered checking and atomic configuration issuing, eliminates the delay of an extra communication link, and guarantees data reliability and system adaptability through structured design. BRIEF DESCRIPTION OF DRAWINGS
[0016] Figure 1 A method flowchart of an embodiment of the application.
[0017] Figure 2 A system structure diagram of an embodiment of the application.
[0018] The application is achieved, and the functions, features and advantages are further described with reference to the embodiments and the accompanying drawings. DETAILED DESCRIPTION
[0019] It should be understood that the specific embodiments described herein are merely intended to explain the application, and are not intended to limit the application.
[0020] As shown in the accompanying drawings, Figure 1 The application provides an EtherCAT control layer and service layer data synchronization method based on a shared memory, which comprises the following steps: S1, dynamically creating a shared memory layer according to an EtherCAT network configuration and the number of slave stations, wherein the shared memory layer is divided into a system state area, a slave station state area, a PDO data area and a configuration information area; S2, a control layer interface module reads the PDO data of the slave stations and the state data of the slave stations from an EtherCAT master station in each control cycle through a real-time thread, and directly writes the PDO data of the slave stations and the state data of the slave stations into the PDO data area and the slave station state area of the shared memory layer through memory mapping, performs zero-copy writing, and updates the time stamp and synchronization flag of the system state area; S3, a service layer interface module reads the device data in the PDO data area and the slave station state area of the shared memory layer through memory mapping, converts the binary device data into a JSON format for use by the service layer, and establishes a local cache to reduce the access frequency of the shared memory, wherein the device data comprises the PDO data of the slave stations and the state data of the slave stations; S4, the service layer interface module calculates the difference between the device data reading time and the time stamp of the system state area in the shared memory layer according to the time stamp, and if the difference exceeds a preset synchronization threshold, it is determined that the device data is expired, re-reading is triggered, and the data integrity is verified through CRC checking; S5, when writing the configuration parameters to the configuration information area of the shared memory layer, the service layer interface module adopts a mutex to ensure atomic writing, and verifies whether the writing is successful by reading the confirmation flag of the system state area, retries if failed, until the maximum number of retries.
[0021] As described in steps S1-S5 above, the application realizes low-latency, high-reliability, and dynamically adaptable real-time data synchronization between the EtherCAT control layer and the service layer through dynamic creation of the shared memory layer, control layer data writing, service layer data reading, and synchronization verification-configuration delivery, meeting the needs of real-time interaction of device data and flexible configuration of the system in industrial automation scenarios (such as robot control and numerical control machine tools).
[0022] The EtherCAT control layer undertakes the core responsibilities of real-time data collection and control instruction execution, and the service layer is responsible for data processing, business logic management, and configuration delivery. Both of them need to continuously interact with data to ensure stable operation of the system. However, due to the extremely high real-time requirements of the control layer and the flexibility and compatibility of the service layer in data processing, traditional data interaction methods need to establish additional communication links between the two, which may cause problems such as data transmission delay, insufficient reliability, or poor adaptability. Therefore, the application provides a data synchronization scheme that can balance real-time, reliability, and dynamic adaptability.
[0023] In the prior art, the data synchronization of the EtherCAT control layer and the service layer mostly uses Socket communication, special protocols (such as ADS protocol), or database middleware. These methods have the following common problems: Socket communication needs to be processed by the operating system kernel protocol stack, resulting in high data transmission delay; special protocols have limited adaptability and are difficult to be compatible with EtherCAT devices of different manufacturers or service layer systems of different architectures; database middleware needs to go through multiple links of data writing-storage-reading, which not only increases the delay, but also may cause data consistency problems due to data caching or concurrent access. To solve these problems, the application takes the shared memory layer as the core carrier, dynamically creates an adaptive memory space, performs zero-copy data transmission, and implements layered verification and atomic configuration delivery, thereby constructing a targeted solution that not only eliminates the delay of additional communication links, but also ensures data reliability and system adaptability through structured design.
[0024] Firstly, "according to the EtherCAT network configuration and the number of slaves, a shared memory layer is dynamically created, which is divided into system state area, slave state area, PDO data area and configuration information area", which can provide a direct and adaptive memory interaction carrier for the control layer and the service layer, avoiding the problem of resource waste or data overflow caused by fixed memory space. To realize this scheme, first of all, the EtherCAT network configuration and the number of slaves need to be obtained, wherein the EtherCAT network configuration can be parsed from the network configuration file (such as the slave mapping file in XML format) of the EtherCAT master station, including the slave device type, data interaction protocol version and other information, and the number of slaves can be read in real time through the API function (such as the ecrt_master_get_slave_count function of IGH EtherCAT) provided by the EtherCAT master station, or manually configured by the user according to the actual number of slave devices deployed in the system initialization stage; then, according to these information, a shared memory layer is dynamically created to ensure that the memory space matches the actual number of devices and data types, and the shared memory layer is divided into four functional areas - the system state area is used to store system-level management data such as timestamps and synchronization flags, the slave state area is used to store the online state and AL state code of a single slave device, the PDO data area is used to store the input / output PDO real-time process data of the slave device, and the configuration information area is used to store the configuration parameters issued by the service layer. This partition design can realize classified storage and accurate access of data, avoiding the problem of low reading efficiency or data disorder caused by mixed storage of different types of data, for example, when the number of slaves is 8, the shared memory layer will dynamically allocate the corresponding size of the PDO data area and the slave state area according to the PDO data volume and the state data volume of each slave, neither will the data be unable to be written due to insufficient space, nor will the memory resources be wasted due to redundant space.
[0025] Then, through the "control layer interface module, in each control cycle, reads the PDO data of the slave station and the state data of the slave station from the EtherCAT master station through real-time threads, and writes the PDO data of the slave station and the state data of the slave station directly into the PDO data area and the slave station state area of the shared memory layer through memory mapping, carries out zero-copy writing, and updates the time stamp and synchronization flag of the system state area", this step can realize efficient and non-redundant transmission of real-time data, and guarantee the real-time and accuracy of the control layer data. In terms of technical implementation, the control layer interface module is first configured with a real-time execution environment, usually adopting a SCHED_FIFO real-time scheduling strategy (priority set to 90-95, higher than that of ordinary user threads) and bound to a physical CPU core (such as core 0) to avoid thread scheduling delay affecting data acquisition and writing; in each control cycle (the control cycle can be set according to the requirements of the industrial scene, such as 1ms or 500μs), the PDO data of the slave station (including input PDO data such as position and speed information fed back by the slave station, and output PDO data such as motor drive instructions issued by the control layer) is read from the EtherCAT master station through the EtherCAT communication protocol, and the state data of the slave station (at least including the online state of the slave station, such as online / offline, and AL state code; for example, 0x00 indicates normal operation, and 0x05 indicates initialization fault) is read through the EtherCAT master station interface function; then, through the memory mapping technology, these data are directly written into the corresponding partition of the shared memory layer, without going through the data copying link (i.e. zero-copy writing), which greatly reduces the data transmission delay; for example, the traditional Socket communication needs to copy the data from the user space to the kernel space, and then transmit through the protocol stack, while the memory mapping can make the control layer directly access the physical address of the shared memory, reducing the data writing delay; finally, the time stamp (using a high-precision clock synchronized with the EtherCAT master station) and the synchronization flag (such as 0x00 indicating unsynchronized and 0x01 indicating synchronization completed) of the system state area are updated.
[0026] Then, the service layer interface module reads the device data of the PDO data area and the slave state area in the shared memory layer through memory mapping, converts the binary device data into JSON format for the service layer, and establishes a local cache to reduce the access frequency of the shared memory, wherein the device data includes the PDO data of the slave and the state data of the slave. This step realizes effective reading and adaptive use of the shared memory data by the service layer, optimizes the access performance of the service layer, and avoids affecting the real-time performance of the control layer due to frequent access to the shared memory. In terms of technical implementation, the service layer interface module first establishes a memory mapping connection with the shared memory layer, usually adopts a private mapping mode (MAP_PRIVATE) and only has read permission, to prevent the service layer from modifying data by mistake and affecting the control layer; then, the device data is obtained from the PDO data area and the slave state area of the shared memory layer according to a preset reading strategy (such as the reading period is an integer multiple of the control layer writing period, for example, when the control layer writing period is 1 ms, the service layer reading period is set to 2 ms); since the data in the shared memory is stored in binary form (such as 4-byte integer speed data and 2-byte AL state code), the service layer needs to parse and process it, convert it into an internal data structure (such as converting binary speed data into a floating-point number with a unit of mm / s), and then convert it into a JSON format suitable for the service layer (including slave index, data name, numerical value, timestamp and other fields, to facilitate the service layer to display data (such as a Web monitoring interface) or process business logic (such as fault diagnosis); at the same time, a local cache is established, an LRU (Least Recently Used) eviction strategy is adopted, the cache capacity is set to twice the total amount of shared memory data, and the update period is dynamically set according to the data refresh requirements of the service layer application, for example, when the service layer needs to frequently obtain historical speed data of a slave, the data can be directly read from the local cache without repeated access to the shared memory, which reduces the access pressure of the shared memory and also reduces the data reading delay of the service layer.
[0027] Then, the service layer interface module calculates the difference between the device data reading time and the timestamp in the system state area of the shared memory layer, and if the difference exceeds the preset synchronization threshold, it is determined that the device data is expired, triggering re-reading, and the data integrity is verified by CRC check. This step can guarantee the timeliness and integrity of the data obtained by the service layer, and avoid logical errors caused by data lag or damage. In terms of technical implementation, the service layer interface module first obtains the timestamp of data update from the system state area of the shared memory layer; then obtains the reading time of the current device data (obtained by the service layer system clock, synchronized with the EtherCAT master clock), and calculates the difference between the two; compare the difference with the preset synchronization threshold (the preset synchronization threshold is usually set to 2 times the control period, such as 2ms when the control period is 1ms, which can be adjusted according to the real-time requirements of the system); if the difference does not exceed the threshold, the data is not expired and can be used normally; if the difference exceeds the threshold, it is determined that the data is expired, triggering the re-reading process, and the exponential backoff strategy is used for re-reading, with an initial interval of 50us and a doubling interval for each subsequent interval, with a maximum interval of 1ms, to avoid frequent retries and occupy system resources; at the same time, the data integrity is verified by CRC check, and the CRC check uses CRC32 algorithm, and the check value is stored at the tail of the PDO data area and the slave state area, and is updated synchronously with the data; the service layer calculates the CRC value of the data after reading, and compares it with the stored check value; if they are consistent, the data is complete; if they are not consistent, it is determined that the data is damaged, the synchronization exception situation (such as abnormal time, slave index, error type) is recorded and the alarm mechanism (such as sending alarm information to the operation and maintenance system) is triggered. For example, when 1 byte of data is damaged due to electromagnetic interference during transmission of the PDO data of a slave station, the CRC check can accurately identify the problem and avoid using incorrect data for control logic judgment by the service layer.
[0028] Finally, through the step of "when the service layer interface module writes configuration parameters to the configuration information area of the shared memory layer, it uses a mutex to ensure atomic writing, and verifies whether the writing is successful by reading the confirmation flag of the system state area, retries if it fails, and retries until the maximum number of retries", this step can guarantee the safety and reliability of service layer configuration parameter distribution, and avoid system configuration abnormalities caused by concurrent writing or writing failure. In terms of technical implementation, the service layer interface module first receives the configuration parameters sent by the service layer application (such as slave station control cycle adjustment, PDO mapping update instruction), and performs parameter validity verification (such as verifying whether the control cycle is within the allowed range and whether the PDO mapping conforms to the EtherCAT protocol specification) to prevent illegal parameters from causing device failure; then it acquires the mutex of the shared memory layer to ensure the atomicity of the configuration parameter writing process, i.e., only one thread is allowed to write to the configuration information area at the same time to avoid parameter confusion caused by multi-thread concurrent writing, for example, when the service layer simultaneously issues control cycle adjustment and PDO mapping update configuration parameters, the mutex ensures that the two parameters are written sequentially and does not overlap or overwrite each other; the verified configuration parameters are stored in key-value pair format (each parameter contains parameter ID (2 bytes), data length (1 byte), and data value (variable length)) and written to the configuration information area of the shared memory layer; after writing is completed, the configuration version identifier (such as version number incremented by 1) and the verification information (such as CRC value) are updated to facilitate identification of new configurations by the control layer; then the mutex is released, and the confirmation flag (a 2-byte field, 0x0000 indicates unconfirmed, 0x0001 indicates successful writing, and 0xFFFF indicates writing failure) of the system state area is read; if the confirmation flag is 0x0001, it is determined that the writing is successful; if it is 0xFFFF, the retry process is triggered, with a maximum of 3 retries, each retry interval being 10 ms; if all 3 retries fail, the writing failure information is recorded and an alarm is raised to ensure that the configuration parameters are successfully distributed as much as possible, for example, when temporary access conflicts occur in the shared memory layer, the retry mechanism can improve the success rate of configuration distribution and avoid system configuration update failure due to single failure.
[0029] In summary, compared to traditional Socket communication, dedicated protocol or database middleware, etc., this scheme realizes precise adaptation of memory space through dynamic creation and partition design of the shared memory layer; greatly reduces data transmission delay through zero-copy writing and memory mapping reading; guarantees the reliability of data interaction through timeliness verification, CRC integrity verification and mutex atomic writing; further improves system performance and configuration distribution success rate through local cache optimization and retry mechanism, and finally realizes low latency, high reliability and high adaptability of control layer and service layer data synchronization in industrial automation scenarios, meeting the real-time data interaction needs of high-precision devices such as robot control and numerical control machine tools.
[0030] In one embodiment of the present application, the step of dynamically creating a shared memory layer according to the EtherCAT network configuration and the number of slaves includes: S11, calculating the total capacity of the shared memory layer according to the number of EtherCAT slaves and the data type, the calculation formula is: In the formula, Total capacity of the shared memory layer, Capacity of the system state area, Number of EtherCAT slaves, Capacity of the single slave state area, Capacity of the single slave PDO data area, Capacity of the configuration information area; S12, calling the shared memory interface provided by the operating system to create the physical carrier of the shared memory layer, and setting the access permission to read and write for the control layer and the service layer; S13, configuring the internal structure of the shared memory layer according to the preset partition layout, and dividing the address space in the order of the system state area, the slave state area, the PDO data area, and the configuration information area; S14, mapping the shared memory layer to the address space of the control layer and the service layer to establish a direct access channel; S15, initializing the initial state values of the system state area, the slave state area, the PDO data area, and the configuration information area in the shared memory layer, including setting the synchronization flag of the system state area to the unsynchronized state.
[0031] As described in steps S11-S15 above, the present application can accurately calculate the total capacity of the shared memory layer according to the number of EtherCAT slaves and the data type, call the operating system interface to create a shared memory object, divide the functional partitions and map them to the address space of the control layer and the service layer, and initialize the state of each partition, finally realizing the dynamic adaptation and standardized construction of the shared memory layer, and providing a stable and efficient memory carrier for the data interaction of the control layer and the service layer.
[0032] The shared memory layer, as the core medium for data interaction between the control layer and the service layer, its capacity size needs to be highly matched with the actual EtherCAT network configuration (such as the number of slaves and data types) - if the capacity is too small, the PDO data or state data of the slave cannot be completely stored, causing data overflow; if the capacity is too large, it will cause redundant waste of physical memory resources, especially in the multi-slave and high-concurrency scenarios, unreasonable memory allocation will directly affect the overall system efficiency.
[0033] This invention achieves dynamic adaptation of shared memory capacity to actual needs through precise capacity calculation, standardized object creation, structured partitioning, cross-layer address mapping, and initial state configuration. It also ensures the standardization and reliability of data interaction through partitioning and initialization.
[0034] First, the total capacity of the shared memory layer is calculated based on the number and data types of EtherCAT slaves. This step is fundamental to the creation of the shared memory layer. Quantitative calculations determine the total capacity of the shared memory, ensuring that the capacity meets all data storage needs while avoiding resource waste. Technically, the specific values of each parameter in the formula need to be obtained: the number of EtherCAT slaves, N, can be read in real-time using API functions provided by the EtherCAT master (such as the `ecrt_master_get_slave_count` function in the IGH EtherCAT library), or manually configured by the user during system initialization based on the actual list of deployed slave devices; the size of the system status area is preset according to the system-level data types and quantities to be stored, for example, storing one microsecond-level timestamp (8 bytes), one synchronization flag (1 byte), one acknowledgment flag (2 bytes), and a reserved system information field (117 bytes). The capacity is set to 128 bytes, a value determined with reference to the typical storage requirements of system status data in industrial EtherCAT systems; this is the capacity of a single slave station status area. Based on the standard fields of EtherCAT slave status data, slave status data typically includes online status (1 byte, e.g., 0x01 for online, 0x00 for offline), AL status code (2 bytes, e.g., 0x00 for normal operation, 0x05 for initialization failure), and error code (4 bytes), after adding reserved space. It can be set to 32 bytes, a value that matches the status data storage requirements of most EtherCAT slave devices; the capacity of a single slave PDO data area. Based on the PDO mapping configuration, the PDO mapping table defines the real-time process data objects that a single slave station needs to transmit (e.g., input PDOs contain 3 channels of position feedback data, 4 bytes each; output PDOs contain 3 channels of speed control commands, 4 bytes each). After adding the data verification field, It can be set to 64 bytes (the specific value can be adjusted according to actual control needs, with a typical range of 64-1024 bytes); the capacity of the configuration information area. The configuration parameters are determined based on their type and quantity. These parameters typically include the slave control cycle (4 bytes), PDO mapping update instructions (256 bytes), and other device parameters. After adding redundant space, It can be set to 4096 bytes, which can meet the configuration parameter storage needs of most industrial scenarios.
[0035] Then, "the shared memory object is created by calling the shared memory interface provided by the operating system, and the access permission is set to read and write for the control layer and the service layer", which is converted into a shared memory entity that can be recognized by the operating system, and the data security is guaranteed through permission control. Among them, the shared memory interface provided by the operating system needs to be selected according to the system architecture, and the shm_open function (POSIX standard interface) is usually called in Linux system, and the CreateFileMapping function is called in Windows system. Taking Linux system as an example, when calling the shm_open function, the name of the shared memory (such as using the naming rule of " / ecat_shm_" + network interface MAC address to ensure the uniqueness of the shared memory object), the creation mode (such as O_CREAT|O_RDWR, indicating creation and supporting read and write) and the initial permission need to be specified; after creation, the size of the shared memory object is set to the total capacity calculated by S11 through the ftruncate function; at the same time, the access permission is set to read and write for the control layer and the service layer (such as setting the permission to 0660 through the chmod function in Linux system, that is, the owner and the group have read and write permissions, and other users have no permission), which can avoid unauthorized processes (such as ordinary application programs in the system) to access or modify the data in the shared memory, prevent the abnormal data interaction between the control layer and the service layer due to misoperation, for example, if an ordinary application program mistakenly writes garbage data to the PDO data area, it will cause the control layer to read incorrect data, and then cause device control failure, and permission control can block such risks from the bottom.
[0036] Then, "the internal structure of the shared memory layer is configured according to the preset partition layout, and the address space is divided in the order of system state area, slave state area, PDO data area and configuration information area", which can divide the continuous shared memory object into functional partition, realize the classified storage and accurate access of data, and avoid the low reading efficiency or data disorder caused by mixed storage of different types of data. Among them, the address offset of the preset partition layout needs to be determined based on the capacity of each partition. This address space is divided in the order of "system management data-slave state data-real-time process data-configuration parameter", which conforms to the data access logic of the control layer and the service layer-the control layer usually reads system state data first to confirm the synchronization state, and then writes PDO data and slave state data; the service layer reads PDO data and slave state data first for business processing, and then writes configuration parameters. The matching of partition layout and access logic can reduce the number of address jumps and improve the data access efficiency.
[0037] Then, the shared memory layer is mapped to the address space of the control layer and the service layer to establish a direct access channel. This step breaks the address space isolation between the control layer and the service layer, and enables them to directly access the physical address of the shared memory layer, avoids copying of data in different address spaces, and lays a foundation for subsequent zero-copy data interaction. The control layer and the service layer respectively map the shared memory object to their virtual address space through the memory mapping function provided by the operating system (such as the mmap function of the Linux system). When mapping, the file descriptor of the shared memory object, the mapping start address (usually set to NULL, automatically allocated by the operating system), the mapping length (i.e. the total size calculated in S11) and the mapping permission (PROT_READ|PROT_WRITE for the control layer, supporting reading and writing; PROT_READ or PROT_READ|PROT_WRITE for the service layer, set to PROT_READ if only reading data) need to be specified. Taking the control layer as an example, after calling the mmap function, the operating system will allocate a continuous address equal to the total size of the shared memory in the virtual address space of the control layer, and establish a mapping relationship between the virtual address and the physical address of the shared memory. The subsequent read and write operations of the control layer on the virtual address will be directly mapped to the physical address of the shared memory without the need for transfer through the kernel space or data copying. For example, when the control layer writes the slave PDO data, the data is directly written to the mapped virtual address, which can complete the update of the shared memory layer PDO data area. Compared with the traditional Socket communication (which needs to pass through multiple links of data copying in the user space, the kernel space and the network protocol stack), this method can reduce the data writing delay and improve the real-time performance.
[0038] Then, the initial state values of the system state area, the slave state area, the PDO data area and the configuration information area in the shared memory layer are initialized, including setting the synchronization flag of the system state area to the unsynchronized state. This step can set the initial reference state for each partition, ensure that the control layer and the service layer can identify data validity at the starting stage of data interaction, and avoid synchronization exceptions caused by chaotic initial state. The initialization operation needs to be performed one by one according to the partition: the initialization of the system state area includes setting the timestamp to 0 (indicating that it is not updated), setting the synchronization flag to 0x00 (unsynchronized state, which is different from the 0x01 state area after synchronization in the S2 step), setting the confirmation flag to 0x0000 (unconfirmed state), and setting the system running state field to "initializing" (for example, if it is represented by 1 byte, 0x02 represents initializing); the initialization of the slave state area needs to set the state field corresponding to each slave to the default value, such as setting the online state to 0x00 (offline) and setting the AL state code to 0xFF (uninitialized) and setting the error code to 0x00000000 (no error). This initial state can help the control layer identify the slave that is not online, and avoid misreading invalid data; the initialization of the PDO data area needs to set all PDO data fields to 0 or a preset safe value, such as setting the speed control instruction to 0 (to avoid accidental start of the device during initialization) and setting the position feedback data to 0 (indicating that it is not collected); the initialization of the configuration information area includes setting the configuration version identifier to 0 (initial version), setting all configuration parameters to the default value (such as setting the control period to 1 ms, which meets the regular control requirements of most EtherCAT devices), and writing the initial CRC check value (to ensure that the integrity can be verified when updating the configuration parameters later). For example, if a slave does not normally go online during system initialization, its corresponding slave state area is initialized to the "offline" state, and the control layer will skip the PDO data writing for this slave after reading the state, avoiding system errors caused by writing to invalid addresses.
[0039] The scheme realizes dynamic matching of the shared memory capacity and the EtherCAT network demand through the formula calculation of S11, avoids resource waste or data overflow caused by capacity deviation; through the permission control of S12 and the address mapping of S14, data security is guaranteed, and a direct access channel between the control layer and the service layer is established, providing support for zero-copy data interaction; through the structured partitioning of S13 and the initialization of S15, the data is classified and stored with the same initial state, improving the data access efficiency and system stability.
[0040] In one embodiment of the present application, the control layer interface module reads PDO data of the slave station and state data of the slave station from the EtherCAT master station in each control cycle through a real-time thread, and writes the PDO data of the slave station and the state data of the slave station into the PDO data area and the slave station state area of the shared memory layer through memory mapping for zero-copy writing, while updating the time stamp and synchronization flag of the system state area, which comprises the steps of: S21, configuring a real-time execution environment of the control layer interface module, including setting a real-time scheduling strategy and processor binding; S22, at the beginning of each control cycle, obtaining PDO data of the slave station through the EtherCAT communication protocol, the PDO data including input PDO data and output PDO data; S23, obtaining state data of the slave station through an EtherCAT master station interface function, the state data of the slave station including at least online state and AL state code of the slave station; S24, writing the PDO data into the PDO data area of the shared memory layer through memory mapping, while writing the state data of the slave station into the slave station state area of the shared memory layer, and updating device state information of the slave station state area in the shared memory layer; S25, updating data time stamp and synchronization state identification in the system state area of the shared memory layer.
[0041] As described in steps S21-S25 above, the present application first configures a real-time execution environment of the control layer to ensure the timeliness of data processing, then accurately obtains PDO data and state data of the slave station from the EtherCAT master station, writes them into the corresponding partition of the shared memory layer through zero-copy mode, and finally updates the key identification of the system state area, finally realizing low-delay and high-reliable real-time data interaction between the control layer and the shared memory layer.
[0042] The control layer, as a bridge between the EtherCAT network and the shared memory layer, needs to complete data collection, transmission and storage in a fixed control cycle. If there is a delay in data processing or transmission, it will directly affect the control accuracy of the device (such as robot joint motion deviation, numerical control machine tool machining error). At the same time, PDO data (real-time process data) and state data (device running state) of the slave station are the core basis for system control and monitoring, and the completeness and accuracy of the data directly determine the effectiveness of the control logic - if the PDO data is missing or the state data is incorrect, it may cause incorrect control instructions or incorrect device fault judgment. Therefore, it is necessary to solve the problems related to real-time guarantee of the control layer, accurate data acquisition and efficient writing of the shared memory.
[0043] The application guarantees the timeliness of processing by real-time thread scheduling, realizes accurate data acquisition by adapting to the EtherCAT protocol, and realizes zero-copy writing by memory mapping, thereby improving the real-time performance and reliability of data interaction of the control layer.
[0044] First, the real-time execution environment of the configuration control layer interface module is configured, including setting the real-time scheduling strategy and processor binding. This step can provide a dedicated high-priority execution environment for the control layer data processing, avoid interference from other tasks of the operating system, and ensure that data acquisition and writing are completed within the control period. In terms of technical implementation, first, the real-time scheduling strategy is set. The SCHED_FIFO scheduling strategy (first-in first-out scheduling) is commonly used in the industrial control field. Under this strategy, once a thread obtains CPU resources, it will continue to execute until it is voluntarily released or preempted by a higher-priority thread. Compared with the ordinary SCHED_OTHER scheduling strategy (time-sharing scheduling), thread scheduling delay can be greatly reduced. At the same time, the thread priority is set, usually set to 90-95 (the real-time priority range of the Linux system is 1-99, the higher the value, the higher the priority), to ensure that the control layer thread priority is higher than other non-real-time tasks in the system (such as log recording, interface rendering thread), avoiding being preempted by low-priority tasks. CPU resources. Second, processor binding is performed. The pthread_setaffinity_np function is used to bind the control layer real-time thread to a physical CPU core (such as core 0 or core 1), avoiding thread switching between different CPU cores. When the thread switches, the context (register data, stack information) needs to be saved and restored, which will cause additional delay, and binding to a fixed core can eliminate this kind of delay. For example, in the robot control scenario, the control period is set to 1ms. If the control layer thread is not configured with a real-time environment, data acquisition may be delayed to 1.5ms due to CPU occupation by other system tasks, exceeding the control period threshold, causing robot motion accuracy deviation. Through the configuration of step S21, the thread scheduling delay can be controlled within 10μs, and data acquisition and writing can be completed within the 1ms control period, ensuring control accuracy.
[0045] Then is "at the beginning of each control cycle, PDO data of the slave station is obtained through the EtherCAT communication protocol, and the PDO data includes input PDO data and output PDO data", the physical meaning of this step is to accurately collect real-time process data of the slave station according to the control cycle, to provide a data source for the subsequent shared memory layer, and to distinguish between input and output PDO data to adapt to different control requirements. In terms of technical implementation, the control layer interface module establishes communication with the slave station through the protocol interface provided by the EtherCAT master station (such as the ecrt_slave_config_pdo_mapping function in the IGH EtherCAT library), and triggers PDO data collection at the beginning of each control cycle. The input PDO data is the device state data (such as the current position of the motor, the speed, and the sensor detection value) fed back by the slave station to the master station, and the output PDO data is the control instruction data (such as the target speed of the motor and the torque limit value) issued by the master station to the slave station. The two data are exchanged through a pre-set PDO mapping table, which needs to be configured in the system initialization stage and contains information such as slave station index, data object ID, and data length (for example, the input PDO data of a certain motor slave station includes "position feedback" (index 0x6064, data length 4 bytes) and "speed feedback" (index 0x606C, data length 4 bytes), and the output PDO data includes "target speed" (index 0x6040, data length 4 bytes)). The control layer directly reads the PDO data cached by the EtherCAT master station through the protocol interface, without the need for complex protocol analysis (the EtherCAT master station has completed the protocol stack processing), ensuring data collection efficiency. For example, in the numerical control machine tool scene, the control layer can quickly obtain the input PDO data (current speed, torque) and output PDO data (target speed) of the main shaft motor through this step in each control cycle.
[0046] Then is "acquiring the state data of the slave through the EtherCAT master station interface function, the state data of the slave at least including the online state and AL state code of the slave", which can collect the running state information of the slave, supplement the device health state not covered by the PDO data, and provide the basis for system monitoring and fault diagnosis. In terms of technical implementation, the control layer interface module calls the special interface function of the EtherCAT master station to acquire the state data: the online state of the slave is acquired through the ecrt_slave_get_state function, the return value is usually "online" (such as EC_SLAVE_STATE_OPERATIONAL) or "offline" (such as EC_SLAVE_STATE_MISSING), stored in 1 byte or enumeration type; AL state code; (Application Layer state code) is acquired through the ecrt_slave_get_al_state function, which complies with the EtherCAT technical specification, and different values represent different running states (such as 0x00 indicating "no error, normal operation", 0x05 indicating "initialization fault", 0x08 indicating "configuration fault"), stored in 2 bytes. In addition, according to the actual needs, the error code (such as ecrt_slave_get_error_code function) and firmware version of the slave can also be acquired. These data and the PDO data of S22 together constitute the complete data portrait of the slave - the PDO data reflects "real-time control process", and the state data reflects "device overall health", the combination of the two can avoid the monitoring blind area caused by relying only on PDO data, for example, the PDO data of a slave shows normal speed, but the AL state code; is 0x05 (initialization fault), after acquiring the state data through S23, the system can identify the potential fault of the device in time, and avoid continuing to issue control instructions to cause safety problems.
[0047] Then, "write the PDO data to the PDO data area of the shared memory layer through memory mapping, and write the slave status data to the slave status area of the shared memory layer, and update the device status information of the slave status area in the shared memory layer", which can write the collected data to the corresponding partition of the shared memory layer in a zero-copy manner, eliminate data copy delay, and ensure that the data storage location matches the partition design of the shared memory layer, facilitating accurate reading by the service layer. In terms of technical implementation, the control layer interface module directly accesses the virtual address space of the shared memory layer using the memory mapping relationship established in step S14: for PDO data, according to the slave index and data length defined in the PDO mapping table, the input PDO data and the output PDO data are written to the corresponding exclusive address segment of the slave in the PDO data area of the shared memory layer (for example, the PDO data of slave 1 is written to the start address + 0 to + 63 bytes of the PDO data area, and the PDO data of slave 2 is written to + 64 to + 127 bytes, the specific address segment is determined by the partition layout in step S13); for slave status data, the online status, AL status code, and other information are written to the corresponding position of the slave status area of the shared memory layer according to the preset format (for example, the online status occupies 1 byte, the AL status code occupies 2 bytes, and the error code occupies 4 bytes). Since memory mapping is used for direct writing, data does not need to be copied from the user space of the control layer to the kernel space, and then written from the kernel space to the shared memory, but is directly written to the physical address of the shared memory, realizing zero-copy transmission. At the same time, the device status information of the slave status area is updated in real time after data writing, ensuring that the service layer reads the latest status and avoiding data lag.
[0048] Finally, the step of updating the data timestamp and the synchronization state identifier in the system state area of the shared memory layer can add a "time label" and a "synchronization label" to the data in the shared memory layer, so that the service layer can judge the timeliness and integrity of the data and avoid using expired or unsynchronized data. In terms of technical implementation, first, the data timestamp is updated. The control layer interface module obtains a high-precision clock synchronized with the EtherCAT master station (obtained through the ecrt_master_get_system_time function to ensure synchronization with the data acquisition time of the slave station), and writes the clock value into the timestamp field (usually 8 bytes, stored in the format of Unix timestamp or relative timestamp) of the system state area. The timestamp can accurately record the time when the data is written into the shared memory layer, and the service layer can subsequently judge whether the data is expired by comparing the difference between the read time and the timestamp. Second, the synchronization state identifier is updated. The synchronization state identifier is a 1-byte or 2-byte state bit. When the PDO data and the state data are all successfully written into the corresponding partition of the shared memory layer, the identifier is set to "synchronization completed" (such as 0x01). If an exception occurs during data writing (such as missing data of a slave station), the identifier is set to "synchronization exception" (such as 0x02). The identifier provides an intuitive basis for the service layer to judge data synchronization. Before reading the data, the service layer checks the synchronization state identifier. Only when the identifier is "synchronization completed" can the data be read, so as to avoid logical errors caused by reading incomplete data. For example, in an automatic production line scenario, if the PDO data of slave station 3 fails to be written in a control cycle, the synchronization state identifier is set to 0x02 in step S25. After the service layer reads the identifier, it skips the current cycle data and waits for the next cycle to be synchronized before reading, so as to ensure that production scheduling decisions are based on complete data.
[0049] The present scheme controls the thread scheduling delay to be lower through real-time environment configuration, guarantees the timeliness of data processing in the control cycle, acquires complete PDO data and state data through precise data acquisition and adaptation to the data characteristics of the EtherCAT slave station, greatly reduces the data transmission delay through zero-copy writing to meet the high real-time requirement, and provides a basis for the service layer to judge the effectiveness of the data through state identifier updating. In the industrial automation scenario, the data interaction between the control layer and the shared memory layer meets both the real-time requirement and the precision requirement.
[0050] In an embodiment of the present application, the step of the service layer interface module reading the device data in the PDO data area and the slave station state area of the shared memory layer through memory mapping and converting the binary device data into JSON format for use by the service layer, while establishing a local cache to reduce the shared memory access frequency, comprises: S31, establishing a memory mapping connection between the service layer interface module and the shared memory layer; S32, obtaining device data from the PDO data area and the station status area of the shared memory layer according to a preset reading strategy; S33, performing parsing processing on the device data and converting the device data into an internal data structure; S34, converting the parsed device data into a structured data format suitable for the service layer; S35, providing the processed device data to the service layer application through a data interface and updating a local cache.
[0051] As described in steps S31-S35, the application first establishes a memory mapping connection between the service layer interface module and the shared memory layer, then reads device data according to a preset strategy, provides the device data to the service layer application after parsing and format conversion, and updates a local cache to optimize access efficiency, thereby realizing efficient acquisition, adaptive use and performance optimization of device data in the shared memory layer by the service layer, and meeting the needs of the service layer in data compatibility and access efficiency.
[0052] The service layer undertakes functions such as data display and business logic processing (such as fault diagnosis and production scheduling), and its data needs and the control layer are significantly different: the control layer needs binary format raw data to ensure real-time performance, while the service layer relies on structured data formats (such as JSON) to adapt to scenarios such as Web interfaces and database storage; at the same time, the service layer has a high access frequency to data (such as Web interface data refresh every second), and if the shared memory layer is directly accessed every time, it may increase the access pressure of the shared memory, and even affect the real-time data writing of the control layer. In addition, the service layer and the shared memory layer belong to different address spaces, and need to establish an access channel through a specific technology, so it is necessary to solve the problems related to cross-layer data access, data format adaptation and access performance optimization.
[0053] The application realizes cross-layer direct access through memory mapping, guarantees data acquisition efficiency, adapts to the needs of the service layer through format conversion, and reduces the access frequency of the shared memory through a local cache, thereby balancing the needs of the service layer and the real-time performance of the control layer.
[0054] First, "establish a memory mapping connection between the service layer interface module and the shared memory layer", this step can break the address space isolation of the service layer and the shared memory layer, provide a direct access channel for the service layer to access the shared memory, and avoid the delay and data loss caused by the intermediate link. Technically, the service layer interface module calls the memory mapping function provided by the operating system (such as the mmap function of the Linux system), which is consistent with the mapping logic of the control layer in step S14, but the mapping permission needs to be set according to the service layer function requirements - if the service layer only needs to read device data (such as the Web monitoring scene), the mapping permission is set to PROT_READ (read only) to prevent the service layer from modifying the data in the shared memory by mistake, and to avoid affecting the data interaction of the control layer; if the service layer needs to issue configuration parameters (such as the remote configuration scene), it is set to PROT_READ|PROT_WRITE (read and write). When mapping, the file descriptor of the shared memory object (obtained by the shm_open function, consistent with the shared memory object used by the control layer), the mapping length (i.e. the total size of the shared memory layer calculated in step S11), and the mapping address are usually set to NULL, and the operating system automatically allocates a continuous virtual address space. For example, in the Linux system, the service layer calls mmap(NULL, total size, PROT_READ, MAP_PRIVATE, shared memory file descriptor, 0), which can establish a mapping connection with the shared memory layer. Subsequent read operations of the service layer on this virtual address will be directly mapped to the physical address of the shared memory layer, without the need to pass through the kernel, the data access delay is controlled in a lower range, and the efficiency is higher compared to through the API interface (the delay is usually in milliseconds).
[0055] Then is "get device data from PDO data area and slave status area of shared memory layer according to preset reading strategy", which can balance service layer data demand and shared memory access pressure through standardized reading strategy, and avoid high frequency disordered reading affecting control layer real-time. In technical implementation, preset reading strategy needs to be determined combined with service layer application scene: from reading period, if service layer is web monitoring interface (data refresh frequency is usually 1 second / time), reading period is set as 1 second, and maintains integer multiple relationship (1 second=1000*1 ms) with control layer writing period (such as 1 ms), avoiding data repetition or loss caused by reading period and writing period out of synchronization; from reading range, if service layer only needs specific slave data (such as only monitoring production line 1 motor slave), only read PDO data area and slave status area address segment corresponding to the slave, without reading all slave data, reducing data transmission amount. Parameters (period, range) of reading strategy can be set through configuration file in system initialization stage, configuration file is written by user according to service layer function demand, for example, in configuration file of web monitoring scene, reading period field is set as "1000 ms", target slave index field is set as "1, 3, 5", service layer interface module starts to read the configuration file, and reading operation can be executed according to preset strategy. This strategy reading mode can not only meet service layer data demand, but also reduce invalid access to shared memory, for example, when service layer only needs 3 slave data, reading data amount is only 1 / 5 of all 16 slaves, greatly reducing shared memory access pressure.
[0056] Then is "analyzing device data and converting to internal data structure", which can convert binary raw data stored in shared memory into structured data recognizable by service layer interface module, laying a foundation for subsequent format conversion, and completing preliminary data validity check. Technically, the analysis of device data needs to be based on the preset data format protocol, which is consistent with the format of the control layer writing data. For the input PDO data of PDO data area (such as motor position feedback), the binary data is usually a 32-bit floating-point number (4 bytes) stored in little-endian format. When parsing, it needs to be reorganized into a floating-point number (such as binary data 0x0000803F corresponds to floating-point number 1.0) and converted into physical units (such as position data from "pulse number" to "millimeter", which needs to be multiplied by the pulse equivalent parameter, which is obtained from the EtherCAT slave configuration file, such as 1000 pulses / mm). For online status data (1 byte) in the slave status area, binary values need to be mapped to text identifiers (such as 0x01 mapped to "online" and 0x00 mapped to "offline"), AL status code (2 bytes) needs to be parsed into status description according to the EtherCAT technical specification (such as 0x05 mapped to "initialization fault"). Data range check is also required during the parsing process. For example, the normal range of motor position feedback is 0-1000 mm. If the parsed data is 1500 mm, it is determined as invalid data, which needs to be discarded and abnormal log is recorded to avoid invalid data entering the subsequent process. For example, in the CNC machine tool scene, the binary data of the spindle speed in the PDO data area is 0x0000C842 (corresponding to 5000 in decimal), which is converted to "5000 rpm" when parsing combined with the pulse equivalent (1 pulse / revolution), and the value is checked whether it is within the allowed speed range of the spindle (0-8000 rpm). After confirming the validity, it is stored in the internal data structure (such as a structure in C language, containing "slave index", "data type", "physical value", "validity identifier" fields).
[0057] Then, the parsed device data is converted into a structured data format suitable for the service layer. This step can adapt to the data format requirements of the service layer application, making device data directly available for web display, database storage, business logic calculation, and other scenarios, eliminating the adaptation cost caused by format differences. Technically, the structured data format suitable for the service layer is mainly in JSON format (XML format may also be used in industrial scenarios, which needs to be determined according to the service layer application), and the internal data structure obtained in step S33 needs to be mapped to JSON key-value pairs during conversion. The "slave index" corresponds to the "slave_index" field in JSON, the "data type" corresponds to the "data_type" field (such as "position" for position, "speed" for speed, and "online_status" for online status), the "physical value" corresponds to the "value" field, and the "validity identifier" corresponds to the "is_valid" field (true for valid and false for invalid). For example, the parsed data of a slave station is "slave index 1, data type speed, physical value 1500 revolutions per minute, validity identifier true", and the converted JSON format is {"slave_index": 1, "data_type": "speed", "value": 1500, "is_valid": true, "timestamp": 1698765432123} (where the timestamp field is obtained from the shared memory layer system state area, which is the timestamp when the data is written). If the service layer application is database storage, the JSON format also needs to be further converted into the fields corresponding to the database table structure (such as the "slave_id" "data_type" "data_value" "create_time" fields in the MySQL table), to ensure that the data can be directly inserted into the database without additional format adjustment. This format conversion method, compared to the traditional method of "control layer, database, service layer" multi-link conversion, reduces 2-3 times of format conversion steps, and the data adaptation delay can be reduced from 100 ms to within 10 ms, while avoiding data loss in the conversion process.
[0058] Finally, "providing the processed device data to the service layer application through the data interface and updating the local cache", this step can provide a standardized data acquisition interface for the service layer application, and at the same time, store recent data through the local cache to reduce the direct access frequency of the service layer to the shared memory layer, balance the service layer data demand and the control layer real-time. In terms of technical implementation, first, the standardized data interface (such as RESTful API, WebSocket interface) is used to provide the processed structured data to the service layer application-RESTful API is suitable for periodic data acquisition (such as Web interface calling API to get data once per second), and WebSocket interface is suitable for real-time data push (such as actively pushing abnormal data to the Web interface when a fault alarm occurs), and the data format returned by the interface is consistent with the structured data format of S34 step, which is convenient for the service layer application to parse. Secondly, update the local cache, the local cache adopts LRU (Least Recently Used) eviction policy, and the cache capacity is set to twice the total amount of device data in the shared memory layer (such as storing 16 slave device data in the shared memory layer, and the cache capacity is set to 32), and the cache update period is consistent with the service layer reading period (such as updating once per second). When the service layer application requests data again, first query the local cache, if there is the latest data in the cache (the difference between the timestamp of the cache data and the timestamp of the shared memory layer system state area is less than the reading period), then return the data from the cache directly, without accessing the shared memory; if the cache data is expired or missing, then re-execute S32-S34 steps to read and update the cache. For example, in the Web monitoring interface scenario, the interface requests data once per second, the first request is read from the shared memory and the cache is updated, the second request is returned directly from the cache, and the shared memory access frequency is reduced from 1 per second to 1 per second (only when the cache is updated), which greatly reduces the access pressure of the shared memory and avoids the delay of the control layer data writing caused by the high-frequency access of the service layer. At the same time, the cache adopts LRU strategy, when the cache capacity is insufficient, the longest unused slave data (such as the 16th slave data which has not been monitored for a long time) is automatically evicted, ensuring that the cache stores the data frequently accessed by the service layer, and improving the cache hit rate.
[0059] The present scheme realizes direct access of the service layer and the shared memory layer through memory mapping connection, the data acquisition delay is lower; through data analysis and format conversion, the format difference between the control layer binary data and the service layer structured data is eliminated, and various scenes such as Web display and database storage are adapted; through strategic reading and local cache, the access frequency of the shared memory is reduced, and the interference on the real-time requirement of the control layer is avoided. Thus in the industrial automation scene, the service layer can efficiently and accurately acquire device data, while balancing the real-time requirement of the control layer.
[0060] In one embodiment of the present application, the service layer interface module calculates the difference between the device data reading time and the timestamp of the system state area in the shared memory layer, and if the difference exceeds the preset synchronization threshold, it is determined that the device data is expired, triggering the steps of re-reading and verifying the data integrity through CRC check, which include: S41, obtaining the timestamp of data update from the system state area of the shared memory layer; S42, obtaining the device data reading time and calculating the difference between the device data reading time and the timestamp; S43, comparing the difference with the preset synchronization threshold to determine the data timeliness; S44, when the difference exceeds the synchronization threshold, it is determined that the device data is expired, triggering the process of re-reading the device data; S45, verifying the integrity of the read device data through CRC check, recording the synchronization exception and triggering the alarm mechanism.
[0061] As described in steps S41-S45 above, the present application first obtains the timestamp of data update from the shared memory layer, then calculates the difference between the data reading time and the timestamp to determine the data timeliness, triggers the re-reading of expired data, verifies the data integrity through CRC check and records the exception, realizes the dual protection of timeliness and integrity of device data obtained by the service layer, and avoids the service layer business logic error or system failure caused by invalid data.
[0062] The service layer is based on device data to carry out core businesses such as fault diagnosis and production scheduling. If expired data (such as data delayed for more than the control period) is used, it may cause the business logic to be out of touch with the actual device state, for example, adjusting the production rhythm based on the motor speed data one second ago may cause production deviation due to the change of the current motor speed. If damaged data (such as data with byte loss in the transmission process) is used, it may directly cause fault misjudgment (such as identifying the damaged “error code” data as device fault, triggering unnecessary downtime). In addition, the data in the shared memory layer may be delayed or damaged in the transmission and storage process due to electromagnetic interference, system resource fluctuation and other factors, so it is necessary to solve the problems related to data timeliness judgment and data integrity verification to ensure that each piece of data obtained by the service layer can accurately reflect the current state of the device.
[0063] The present application judges the timeliness by the timestamp difference, verifies the integrity by CRC check, guarantees the data continuity by re-reading and alarm mechanism, and constructs a multi-dimensional and closed-loop verification system.
[0064] Firstly, "get the timestamp of data update from the system state area of the shared memory layer", the physical meaning of this step is to get the "reference time" of data writing to the shared memory layer, which can provide a reference standard for subsequent judgment of data expiration and ensure the accuracy of timeliness judgment. Technically, the service layer interface module directly accesses the timestamp field of the shared memory layer system state area through the virtual address of memory mapping - the timestamp is updated in real time by S25 step after writing data in the control layer, using a high-precision clock synchronized with the EtherCAT master, and the storage format is 64-bit integer (such as Unix timestamp), which is consistent with the format of the service layer system clock, avoiding comparison errors caused by format differences. It should be noted that the service layer needs to synchronize the EtherCAT master clock regularly (such as synchronizing once an hour through NTP protocol), to ensure that the deviation between its own system clock and the timestamp is within 10μs, avoiding misjudgment caused by clock desynchronization.
[0065] Then, "get the device data reading time and calculate the difference between the device data reading time and the timestamp", this step can quantify the "time interval" of data from writing to the shared memory layer to being read by the service layer, and judge whether the data can still reflect the current state of the device through the interval. Technically, the service layer interface module calls the system function (such as the clock_gettime function of the Linux system, using the CLOCK_MONOTONIC clock source to avoid the influence of system time adjustment) to get the current reading time at the moment of starting to read the device data, also with high-precision recording; then calculate the difference between the reading time and the timestamp obtained by S41 step (difference = reading time - timestamp), which directly reflects the "residence time" of data in the shared memory layer - the longer the residence time, the higher the possibility of data deviation from the current state of the device.
[0066] Then is "the difference is compared with the preset synchronization threshold, the data timeliness is judged", this step can quantify the "expiration standard" through the preset threshold, and it is clear that the data stay time exceeds which range is no longer applicable, avoid the inconsistency of the verification standard caused by subjective judgment. Technically, the preset synchronization threshold needs to be determined in combination with the control layer write cycle and service layer business requirements - usually set to 2 times the control layer write cycle, for example, the control layer write cycle is 1ms (i.e. update data every 1ms), the synchronization threshold is set to 2ms, which allows data to exist for a short period of time (such as 1.5ms delay caused by system resource fluctuations), and can avoid data staying time too long (such as more than 2ms, the device state may have been updated twice, the data is seriously lagging behind). The specific value of the synchronization threshold is stored in the service layer configuration file, which can be adjusted by the user according to the actual scene (such as the robot control scene with extremely high real-time requirements, the threshold can be set to 1 times the control cycle; for the environmental monitoring scene with lower real-time requirements, it can be set to 5 times the control cycle). After reading the threshold value in the configuration file, the service layer interface module compares the difference value calculated in step S42 with it: if the difference value ≤ threshold, it is determined that the data is not expired, and it can enter the subsequent integrity verification; if the difference value > threshold, it is determined that the data is expired, triggering the re-reading process in step S44.
[0067] Then is "when the difference exceeds the synchronization threshold, it is determined that the device data is expired, triggering the process of re-reading the device data", this step can compensate for the data expiration problem through the re-reading mechanism, avoid the data supply interruption caused by the service layer directly discarding the expired data, and ensure the business continuity. Technically, the re-reading process adopts an exponential backoff strategy, for example, the interval of the first re-reading is set to 50μs (waiting for the control layer to complete the next data write), if the data is still expired after the first re-reading (such as the control layer write delay causes the data not to be updated), the second interval is doubled to 100μs, the third is 200μs, the maximum interval is set to 1ms (to avoid occupying system resources indefinitely), and the upper limit of the retry number is set to 3 (which can be adjusted in the configuration file). If the data is still expired after 3 retries, it is determined that there is an exception in the current shared memory layer data, and the retry is stopped and the alarm mechanism in step S45 is triggered. For example, the first reading difference of a slave station data is 1200μs (more than 1000μs threshold), the service layer waits for 50μs and re-reads, at this time the control layer has completed a new data write, the timestamp is updated to the latest value, and the recalculated difference is 300μs (≤ threshold), the data is restored effectively, and it can normally enter the subsequent process. This exponential backoff strategy not only avoids the consumption of system resources caused by frequent retries, but also maximizes the probability of obtaining the latest data, compared with fixed interval retry (such as 100μs each time), the data recovery success rate is higher.
[0068] Finally, "integrity verification of read device data by CRC check, record synchronization exception and trigger alarm mechanism", this step can verify whether the data itself is damaged, and record and alarm the abnormal data to provide troubleshooting basis for operation and maintenance personnel, forming a verification closed loop. Technically, first, CRC check is performed: when writing device data, the control layer synchronously calculates the CRC32 check value of the PDO data area and the slave station state area data, and stores the check value at the tail of the corresponding data area (such as reserving 4 bytes at the end of the PDO data area to store the CRC value); after the service layer reads the device data, the check value at the tail is extracted, and the CRC32 value of the read data (excluding the check value field) is recalculated, if the two values are consistent, the data is determined to be complete; if not, the data is determined to be damaged. Secondly, record the synchronization exception: whether it is "timeliness exception" of S44 step retry failure or "integrity exception" of CRC check failure, the service layer will write the exception information (including exception time, slave station index, exception type, difference / CRC value) into the system log file (such as / var / log / ecat_data_sync.log), and the log format adopts structured text, which is convenient for operation and maintenance personnel to trace back. Finally, trigger the alarm mechanism: if the exception appears continuously for 3 times (configurable), send alarm information to the operation and management platform through SNMP protocol, or trigger local sound and light alarm (such as alarm light flashing of industrial host), timely remind operation and maintenance personnel to troubleshoot problems (such as checking shared memory link, EtherCAT master clock synchronization state).
[0069] The scheme accurately identifies expired data through timestamp difference judgment; improves data recovery success rate through exponential backoff retry; and fully guarantees data integrity and supports fault troubleshooting through CRC check and alarm recording. Therefore, in the industrial automation scene, the service layer data error rate can be controlled below a lower proportion, the data supply time is shorter, which provides key support for the reliable operation of service layer business logic, and reduces the difficulty of troubleshooting for operation and maintenance personnel.
[0070] In an embodiment of the present application, when the service layer interface module writes configuration parameters to the configuration information area of the shared memory layer, it uses a mutex to ensure atomic writing, and verifies whether the writing is successful by reading the confirmation flag of the system state area, and if it fails, it retries until the maximum number of retries. S51, receiving the configuration parameters sent by the service layer application, performing parameter validity verification; S52, acquiring the mutex of the shared memory layer to ensure the atomicity of the configuration parameter writing; S53, writing the verified configuration parameters to the configuration information area of the shared memory layer; S54, updating the configuration version identifier and check information; S55, release the mutex, and read the confirmation flag of the system state area. If the confirmation flag is 1, it is determined that the writing is successful, and if it fails, it is retried until the maximum number of retries.
[0071] As described in steps S51-S55, the application first verifies the validity of the configuration parameters sent by the service layer application, then guarantees the atomicity of parameter writing through the mutex, updates the configuration identifier after writing is completed and verifies the result, triggers the retry mechanism when it fails, realizes the safe and reliable delivery of configuration parameters between the service layer and the control layer, and ensures that the control layer can accurately receive and execute the configuration instructions of the service layer.
[0072] The configuration parameters issued by the service layer (such as slave control period, PDO mapping rule, and device running threshold) directly determine the running logic of the control layer and the working state of the device. If the parameters are invalid (such as the control period is set to 0 or exceeds the device support range), it may cause the control layer program to be abnormal or the device to be overloaded; if the parameter writing process is interrupted (such as multi-thread concurrent writing leading to field overlap), it will produce "semi-valid" parameters, causing control logic confusion - for example, only part of the PDO mapping rule is updated, which may cause the control layer to fail to correctly identify the slave data. In addition, the configuration information area of the shared memory layer may be accessed by multiple threads at the same time (such as multiple applications in the service layer issuing different configurations at the same time), and a specific mechanism is needed to guarantee the safety of writing, and the writing result needs to be verified to confirm that the control layer can receive new parameters, so the problems of parameter validity screening, writing atomicity guarantee, result verification and retry related problems need to be solved to ensure the safety and reliability of the whole process of configuration delivery.
[0073] The application screens illegal parameters through validity verification, guarantees concurrent safety through mutex, and ensures the closed loop of configuration delivery through confirmation flag and retry mechanism, covering all risk points of configuration delivery.
[0074] Firstly, "receive the configuration parameters sent by the service layer application, and verify the validity of the parameters", this step can filter out invalid or illegal parameters in advance, avoid their entering the shared memory layer and affecting the running of the control layer, and ensure the safety of configuration from the source. Technically, the service layer interface module first receives the configuration parameters sent by the service layer application (such as remote configuration platform, local management software) through the standardized interface (such as RESTful API, internal function call), and the parameter format adopts the key-value pair structure (including parameter ID, data length, data value, such as "control_cycle=1000us" "pdo_mapping_index=0x6040"). Then, the validity verification is carried out, and the verification logic needs to be determined in combination with the parameter type and the device specification: for numerical value type parameters (such as control cycle), check whether it is within the range supported by the device (such as the control cycle of a certain EtherCAT slave station supports 500us-10ms, if the parameter is 200us, it is judged as invalid); for enumeration type parameters (such as PDO mapping mode), check whether it belongs to the preset enumeration value (such as only supporting "cyclic transmission" "event triggered" two modes, other modes are judged as invalid); for structured parameters (such as PDO mapping table), check whether its format conforms to the EtherCAT protocol specification (such as whether the index is hexadecimal, whether the data length matches the parameter type). The verification rules of the parameters and the device specification data need to be read and stored from the technical manual or configuration file of the EtherCAT slave station in the system initialization stage, for example, the support range of the slave station control cycle can be obtained from the " <cyclerange>500 us - 10 ms< / cyclerange> " field of the device XML configuration file. If the verification fails, the service layer interface module directly returns an error message to the service layer application (such as "the parameter control_cycle=200us exceeds the support range 500us-10ms"), and terminates the subsequent process; if the verification is passed, it enters the next step of writing operation. For example, in the robot control scene, the service layer application issues the parameter "joint 1 torque limit=200N·m", while the maximum torque limit of the joint is 150N·m, and the S51 step will judge that the parameter is invalid and return an error, avoiding the damage of the joint due to the torque overrun.
[0075] Then is "get the mutex lock of the shared memory layer, ensure the atomicity of the configuration parameter writing", the physical meaning of this step is to provide "exclusive access" for the configuration parameter writing process, prevent data conflicts caused by simultaneous writing of multiple threads or multiple applications, and guarantee the integrity of parameter writing. Technically, the mutex is of pthread_mutex_t type (applicable to POSIX system), and the PTHREAD_MUTEX_ERRORCHECK mutex type is used - this type supports error checking, and if a thread requests again without releasing the mutex, or releases a non-held lock, it will return an explicit error code (such as EDEADLK), which is convenient for troubleshooting concurrent problems, and compared with the ordinary PTHREAD_MUTEX_NORMAL type, it can reduce the difficulty of debugging. The initialization of the mutex is synchronized with the creation of the shared memory layer (completed in step S15), and is bound to the shared memory layer, ensuring that only legal requests through the service layer interface module can be obtained. Before writing the parameters, the service layer interface module calls the pthread_mutex_lock function to request the mutex: if no other thread holds the lock at this time, the function will return immediately, allowing subsequent write operations; if the lock has been held by other threads, the current thread will enter a blocked state until the lock is released (avoid busy waiting and occupy CPU resources). For example, when the service layer two applications simultaneously issue "control period" and "PDO mapping" parameters, the thread that initiates the request first acquires the mutex lock and performs writing, and the thread that initiates the request later needs to wait for the previous thread to release the lock before executing, avoiding the overlap or overwrite of the two parameters in the configuration information area, ensuring that each write is a complete and independent operation.
[0076] Then is "write the configuration parameters passed the verification to the configuration information area of the shared memory layer", which can accurately write the legal parameters to the specified area of the shared memory layer, provide data carriers for the control layer to read the configuration, and is the core execution link of the configuration issuance. In terms of technical implementation, the service layer interface module directly accesses the corresponding address of the configuration information area of the shared memory layer through the virtual address of memory mapping - the address layout of the configuration information area needs to be planned in advance, and dedicated address segments are allocated for different types of configuration parameters (such as control cycle parameters stored in the starting address + 0 to + 3 bytes of the configuration information area, and PDO mapping parameters stored in + 4 to + 255 bytes), the address segment division rule is consistent with the partition layout of step S13, ensuring that the control layer can read according to the fixed address. When writing, the data value needs to be stored in the corresponding address according to the parameter format. At the same time, in order to facilitate the control layer to identify new parameters, the "parameter update flag" (such as a 1-byte field, 0x00 indicates no update, and 0x01 indicates new parameters) of the configuration information area needs to be updated after writing, which will trigger the configuration monitoring logic of the control layer (the control layer reads the flag at a fixed period, and reads new parameters when 0x01 is found). For example, in the numerical control machine tool scene, the service layer issues the parameter "spindle speed upper limit = 3000 rpm", step S53 writes the parameter in 4-byte integer format to +20 to +23 bytes of the configuration information area, and sets the parameter update flag to 0x01. After the control layer reads the flag, it will read the new parameter from the corresponding address and update the spindle control logic.
[0077] Then, "update configuration version identification and check information" is followed, which can add "version label" and "integrity check value" to the configuration parameters, so as to identify whether the parameters are updated or damaged by the control layer, and to ensure the reliability of the parameter transmission from the shared memory layer to the control layer. In terms of technical implementation, first, the configuration version identification is updated: the version identification is a 2-byte integer, stored in the fixed address (such as the end +4094 to +4095 bytes) of the configuration information area, and the version number is increased by 1 (such as from 0x0001 to 0x0002) after writing new parameters each time. The control layer can quickly determine whether there are new parameters (if the version numbers are different, the new parameters are read) by comparing the version number with the old version number stored by itself, so as to avoid repeatedly reading the parameters that are not updated. Secondly, the check information is updated: the check value of all parameters (except the check value itself) in the configuration information area is calculated by using the CRC32 algorithm, and is stored in the 4-byte field (such as +4090 to +4093 bytes) at the end of the configuration information area. The check value is consistent with the CRC check logic in the S45 step, and the control layer will recalculate the CRC value after reading the parameters and compare it with the stored check value. If they are inconsistent, it is determined that the parameters are damaged, and the use is refused. For example, the total length of the parameters in the configuration information area is 4090 bytes, the CRC32 value of the 4090 bytes is 0x12345678, which is written into +4090 to +4093 bytes. If the CRC value calculated by the control layer after reading is consistent with the value, the parameter update will be performed, and it is ensured that the parameters are not damaged during the storage in the shared memory layer.
[0078] Finally, it is to "release the mutex and read the confirmation flag of the system state area to verify whether the write is successful, if it fails, retry until the maximum number of retries", this step can release the concurrent resource, at the same time verify whether the control layer successfully receives the configuration parameter, compensate for the occasional write failure through the retry mechanism, and ensure the closed loop of configuration delivery. In terms of technical implementation, the service layer interface module first calls the pthread_mutex_unlock function to release the mutex, allowing other threads to acquire the lock to perform subsequent write operations. After releasing, the mutex returns to the available state, avoiding resource leakage caused by long-term occupation. Subsequently, the confirmation flag of the shared memory layer system state area is read - this confirmation flag is updated by the control layer after successfully reading and executing the configuration parameter. It is a 2-byte field, with a value of 0x0000 (not confirmed), 0x0001 (write success), or 0xFFFF (write failure, such as parameter damage or address error). The address of the confirmation flag and the update logic are determined during the initialization in step S15. The service layer interface module will periodically read the confirmation flag (the reading interval is set to 10 ms, taking into account real-time performance and resource consumption). If 0x0001 is read within the preset timeout time (such as 100 ms), it is determined that the write is successful, and the service layer application is returned with success information. If 0xFFFF is read or 0x0001 is not read within the timeout, it is determined that the write has failed, triggering the retry process. The maximum number of retries of the retry mechanism is set to 3 (which can be adjusted according to system requirements), with a 10 ms interval between each retry. During the retry, steps S52 to S55 (reacquiring the mutex, writing the parameter, and verifying the result) need to be executed again. If all three retries fail, an error message is returned to the service layer application and a log is recorded (such as "configuration parameter pdo_mapping write failed, 3 retries failed to receive confirmation flag"), facilitating the troubleshooting of the operation and maintenance personnel (such as checking whether the control layer is running normally and whether the shared memory address mapping is correct). For example, in the intelligent warehouse scenario, the service layer delivers the parameter "conveyor_speed=500mm / s". After the first write, the control layer temporarily occupies the CPU and does not update the confirmation flag in time. The service layer interface module triggers the retry, and after the second write, the control layer successfully updates the confirmation flag to 0x0001, ensuring that the conveyor runs at the new speed, avoiding configuration failure due to occasional delays.
[0079] In summary, this scheme improves the illegal parameter interception rate through effectiveness verification, avoids control layer abnormalities from the source; completely eliminates data conflicts in multi-thread concurrent writing through mutex, and improves concurrent safety to industrial standard; increases the success rate of configuration delivery through the confirmation flag and the retry mechanism, while avoiding configuration inconsistency problems. In the industrial automation scenario, this can ensure that the service layer's configuration delivery to the control layer is safe and reliable, with traceability, reducing the risk of equipment failure and production downtime caused by configuration errors, and reducing the workload of operation and maintenance personnel.
[0080] As Figure 2 shown, the application also provides an EtherCAT control layer and service layer data synchronization system based on shared memory, comprising: a shared memory layer module, configured to dynamically create a shared memory layer according to EtherCAT network configuration and the number of slaves, the shared memory layer being divided into a system state area, a slave state area, a PDO data area and a configuration information area; a control layer interface module, configured to let the control layer interface module read PDO data of slaves and state data of slaves from an EtherCAT master station in each control cycle through a real-time thread, and write the PDO data of slaves and the state data of slaves directly into the PDO data area and the slave state area of the shared memory layer through memory mapping for zero-copy writing, while updating the timestamp and synchronization flag of the system state area; a service layer first module, configured to let the service layer interface module read device data in the PDO data area and the slave state area of the shared memory layer through memory mapping, and convert the binary device data into JSON format for use by the service layer, while establishing a local cache to reduce shared memory access frequency, the device data including PDO data of slaves and state data of slaves; a service layer second module, configured to let the service layer interface module calculate the difference between the device data reading time and the timestamp of the system state area in the shared memory layer, and if the difference exceeds a preset synchronization threshold, determine that the device data is expired, trigger re-reading, and verify data integrity through CRC check; a service layer third module, configured to let the service layer interface module use a mutex to ensure atomic writing when writing configuration parameters to the configuration information area of the shared memory layer, and verify whether the writing is successful by reading the confirmation flag of the system state area, and if not, retry until the maximum number of retries.
[0081] In one embodiment of the application, the control layer interface module comprises: a configuration unit, configured to configure the real-time execution environment of the control layer interface module, including setting a real-time scheduling strategy and processor binding; a data acquisition unit, configured to acquire PDO data of slaves through an EtherCAT communication protocol at the beginning of each control cycle, the PDO data including input PDO data and output PDO data; a state monitoring unit, configured to acquire state data of slaves through an EtherCAT master station interface function, the state data of slaves including at least the online state and AL state code of slaves; The data writing and state updating unit is configured to write the PDO data into the PDO data area of the shared memory layer through memory mapping, and write the state data of the slave station into the slave station state area of the shared memory layer, and update the device state information of the slave station state area in the shared memory layer. The synchronization updating unit is configured to update the data timestamp and the synchronization state identifier in the system state area of the shared memory layer.
[0082] The application further provides a computer device comprising a memory and a processor, and the memory stores a computer program.
[0083] The application further provides a computer readable storage medium, which stores a computer program.
[0084] It should be noted that, in the present document, the terms "comprise", "contain" or any other variants thereof are intended to cover non-exclusive inclusion, so that a process, device, article or method comprising a series of elements not only includes those elements, but also includes other elements not explicitly listed or inherent to such a process, device, article or method. Without more limitations, the element defined by the statement "comprising a" does not exclude the presence of other identical elements in the process, device, article or method comprising the element.
[0085] The above description is only preferred embodiments of the application, and does not limit the patent scope of the application, and any equivalent structure or equivalent process transformation obtained by using the content of the specification and drawings, or direct or indirect application in other related technical fields, are also included in the patent protection scope of the application.
Claims
1. A shared memory-based EtherCAT control layer and service layer data synchronization method, characterized in that, The method comprises the following steps: According to the EtherCAT network configuration and the number of slaves, a shared memory layer is dynamically created, which is divided into a system state area, a slave state area, a PDO data area and a configuration information area; The control layer interface module reads the PDO data and state data of the slaves from the EtherCAT master station in each control cycle through real-time threads, and directly writes the PDO data and state data of the slaves into the PDO data area and slave state area of the shared memory layer through memory mapping for zero-copy writing, while updating the timestamp and synchronization flag of the system state area; The service layer interface module reads the device data in the PDO data area and slave state area of the shared memory layer through memory mapping, and converts the binary device data into JSON format for use by the service layer, while establishing a local cache to reduce shared memory access frequency, the device data including the PDO data and state data of the slaves; The service layer interface module calculates the difference between the device data reading time and the timestamp of the system state area in the shared memory layer, and if the difference exceeds a preset synchronization threshold, it is determined that the device data is expired, triggering re-reading, and verifying data integrity through CRC check; When writing configuration parameters to the configuration information area of the shared memory layer, the service layer interface module uses a mutex to ensure atomic writing, and verifies whether the writing is successful by reading the confirmation flag of the system state area, and if it fails, it retries until the maximum number of retries.
2. The method of claim 1, wherein the method is characterized by, The step of dynamically creating a shared memory layer according to the EtherCAT network configuration and the number of slaves comprises: According to the number of EtherCAT slaves and the data type, the total capacity of the shared memory layer is calculated; Call the shared memory interface provided by the operating system to create the physical carrier of the shared memory layer, and set the access permission to read and write for the control layer and the service layer; According to the preset partition layout, the internal structure of the shared memory layer is configured, and the address space is divided in the order of system state area, slave state area, PDO data area and configuration information area; Map the shared memory layer to the address space of the control layer and the service layer to establish a direct access channel; Initialize the initial state values of the system state area, slave state area, PDO data area and configuration information area in the shared memory layer, including setting the synchronization flag of the system state area to an unsynchronized state.
3. The method of claim 1, wherein the method is characterized by, The step of the control layer interface module reading the PDO data and state data of the slaves from the EtherCAT master station in each control cycle through real-time threads, and directly writing the PDO data and state data of the slaves into the PDO data area and slave state area of the shared memory layer through memory mapping for zero-copy writing, while updating the timestamp and synchronization flag of the system state area, comprises: Configure the real-time execution environment of the control layer interface module, including setting the real-time scheduling strategy and processor binding; At the beginning of each control cycle, PDO data of the slave station is obtained through the EtherCAT communication protocol, the PDO data including input PDO data and output PDO data; State data of the slave station is obtained through an EtherCAT master station interface function, the state data of the slave station including at least an online state and an AL state code of the slave station; The PDO data is directly written into a PDO data area of the shared memory layer through memory mapping, and the state data of the slave station is written into a slave station state area of the shared memory layer, device state information in the slave station state area of the shared memory layer being updated; Data time stamps and synchronization state identifiers are updated in a system state area of the shared memory layer.
4. The method of claim 1, wherein the method is characterized in that, The step of reading device data in the PDO data area and the slave station state area of the shared memory layer through memory mapping by the service layer interface module and converting the binary device data into a JSON format for use by the service layer, while establishing a local cache to reduce shared memory access frequency, comprises: establishing a memory mapping connection between the service layer interface module and the shared memory layer; obtaining device data from the PDO data area and the slave station state area of the shared memory layer according to a preset reading strategy; performing parsing processing on the device data and converting the device data into an internal data structure; converting the parsed device data into a structured data format suitable for the service layer; providing the processed device data to the service layer application through a data interface and updating the local cache.
5. The method of claim 1, wherein the method is characterized by, The step of calculating, by the service layer interface module, a difference between a device data reading time and a time stamp in the system state area of the shared memory layer, determining that the device data is expired if the difference exceeds a preset synchronization threshold, triggering re-reading, and verifying data integrity through CRC checking, comprises: obtaining the time stamp of data update from the system state area of the shared memory layer; obtaining the device data reading time and calculating the difference between the device data reading time and the time stamp; comparing the difference with the preset synchronization threshold to determine data timeliness; when the difference exceeds the synchronization threshold, determining that the device data is expired, triggering the process of re-reading the device data; verifying the integrity of the read device data through CRC checking, recording synchronization exception conditions and triggering an alarm mechanism.
6. The method of claim 1, wherein the method is characterized by, The step of, when writing configuration parameters into a configuration information area of the shared memory layer by the service layer interface module, using a mutex to ensure atomic writing, and verifying whether the writing is successful by reading a confirmation flag of the system state area, retrying if the writing fails until a maximum number of retries, comprises: receiving configuration parameters sent by the service layer application and performing parameter validity verification; obtaining a mutex of the shared memory layer to ensure the atomicity of writing of the configuration parameters; writing the verified configuration parameters into the configuration information area of the shared memory layer; updating a configuration version identifier and verification information; releasing the mutex and reading the confirmation flag of the system state area, determining that the writing is successful if the confirmation flag is 1, and retrying if the writing fails until a maximum number of retries.
7. A shared memory-based EtherCAT control layer and service layer data synchronization system, characterized in that, comprises: The shared memory layer module is configured to dynamically create a shared memory layer according to an EtherCAT network configuration and a number of slave stations, and the shared memory layer is divided into a system state area, a slave station state area, a PDO data area, and a configuration information area; The control layer interface module is configured to read, by a real-time thread, PDO data of the slave stations and state data of the slave stations from the EtherCAT master station in each control cycle, and write the PDO data of the slave stations and the state data of the slave stations into the PDO data area and the slave station state area of the shared memory layer through memory mapping for zero-copy writing, while updating a timestamp and a synchronization flag of the system state area; The service layer first module is configured to read device data in the PDO data area and the slave station state area of the shared memory layer by the service layer interface module through memory mapping, and convert the binary device data into JSON format for use by the service layer, while establishing a local cache to reduce shared memory access frequency, and the device data includes the PDO data of the slave stations and the state data of the slave stations; The service layer second module is configured to calculate, by the service layer interface module, a difference between a device data reading time and the timestamp of the system state area in the shared memory layer, and if the difference exceeds a preset synchronization threshold, determine that the device data is expired, trigger re-reading, and verify data integrity through CRC checking; The service layer third module is configured to use a mutex to ensure atomic writing when writing configuration parameters into the configuration information area of the shared memory layer by the service layer interface module, and verify whether the writing is successful by reading an acknowledgement flag of the system state area, and if not, retry until a maximum number of retries.
8. The shared memory based EtherCAT control layer and service layer data synchronization system according to claim 7, wherein, The control layer interface module includes: A configuration unit is configured to configure a real-time execution environment of the control layer interface module, including setting a real-time scheduling strategy and processor binding; A data acquisition unit is configured to acquire PDO data of the slave stations by an EtherCAT communication protocol at the beginning of each control cycle, and the PDO data includes input PDO data and output PDO data; A state monitoring unit is configured to acquire state data of the slave stations by an EtherCAT master station interface function, and the state data of the slave stations at least includes an online state and an AL state code of the slave stations; A data writing and state updating unit is configured to directly write the PDO data into the PDO data area of the shared memory layer through memory mapping, and write the state data of the slave stations into the slave station state area of the shared memory layer, and update device state information of the slave station state area in the shared memory layer; A synchronization updating unit is configured to update a data timestamp and a synchronization state identifier in the system state area of the shared memory layer. 9.A computer device, comprising a memory and a processor, wherein the memory stores a computer program, and the computer device is configured to perform the method according to any one of claims 1-8 when the computer program is executed by the processor. The processor implements the steps of the method of any one of claims 1 to 6 when executing the computer program.
10. A computer-readable storage medium having stored thereon a computer program, characterized in that, The computer program is executed by the processor to implement the steps of the method of any one of claims 1 to 6.