Mcp2515 can controller virtual simulation and integration method and system for hardware-in-the-loop test

By constructing a virtual simulation model of the MCP2515_CAN controller and a virtual CAN bus middleware, the high cost and compatibility issues of traditional hardware-in-the-loop testing are solved, enabling flexible system integration and efficient cross-platform testing.

CN121050413BActive Publication Date: 2026-02-06VISION MICROSYST (SHANGHAI) CO LTD
View PDF 3 Cites 0 Cited by

Patent Information

Application Number
CN202511587037.3
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-10-31
Publication Date
2026-02-06
Estimated Expiration
2045-10-31

AI Technical Summary

Technical Problem

Traditional hardware-in-the-loop testing methods rely on real hardware, resulting in high costs and complexity, making it difficult to achieve flexible system integration and verification, especially in scenarios involving multi-node collaborative simulation and complex network topology construction. Furthermore, there are compatibility barriers between testing software from different vendors.

Method used

By constructing a virtual simulation model of the MCP2515_CAN controller, including a register model, CAN protocol layer, and host simulation interface, and utilizing virtual CAN bus middleware and DDS protocol, the software-based operation of the controller logic and multi-node collaborative simulation are realized, supporting interconnection with third-party testing tools.

Benefits of technology

It reduces hardware costs and maintenance complexity, improves system flexibility and scalability, achieves seamless cross-platform integration and efficient testing, and solves compatibility barriers in traditional methods.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121050413B_ABST
    Figure CN121050413B_ABST
Patent Text Reader

Abstract

The application provides a MCP2515_CAN controller virtual simulation and integration method for hardware-in-the-loop test, comprising the following steps: constructing a MCP virtual model; constructing a virtual CAN bus; constructing an external interface; creating independent events for the MCP virtual model, and realizing asynchronous data transceiving and interrupt processing by using an event triggering mechanism; and integrating the MCP virtual model, the virtual CAN bus and the external interface in a unified simulation environment. The application solves the technical problems of traditional controller communication test, such as high cost, complex debugging and poor compatibility.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The present application relates to the field of computer hardware virtualization, in particular, to a MCP2515_CAN controller virtual simulation and integration method and system for hardware-in-the-loop testing. BACKGROUND

[0002] In the development and testing of distributed control and embedded communication systems, controller communication often relies on specific hardware chips and physical bus environments, which limits the system integration and verification process. Traditional testing methods require real hardware to implement SPI register interaction and CAN communication protocol verification, which not only increases hardware costs and debugging complexity, but also limits the flexible expansion of the testing environment. Especially in the context of multi-node collaborative simulation and complex network topology construction, the traditional method is difficult to efficiently reproduce the real communication environment due to the influence of the number of physical connections and network bandwidth. In addition, the interface standards between current testing systems are not unified, and different manufacturers' testing software uses closed protocols, causing compatibility barriers between third-party tools, hindering system cascade debugging and cross-platform collaboration.

[0003] To solve the above problems, a MCP2515_CAN controller virtual simulation and integration method for hardware-in-the-loop testing is proposed. This method simulates SPI registers and CAN protocol layers to realize the pure software operation of controller logic and break away from the dependence on physical chips. It uses virtual CAN bus middleware to simulate real network communication, supports multi-node collaborative simulation and complex topology construction, and realizes interconnection and intercommunication with third-party testing tools based on DDS protocol communication channels, thereby significantly improving the flexibility, expandability and compatibility of the system.

[0004] A Chinese patent with application number CN202411810280.2 discloses a CAN network virtualization method, system, device and medium. This patent simulates CAN hardware through QEMU virtual machines, establishes a virtual CAN network, and connects virtual nodes using KvaserVirtualCANDriver drivers to realize simulation and operation of virtual CAN hardware nodes. However, it does not involve MCP simulation, and there is a significant difference in technical means compared to the present application. SUMMARY

[0005] To overcome the defects in the prior art, the present application aims to provide a MCP2515_CAN controller virtual simulation and integration method and system for hardware-in-the-loop testing.

[0006] According to one aspect of the present invention, a virtual simulation and integration method for an MCP2515_CAN controller oriented to hardware-in-the-loop testing is provided, characterized by comprising: Step 1: constructing an MCP virtual model; Step 2: constructing a virtual CAN bus; Step 3: constructing an external interface; Step 4: creating independent events for the MCP virtual model and using an event triggering mechanism to realize asynchronous data transmission and reception and interrupt handling; Step 5: integrating the MCP virtual model, the virtual CAN bus, and the external interface into a unified simulation environment.

[0007] Preferably, step one, constructing the MCP virtual model, includes: constructing a register model, wherein the register model is used for: parsing read and write instructions of the SPI standard through functions, and executing the chip select signal of GPIO through functions; constructing a simulated CAN protocol layer, wherein the simulated CAN protocol layer executes the following through functions: sending: parsing the contents of the transmit buffer based on the data and write timing signals written by the MCU through the SPI interface, and generating corresponding virtual CAN frames for sending according to preset GPIO control signals; receiving: filtering and processing the input frames received from the virtual CAN bus based on preset shielding and filtering rules; interrupting: setting an interrupt flag and issuing an interrupt signal according to the event triggering mechanism after completing the data sending or receiving operation; and constructing a host simulation interface, wherein the host simulation interface includes an SPI simulation interface and a GPIO simulation interface.

[0008] Preferably, the SPI emulation interface is used for data communication between the MCP virtual model and the MCU, wherein the data communication between the MCP virtual model and the MCU includes: the MCP virtual model receiving a write instruction from the MCU register and writing the SP value into the virtual register model; the MCP virtual model receiving a read instruction from the MCU register, reading the corresponding register value from the virtual register model and returning it to the MCU.

[0009] Preferably, the GPIO emulation interface is used for signal communication between the MCP virtual model and the MCU: the signal communication between the MCP virtual model and the MCU includes: the MCP virtual model receiving the chip select enable signal from the MCU; the MCP virtual model triggering an interrupt event after data transmission or reception is completed, and feeding back the interrupt notification signal to the MCU.

[0010] Preferably, the independent events include: Event 1: parsing or responding to SPI commands; Event 2: receiving or sending CAN data frames; Event 3: monitoring and notifying of interrupt status.

[0011] Preferably, the external interface is a DDS interface, wherein the DDS interface is used for: encapsulating virtual CAN frames into DDS data packets and sending them to the test software; parsing the DDS packets from the test software and restoring them into CAN frames for input to the virtual CAN.

[0012] Preferably, in the step five, the MCP virtual model and the virtual CAN bus are integrated in a unified simulation environment, comprising: connecting the MCP virtual model with the MCU through an SPI simulation interface; constructing an independent simulation node, and making the virtual CAN bus interact with a third-party test tool through the independent simulation node and a DDS interface; and distributing CAN node data through the virtual CAN bus, and communicating with a plurality of opposite nodes.

[0013] According to another aspect of the present application, a MCP2515_CAN controller virtual simulation and integration system for hardware-in-the-loop testing is provided, characterized in that, comprising: module M1: constructing a MCP virtual model; module M2: constructing a virtual CAN bus; module M3: constructing an external interface; module M4: creating an independent event for the MCP virtual model, and realizing asynchronous data transmission and reception and interrupt processing by using an event triggering mechanism; and module M5: integrating the MCP virtual model, the virtual CAN bus and the external interface in a unified simulation environment.

[0014] Preferably, the module M1 comprises: a sub-module M1: constructing a register model, wherein the register model is used for: executing instruction analysis of SPI standard reading and writing by a function, and executing chip selection signal of GPIO by a function; a sub-module M2: constructing a simulation CAN protocol layer, wherein the simulation CAN protocol layer is used for: transmitting: analyzing buffer content according to data in a transmission buffer written by the MCU through an SPI interface and a writing time sequence signal thereof, and generating a corresponding virtual CAN frame for transmission according to a preset GPIO control signal; receiving: screening and processing input frames received from the virtual CAN bus based on preset screening and filtering rules; and interrupting: setting an interrupt flag and issuing an interrupt signal according to an event triggering mechanism after completing data transmission or reception operation; and a sub-module M3: constructing a host simulation interface, wherein the host simulation interface comprises an SPI simulation interface and a GPIO simulation interface, wherein the SPI simulation interface is used for data communication between the MCP virtual model and the MCU, and the data communication between the MCP virtual model and the MCU comprises: the MCP virtual model receiving a register writing instruction from the MCU, and writing an SPI value into a virtual register model; and the MCP virtual model receiving a register reading instruction from the MCU, and reading a corresponding register value from the virtual register model and returning to the MCU; and the GPIO simulation interface is used for signal communication between the MCP virtual model and the MCU, and the signal communication between the MCP virtual model and the MCU comprises: the MCP virtual model receiving a chip selection enable signal of the MCU; and the MCP virtual model triggering an interrupt event after completing data transmission or reception, and feeding back an interrupt notification signal to the MCU.

[0015] Preferably, the independent events include: event one: resolving or responding to SPI instructions; event two: receiving or sending CAN data frames; event three: monitoring and notifying interrupt status.

[0016] Compared with the prior art, the application has the following beneficial effects:

[0017] 1. By constructing a virtual simulation model based on SPI registers and CAN protocol layers, the complete software operation of the controller logic is realized, and the strong dependence on physical chips and hardware connections in traditional testing is broken. The scheme enables the standard SPI driver to directly drive the virtual controller for data interaction, thereby significantly reducing the hardware cost and maintenance complexity, and providing an efficient means for early system verification and cross-platform development

[0018] 2. An extensible communication network model is constructed by using a virtual CAN bus middleware, which can simulate the frame scheduling, arbitration and forwarding mechanism of the real bus in the host environment. The middleware supports the access of any number of virtual nodes and parallel communication of multiple nodes, effectively solving the limitations of traditional physical buses in cooperative testing, fault injection and complex topology construction, and significantly improving the flexibility and scalability of the system.

[0019] 3. A standardized communication interface with third-party testing tools is realized through a DDS protocol conversion channel, supporting data intercommunication of different testing platforms (such as CANoe, dSPACE, VeriStand, etc.). This mechanism breaks down the compatibility barriers between heterogeneous tools, realizes seamless integration of the virtual simulation system and the external testing environment, and provides a general and efficient solution for cross-platform joint testing and distributed system verification. BRIEF DESCRIPTION OF DRAWINGS

[0020] Other features, objects and advantages of the application will become more apparent after reading the detailed description of non-limiting embodiments with reference to the following drawings:

[0021] Figure 1 Flow chart of the MCP2515_CAN controller virtual simulation and integration method for hardware-in-the-loop testing;

[0022] Figure 2 Schematic diagram of the integration method;

[0023] Figure 3 Schematic diagram of data and signal processing by the virtual MCP model. DETAILED DESCRIPTION

[0024] The application will be described in detail below with specific examples. The following examples will help those skilled in the art to further understand the application, but do not limit the application in any form. It should be noted that those skilled in the art can make several changes and improvements without departing from the concept of the application. These are within the scope of the present application.

[0025] For the convenience of understanding, the terms or concepts involved in the present application are explained as follows:

[0026] (1) Register model

[0027] The register model refers to the establishment of a storage structure corresponding to the hardware registers of the MCP2515 controller in the software, which is used to simulate the read-write operation, bit modification and reset behavior of the registers, so as to realize consistent register access logic with the real chip in the virtual environment.

[0028] (2) SPI simulation interface

[0029] The SPI simulation interface is a software module in the host environment that simulates the communication behavior of the serial peripheral interface, which is used to realize data interaction between the virtual controller and the host unit, and supports the analysis and response of standard SPI instructions.

[0030] (3) GPIO simulation interface

[0031] The GPIO simulation interface is used to transmit the chip select signal and the interrupt signal between the virtual controller and the host unit, simulating the control and notification mechanism of the physical pins in the MCP2515 chip.

[0032] (4) Simulation CAN protocol layer

[0033] The simulation CAN protocol layer refers to the CAN communication protocol logic implemented in software, which is used to generate, receive and process virtual CAN frames, and perform frame filtering, arbitration, error management and other link layer functions.

[0034] (5) Virtual CAN bus middleware

[0035] The virtual CAN bus middleware is a software component in the host environment that is used to realize data transmission and management between multiple virtual nodes, responsible for frame forwarding, broadcast distribution, arbitration and link layer behavior simulation.

[0036] (6) Simulation node

[0037] The simulation node is a logical unit located in the host environment, which is used to perform data encapsulation, analysis and routing between the virtual CAN bus and the DDS interface, realizing protocol conversion and bidirectional communication.

[0038] (7) DDS interface

[0039] The DDS interface is a communication channel based on the data distribution service protocol, and is used to realize data publishing, subscribing and distributing between the host environment and external test tools, and to realize external interconnection of the virtual system.

[0040] (8) Event mechanism

[0041] The event mechanism is a task triggering and callback framework provided by the host system, and is used to realize real-time response of SPI transactions, CAN sending and receiving and interrupts through event registration and triggering functions to manage asynchronous operations.

[0042] (9) Interrupt event

[0043] The interrupt event refers to a notification action triggered by the virtual controller after completing data sending or receiving, and is used to simulate the interrupt signal of the real hardware, so that the host unit can asynchronously respond to the state change.

[0044] (10) Host environment

[0045] The host environment is a platform environment for running the virtual simulation system, and provides computing resources, event scheduling, interface driving and communication middleware support, so that each software module runs and interacts under a unified framework.

[0046] The application provides a MCP2515_CAN controller virtual simulation and integration method for hardware-in-the-loop testing. The method simulates all hardware logic of the MCP2515 controller in a software manner in the host environment, realizes pure software operation of the controller communication and testing process. By constructing a register model and a CAN protocol layer, the system simulates the register operation and communication behavior of the real chip at the SPI interface layer, completes data reading and writing, sending, receiving and interrupt response. The virtual CAN bus middleware establishes an extensible data transmission channel in the host system, simulates the arbitration and distribution mechanism of the link layer, and realizes real-time communication between multiple nodes. The external interface converts the virtual CAN frame into a standard DDS message based on the DDS protocol, realizes interconnection and intercommunication with third-party test software. The entire system realizes asynchronous data sending and receiving and interrupt processing through the event triggering mechanism, so that the virtual controller has consistent communication characteristics with the physical hardware in the host environment.

[0047] The method will be explained in detail as follows: Figure 1 、 Figure 2 、 Figure 3

[0048] Step 1: Construct the MCP virtual model

[0049] ​In this step, the core goal of building the MCP virtual model is to completely replicate the hardware behavior of MCP2515 controller through pure software, so that it can correctly respond to the SPI communication of the MCU in the simulation environment. The virtual model is composed of register model, CAN protocol simulation layer and host simulation interface, which are coupled through a unified event system and data bus to form a complete controller simulation structure. The model not only needs to have consistent register access mechanism with the real chip, but also needs to be able to simulate communication timing, interrupt triggering and protocol state change, so as to realize the verifiable and extensible controller behavior at the software level.

[0050] The register model is the basic part of the MCP virtual controller, which is used to accurately map the address and function of the hardware register. The system defines a global register set to store core information such as control registers, status registers, sending and receiving buffers, and filtering and masking registers. Each register is organized in the form of a structure, and the address and register domain are corresponded through a mapping table. On this basis, the system implements the standard SPI instruction set of MCP2515, including READ, WRITE, BITMODIFY, RESET, READSTATUS, etc. Each instruction is parsed as a specific read-write operation on the register model when executed, and the status register and interrupt flag are updated according to the operation result. For example, when the MCU writes a sending request through SPI, the system will automatically trigger the construction and sending event of the CAN frame, and update the status bit after the task is completed. To ensure timing consistency, the register model internally implements state machine logic to control the transition between the RESET, CONFIG, NORMAL, SLEEP, LOOPBACK and other running states of the controller. State changes can be triggered by SPI commands or event-driven, so as to realize the same workflow as the real hardware.

[0051] The CAN protocol simulation layer is responsible for frame sending, receiving and interrupt management. In terms of sending logic, when the MCU writes frame data into the sending buffer, the system will parse and generate the corresponding CAN data frame according to the register content, and submit it through the virtual CAN bus interface function. The receiving logic receives frame data from the virtual bus and performs filtering and masking comparison, and only when the identifier matches the current controller configuration will the frame be stored in the receiving buffer and the receiving flag bit will be updated. In terms of interrupt mechanism, when frame sending is completed, a new frame is received or an error occurs, the model will set the corresponding bit flag through the interrupt flag register and trigger the interrupt event, and finally send an interrupt signal to the host MCU through the GPIO simulation interface. This mechanism ensures that the simulation controller is consistent with the real hardware in terms of event triggering, timing response and state feedback.

[0052] The host emulation interface serves as the communication bridge between the virtual model and the MCU, primarily consisting of two parts: the SPI emulation interface and the GPIO emulation interface. The SPI emulation interface is used to parse timing signals, distinguish chip select states, transmit instruction data, and correctly sample data in different SPI modes (such as Mode 0 to Mode 3). This interface simulates the communication process of a real bus, including chip select signal detection, byte-level transmission, and return data feedback. The GPIO emulation interface is responsible for interrupt and chip select signal management: when the MCU pulls the chip select signal low, the SPI module begins communication; after communication ends, if the interrupt condition is met, the GPIO module immediately triggers an interrupt event and feeds it back to the MCU, thus forming a complete hardware-software level interactive closed loop.

[0053] To ensure the accuracy and stability of the model, the system incorporates several verification mechanisms during implementation. A register self-test module checks the correctness of the register mapping table during initialization; the SPI instruction replay mechanism verifies timing consistency by comparing simulation and real hardware waveforms; and protocol conformance testing uses a standard CAN test frame set to verify the sending and receiving logic. Furthermore, to enhance the realism of the simulation, the system can insert adjustable delays based on bus load and baud rate to simulate hardware transmission delays and congestion characteristics. These designs collectively ensure that the MCP virtual model possesses high simulation accuracy, adjustability, and stability.

[0054] In summary, the MCP virtual model implements the underlying control logic through a register model, simulates communication behavior through a protocol layer, and achieves external communication through a host interface. This enables the entire system to accurately simulate the complete operation of the MCP2515 controller without hardware intervention. This model not only provides a reliable foundation for subsequent virtual CAN bus and DDS external interface development but also offers crucial simulation capabilities for hardware-in-the-loop (SIL / HIL) testing, significantly improving the development and verification efficiency of communication systems.

[0055] Step 2: Construct a virtual CAN bus

[0056] The goal of this step is to construct a virtual CAN bus system that accurately simulates the communication, arbitration, and error handling behavior of a real CAN bus in a software environment. The virtual CAN bus is the communication core of the entire simulation platform, responsible for broadcasting and distributing data frames and simulating the link layer among multiple MCP virtual nodes. By designing virtual middleware and standardized interfaces, the system can reproduce the multi-node communication characteristics, arbitration logic, and error recovery mechanisms of a CAN network under pure software conditions, thus providing complete simulation support for protocol verification, node interaction, and system integration.

[0057] The first part of the virtual CAN bus is the data distribution mechanism. This mechanism is responsible for forwarding CAN frames between multiple nodes, ensuring the broadcast nature and arbitration order of frame transmission. When any node sends a data frame through the virtual MCP model, the bus middleware will capture the frame and perform a distribution operation according to its identifier (ID) and node configuration. The system uses a message queue structure to manage all transmission tasks in the bus, and each frame enters the queue to wait for arbitration. The arbitration mechanism is based on the priority of the frame ID: the smaller the ID value, the higher the priority. If multiple nodes are detected to request transmission at the same time, the bus will select the winning node according to the ID priority, and its frame will be normally broadcast, while other nodes automatically enter the retransmission waiting state. This mechanism not only conforms to the bus arbitration rules of the CAN protocol, but also ensures the data consistency and transmission timing certainty in a multi-node environment.

[0058] To further enhance the simulation realism, the system builds a link layer simulation module based on the data distribution mechanism. This module simulates the actual CAN bus behavior characteristics at the physical and link layers through algorithms, including collision detection, error counting, and automatic recovery logic. Specifically, when a node detects a bit conflict or an error frame during transmission, the system will immediately update the error counter and trigger the corresponding error state, such as "error active," "error passive," or "bus off" mode. In the error recovery phase, the system will periodically detect the bus idle state and reactivate the node when the recovery conditions are met, allowing it to participate in communication again. In addition, link layer simulation can also simulate underlying behaviors such as bit stuffing, acknowledgement bit, CRC check, etc., to ensure that frame transmission in the simulation environment conforms to the real CAN protocol standard. Through these mechanisms, the virtual CAN bus not only has high fidelity protocol consistency, but also can reproduce common anomalies and recovery processes in multi-node communication.

[0059] In terms of system architecture, the implementation of the virtual CAN bus relies on a bus middleware (CANBusMiddleware) as the communication hub for all nodes. The middleware provides standardized sending and receiving interfaces, such as CAN_TxFrame() and CAN_RxFrame(), for managing frame flow between different nodes. Each MCP virtual node interacts with the bus by calling these interfaces, while the middleware internally maintains a centralized message queue and event scheduler to achieve ordered scheduling of data flow. Through multi-threading mechanisms, the middleware can handle multiple node transmission and reception requests simultaneously, supporting multi-node parallel operation. To ensure thread safety and real-time response, the system uses semaphores and mutexes to manage access control, avoiding data race or timing disorder problems in high concurrency states. In addition, the message queue structure supports priority scheduling and timestamp marking, allowing the bus to accurately reproduce the communication timing of the real CAN network in simulation.

[0060] Link layer behavior simulation is one of the key features of the virtual bus system. To reflect the physical competition relationship of the CAN network, the system simulates the master-slave logic of signal level in each arbitration process: the master node controls the bus level by sending the dominant bit, while the slave node automatically gives up sending after detecting the coverage. This process is implemented in software with logical operations and time sequence control, which can accurately simulate the conflict detection and priority decision of the bus layer signal. In addition, the system has built-in error detection algorithms to determine whether bit errors, padding errors, CRC errors or acknowledgement errors occur during frame transmission. Once an anomaly is detected, the bus will immediately mark the error source node and update the error counter, while broadcasting an error frame signal to prompt other nodes to enter a waiting state. This mechanism ensures that the CAN network in the virtual environment has complete fault tolerance and recovery characteristics.

[0061] In terms of interface adaptation and expansion, the virtual CAN bus provides modular interface definitions to support flexible topology and multi-node expansion. The standard interface layer includes sending interfaces, receiving interfaces, initialization interfaces, and error callback functions, allowing users to access the bus system through a unified API. To achieve system scalability, the virtual bus middleware supports dynamic registration and deregistration of nodes, allowing developers to add or remove nodes during simulation runtime without restarting the system. In addition, to adapt to different host system architectures, the interface layer design reserves an abstract driver layer that can run compatibly with various concurrent frameworks such as POSIX threads or real-time operating system tasks. This allows the system to be quickly ported and deployed on different development platforms (Windows, Linux, RTOS).

[0062] To verify the correctness and stability of the virtual CAN bus, the system is equipped with various testing and monitoring tools. For example, through the frame logging mechanism, the system can capture all transmission events and output timestamps and node identifiers, facilitating protocol consistency verification by developers; through the simulation monitoring module, users can view bus load, error count, node status, and arbitration success rate in real time, allowing them to evaluate system performance; in addition, the system supports exporting virtual bus data in standard CAN log format (such as.blf or.asc), facilitating cooperation with third-party analysis tools (such as VectorCANalyzer, CANoe). The introduction of these tools makes the virtual bus not only valuable for research and development, but also directly applicable to testing and verification scenarios.

[0063] Overall, the virtual CAN bus implements the data transmission, arbitration control and error recovery mechanism of the real bus at the software level. It provides a highly simulated communication environment for multiple MCP virtual nodes and supports system-level expansion and parallel simulation through standardized interfaces. With this virtual bus system, developers can perform complete CAN network communication testing, protocol verification and debugging analysis without physical hardware, thereby significantly reducing debugging costs and improving development efficiency. This module provides a solid communication foundation for the integration of subsequent DDS external interfaces and software-in-the-loop simulation.

[0064] Step three: Build external interface

[0065] In this step, the goal is to build a DDS (Data Distribution Service) interface as a bridge to the external world, enabling the virtual CAN system to interact with third-party test software or actual test platforms in a highly reliable, low-latency and configurable manner. The overall idea is to deploy a DDS communication layer and an independent protocol bridge node in the host environment: the former provides publish / subscribe and QoS management, and the latter is responsible for format mapping, direction selection and routing control between CAN frames and DDS messages. Through this layered design, the coupling between the virtual bus and external tools is limited to the bridge boundary, the internal simulation logic remains pure and testable, and external integration is decoupled through a standardized topic and type system.

[0066] In terms of DDS data communication, the system defines a dedicated topic namespace and message pattern for the virtual CAN network, such as publishing frames from the virtual bus to the “ / can / bus / out” topic and subscribing external injected test data from the “ / can / bus / in” topic. The message payload contains fields such as timestamp, frame ID (including standard / extended bits), DLC, data area, error flag, node source and bus number, and simulation context information (such as arbitration results or retransmission count) when necessary, to facilitate accurate playback and consistency verification by external tools. Data serialization uses IDL description and CDR encoding, ensuring cross-language / cross-platform interoperability and facilitating field extension without compromising compatibility. The publish / subscribe end is configured with QoS policies such as reliability (Reliable / BestEffort), history depth, keep-alive time and delay budget, allowing scenario switching between “real-time priority” and “completeness priority”.

[0067] The protocol bridge node undertakes the responsibilities of format conversion, path control and traffic management. The original CAN frame output by the virtual bus is mapped into a DDS message and published according to the topic in the bridge node; in the reverse path, the bridge node parses the DDS message and restores it to a virtual CAN frame, and then injects it into the virtual bus for transmission. To adapt to different test topologies, the bridge node provides two transmission mode options: point-to-point and broadcast. The point-to-point mode is suitable for diagnosis and single-node verification, and the broadcast mode is suitable for consistency / robustness testing. The routing control supports filtering based on ID interval, frame type or custom label, avoiding external noise data pollution of the simulation environment, while allowing priority promotion and accelerated forwarding of key frames.

[0068] To meet the requirements of engineering practicability and observability, the DDS interface has built-in end-to-end timestamp and clock alignment mechanism: key points are recorded when the frame enters and leaves the bridge node, and the host monotonic clock or external clock source is combined to realize delay measurement and jitter statistics; if necessary, a time synchronization adaptation layer is supported to map the time base of the external platform to the simulation time axis. To ensure stability in high-load scenarios, the bridge node implements back pressure and buffering strategy: when the external subscriber consumption rate is insufficient or the virtual bus is busy, the system selects a discard policy (such as discarding the oldest or discarding non-key frames according to filtering rules) according to QoS, and publishes congestion alarms and packet loss statistics through diagnostic topics, facilitating immediate parameter tuning by testers. Error channels and exception handling are also explicitly modeled: parsing failures, field out-of-bounds, CRC / inconsistency, no subscriber, etc. will generate diagnostic events with context, supporting automatic degradation and rapid positioning.

[0069] In terms of security and isolation, the DDS interface can enable domain and partition-based naming isolation, combined with white list topics and type checking, to limit the injection range of external data; when needed, identity authentication and data encryption are enabled in combination with security extensions to ensure transmission security during cross-host / cross-network joint debugging. To reduce the degree of binding to specific DDS implementations, the communication layer encapsulates common APIs through adapters, and the bridge node only relies on abstract interfaces to complete publish / subscribe and QoS configuration, making it easy to replace or coexist with multiple implementations between different middleware. In terms of performance, the bridge node uses a lock-free ring queue or a producer / consumer model with minimal lock granularity to implement zero-copy or few-copy data paths; in a multi-core environment, the sending, receiving and serialization pipelines can be bound to cores and memory pools according to CPU affinity and NUMA topology, reducing jitter.

[0070] In terms of testing and verification, the system provides replayable and comparable capabilities: on one hand, it unifies external DDS streams and virtual bus events into time-ordered logs (containing simulation timestamps and real timestamps) and supports filtering replay by interval, ID, or node; on the other hand, it provides golden use cases and consistency checkers to compare the replay results with expected arbitration sequences and error count trajectories, outputting deviation reports and statistical indicators. At the same time, the interface exposes health probes and indicator endpoints (publishing rate, subscription lag, buffer occupancy, packet loss rate, end-to-end delay P50 / P95 / P99) for automatic acceptance and regression monitoring in continuous integration pipelines and long-term stress testing.

[0071] In summary, step three realizes bidirectional intercommunication, controllable routing, and observable operation and maintenance between the virtual CAN system and the external test platform by constructing a DDS communication layer and a protocol bridge node in the host environment. This design not only ensures the engineering balance between real-time performance, reliability, and scalability, but also makes cross-platform integration smoother through standardization of types and QoS, providing a robust external interface foundation for subsequent system-level SIL / HIL joint verification, heterogeneous tool chain integration, and large-scale scenario replay.

[0072] Step four: create independent events and use event-triggered mechanisms to realize asynchronous data transmission and interrupt processing

[0073] In this step, the goal is to build a unified event triggering and scheduling mechanism covering SPI instructions, CAN transmission and interrupt monitoring, so that the virtual system has the engineering capabilities of asynchronous transmission, real-time interrupt response, and predictable timing. The overall design adopts a combination of event-driven architecture and message queue mode: all changes from the MCU, virtual CAN bus, and internal state machine enter the scheduler in the form of events; the scheduler processes events according to priority, timestamp, and resource availability, and drives the register model, protocol stack, and host simulation interface through callbacks or task execution units. To improve realism, the system simulates hardware-level delays (such as SPI clock and bit time, arbitration window, and interrupt propagation delay) in the critical path and presents them as configurable parameters, allowing tests to switch between "ideal link" and "high load / high jitter" scenarios.

[0074] The SPI instruction event takes the MCU chip select as the transaction starting point, and the scheduler creates an "SPI transaction" event and locks the current chip select context after receiving the edge trigger. The event processing flow parses the command bytes, address and data length in time sequence, and maps them to read / write / bit modification operations on the register model; for instructions that cross-register write (such as writing to the TX buffer and setting the request bit), the processing function completes the register update and side effect trigger in the atomic area to avoid read-write competition. To be close to the hardware, the SPI read-write throughput is subject to the simulated SCK frequency and mode (Mode0~3), and in long frame read-write, sub-events are delivered in batches by bytes, so that the returned data presents real time sequence interleaving. For RESET, BITMODIFY and other instructions that have a wide impact, the event processor will push a "state refresh" sub-event at the tail, drive the state machine migration and interrupt flag recalculation, and ensure that the subsequent visible register view is consistent with the real chip.

[0075] CAN transceiver events are triggered by two types of sources: one is the sending path, when the request bit of any TX buffer is set, the scheduler generates a "to-be-sent frame" event, reads the register domain to assemble standard / extended frames and submits to the virtual bus; the second is the receiving path, when the bus middleware distributes the arrival frame, the scheduler generates a "frame arrival" event and performs filtering / masking matching. The sending event will go through arbitration and line-speed transmission simulation after entering the bus, and after completion, the "sending end" event is pushed back to update TXIF, clear the request bit and write the timestamp; the receiving event will write data to the RX buffer and set RXIF when matching is successful, if the buffer is full, it will decide to cover, discard or back to the waiting queue according to the strategy, while recording the overflow count. To ensure predictability in high-concurrency scenarios, the scheduler maintains a priority queue for sending and receiving respectively: the sending queue is sorted by frame ID and entry time, and the receiving queue is dynamically weighted by arrival time and buffer occupancy ratio, so as to meet the CAN priority and avoid long-term starvation of some nodes.

[0076] The interrupt monitoring event is triggered by register flag changes, and conditions such as sending completion, receiving completion, error count transition and mode switching are continuously observed. Once the trigger criteria are met, the scheduler sets the CANINTF corresponding bit in the shortest safe window and pulls up the INT pin through the GPIO emulation interface, and then enters the "interrupt pending" state to wait for the MCU response. In order to reproduce the hardware semantics, the system distinguishes between level triggering and edge sensing behaviors: when the MCU reads the interrupt source and clears the flag, if there are still unprocessed events, the INT level will remain high until all sources are cleared; if multiple sources overlap in a short time, the scheduler merges or splits the interrupt according to the priority table (RX>TX>ERR configurable) to ensure controllable ISR load and stable processing order. In addition, the interrupt path has built-in debounce and minimum width settings to avoid false triggers caused by high-frequency state jitter; in extreme load conditions, if the ISR processing is delayed, the system will enter "back pressure mode" to delay new non-critical interrupts in an observable way and issue diagnostic events.

[0077] In terms of scheduling and concurrency control, the system uses a single-write multi-read register access strategy and fine-grained lock partitioning: the SPI, bus and INT paths each hold their own fast mutex, and cross-domain modifications pass event descriptions through a lock-free ring queue to reduce critical section duration. The scheduler provides both priority preemption and time slice rotation strategies: in high real-time requirement mode, preemption is enabled to allow interrupt monitoring to interrupt low-priority bulk SPI read and write; in throughput-priority bulk processing mode, the time slice strategy is used to improve long transaction efficiency. To ensure timing repeatability, all events carry dual timestamps (emulation clock and host monotonic clock), which are used as the basis for ordering and measurement in playback and comparison tests.

[0078] In terms of performance and reliability, the event system supports rate limiting and back pressure: when the external driver triggers SPI transactions or external DDS injects high-frequency frames at an abnormal rate, the scheduler shapes the enqueue rate according to the water line, prioritizing critical events (interrupts, receptions, error transitions), while merging or discarding low-value repeated reads and writes, and reporting throttling and discard statistics on the diagnostic channel. Error handling follows a hierarchical strategy: recoverable errors (buffer full, CRC check failure) are retried locally or fail fast and counted; non-recoverable errors (invalid address, illegal instruction length) immediately generate error events, mark red related register bits and block subsequent dependent processes to prevent mispropagation. The system provides watchdog monitoring for long-pending critical events (such as pending send completion) and triggers self-healing logic or exports core dump for offline positioning.

[0079] To improve observability and test convenience, the event framework has built-in subscribable tracking streams and metrics: including event in / out queue rate, queue depth, ISR latency distribution (P50 / P95 / P99), interrupt coalescing ratio, buffer overflow count, and retransmission statistics; while supporting the recording of event sequences and register snapshots in time-ordered manner, combined with the playback for deterministic replay. Through the "golden sample" use case library, developers can compare a complete interaction (SPI configuration -> send -> arbitration -> receive -> interrupt clear) with the expected trajectory frame by frame, quickly find the timing deviation or boundary condition vulnerability. Ultimately, this event triggering and scheduling mechanism balances between real-time performance, repeatability, and maintainability, enabling the virtual system to stably reproduce complex asynchronous transmission and interrupt scenarios without physical hardware, providing a solid foundation for driving joint debugging, protocol consistency verification, and stress testing.

[0080] Step five: integration into a unified simulation environment

[0081] In this step, the system will assemble and arrange the MCP virtual model, virtual CAN bus, and DDS external interface in the same simulation framework to form a unified simulation environment that supports SIL / HIL. The overall design follows the principles of "layered decoupling, event unification, time consistency, observability, and replayability": the bottom layer consists of SPI / GPIO I / O adaptation and register / protocol stack to form the controller-side logic, the middle layer implements broadcast and arbitration through virtual CAN middleware, and the upper layer completes cross-platform and third-party tool interconnection through the DDS bridge. The three layers are connected through a unified event dispatcher and message queue, and are managed by the same simulation clock domain and beat. The data flow consists of the forward link from MCU -> SPI simulation -> MCP register / protocol layer -> virtual bus -> multi-node distribution -> DDS bridge -> external tools, and the reverse link from external -> DDS -> bridge -> virtual bus -> target MCP node -> interrupt reporting -> MCU; any change in the status of any link will be eventized and timestamped with double timestamps (simulation clock and host monotonic clock) to ensure traceability and repeatability of the timing of the entire link.

[0082] To ensure timing correctness and system consistency, the unified simulation environment implements multi-module synchronization through a single source time base: the internal tick drives the transmission / reception and ISR window according to the configured bit time, arbitration window, and interrupt propagation delay, the SPI simulation performs transactions at the SCK frequency and mode slice, the virtual bus controls the arbitration order with a priority queue, and the DDS layer aligns with the external endpoint rhythm through the delay budget and history depth of QoS. The system provides three running modes to cope with different scenarios: the deterministic playback mode guarantees complete consistency for each execution with discrete event advancement; the real-time approximation mode anchors the simulation clock to the host monotonic clock for "soft real-time" interaction with hardware or external tools; and the acceleration mode bypasses non-critical delays for regression testing and large-scale scenario benchmarking. To improve robustness, the scheduler supports back pressure and water level control, merging or discarding low-priority frames when the queue approaches the threshold, and publishing congestion and packet loss statistics through the diagnostic channel.

[0083] Unified integration is also reflected in the engineering of configuration and loading processes. The system uses a declarative configuration scheme to describe node topology, baud rate / bit timing, filtering / masking, DDS topics and QoS, log policies and threshold values, etc. After reading the configuration, the launcher initializes I / O adaptation, register default values, event bus, virtual bus, and DDS bridge in turn, and performs self-checking (register mapping verification, SPI loopback, bus arbitration, and DDS loopback). To support HIL, the framework preserves the hardware abstraction boundary at the I / O layer: SPI / GPIO interfaces can be switched to real interface cards or logical probes while maintaining the event and protocol behavior unchanged at the upper layer; for peripheral / sensor data, real sampling streams can be imported through DDS or additional adaptation layers, and closed-loop commissioning with virtual CAN networks can be performed. In terms of security and isolation, the runtime limits the DDS injection range through naming domains / partitions and topic white lists, audits and signature checks critical register access and bridge strategy changes to ensure data integrity during cross-host commissioning.

[0084] In terms of observability and quality assurance, the system incorporates end-to-end tracing, metrics, and fault injection capabilities. The tracing channel records event sequences and register snapshots from MCU instructions to feedback from external tools. The metrics layer provides key performance indicators (KPIs) such as queue depth, end-to-end latency P50 / P95 / P99, arbitration win rate, buffer overflow, retransmission, and error count transitions, triggering alarms with thresholds. Fault injection supports scenarios such as bit errors, arbitration conflicts, bus shutdown, DDS packet loss / out-of-order delivery, SPI jitter, and interrupt suppression, verifying the abnormal handling paths of drivers and upper-layer applications. The test base includes a library of sample test cases and a replay function, enabling frame-by-frame comparison of the path "configuration → send → arbitration → receive → interrupt clearing → external loopback." CI / CD integration automatically runs protocol consistency and performance regression tests after each change, generating reports and difference summaries. For large-scale simulations, the scheduler and bus middleware support multi-process / multi-core sharding and NUMA affinity. Logs employ segmentation and on-demand sampling strategies to reduce I / O interference. The resource management layer performs quota and leak detection on memory pools, circular queues, and object caches to ensure long-term stable operation.

[0085] The final unified simulation environment ensures reproducible communication behavior, scalable topology, and verifiable protocols, while providing high compatibility and observability for seamless integration with external tools. Development teams can complete driver integration and protocol consistency testing without physical hardware, and smoothly transition to HIL when some hardware is integrated. Through deterministic replay and automated regression, problems can be quickly located and reproduced. With standardized DDS / QoS and a modular adaptation layer, the system can flexibly integrate different middleware and testing platforms, supporting the entire lifecycle of R&D and verification processes, from single-node verification to large-scale network scenario replay.

[0086] This invention also provides a virtual simulation and integration system for the MCP2515_CAN controller oriented to hardware-in-the-loop testing. The virtual simulation and integration system for the MCP2515_CAN controller oriented to hardware-in-the-loop testing can be implemented by executing the process steps of the virtual simulation and integration method for the MCP2515_CAN controller oriented to hardware-in-the-loop testing. That is, those skilled in the art can understand the virtual simulation and integration method for the MCP2515_CAN controller oriented to hardware-in-the-loop testing as a preferred embodiment of the virtual simulation and integration system for the MCP2515_CAN controller oriented to hardware-in-the-loop testing.

[0087] Those skilled in the art know that, in addition to implementing the system provided by the present application and each device, module and unit thereof in the form of pure computer readable program code, the system provided by the present application and each device, module and unit thereof can also be implemented in the form of logic gates, switches, application specific integrated circuits, programmable logic controllers and embedded microcontrollers, etc. by logically programming the method steps to achieve the same functions. Therefore, the system provided by the present application and each device, module and unit thereof can be considered as a hardware component, and the devices, modules and units included therein for achieving various functions can also be considered as structures within the hardware component; the devices, modules and units for achieving various functions can also be considered as both software modules implementing methods and structures within hardware components.

[0088] The specific embodiments of the present application are described above. It needs to be understood that the present application is not limited to the specific embodiments described above, and various changes or modifications can be made by those skilled in the art within the scope of the claims, which does not affect the essential content of the present application. The embodiments of the present application and the features in the embodiments can be combined with each other in any manner without conflict.

Claims

1. A method for virtual simulation and integration of MCP2515 CAN controller for hardware-in-the-loop test, characterized in that, include: Step 1: Construct the MCP virtual model; Step 2: Construct a virtual CAN bus; Step 3: Build the external interface; Step 4: For the MCP virtual model, create independent events and use the event triggering mechanism to realize asynchronous data transmission and reception and interrupt handling; Step 5: Integrate the MCP virtual model, virtual CAN bus, and external interfaces into a unified simulation environment; Step one, constructing the MCP virtual model, includes: Construct a register model, wherein the register model is used for: parsing SPI standard read and write instructions through functions, and executing GPIO chip select signals through functions; Construct a simulated CAN protocol layer, wherein the simulated CAN protocol layer is executed through a function: Transmission: Based on the data in the transmit buffer written by the MCU through the SPI interface and its write timing signals, the contents of the buffer are parsed, and a corresponding virtual CAN frame is generated according to the preset GPIO control signals for transmission. Reception: Based on preset shielding and filtering rules, the input frames received from the virtual CAN bus are filtered and processed; Interrupt: After completing the data transmission or reception operation, an interrupt flag is set and an interrupt signal is sent according to the event triggering mechanism; Construct a host emulation interface, which includes an SPI emulation interface and a GPIO emulation interface.

2. The method of claim 1, wherein, The SPI emulation interface is used for data communication between the MCP virtual model and the MCU, wherein the data communication between the MCP virtual model and the MCU includes: The MCP virtual model receives write instructions from the MCU registers and writes the SPI value into the virtual register model; The MCP virtual model receives register read instructions from the MCU, reads the corresponding register values ​​from the virtual register model, and returns them to the MCU.

3. The method of claim 1, wherein, The GPIO simulation interface is used for signal communication between the MCP virtual model and the MCU: the signal communication between the MCP virtual model and the MCU includes: The MCP virtual model receives the MCU's chip select enable signal; The MCP virtual model triggers an interrupt event after data transmission or reception is completed, and feeds back the interrupt notification signal to the MCU.

4. The method of claim 1, wherein, The independent events include: Event 1: Parsing or responding to SPI commands; Event 2: Receiving or sending CAN data frames; Event 3: Monitoring and notification interrupted.

5. The method of claim 1, wherein, The external interface is a DDS interface, wherein the DDS interface is used for: The virtual CAN frame is encapsulated into a DDS data packet and sent to the test software. The DDS packet of the parsing test software is restored to a CAN frame input virtual frame.

6. The method of claim 2, wherein, In step five, the MCP virtual model and the virtual CAN bus are integrated into a unified simulation environment, including: Connect the MCP virtual model to the MCU via the SPI simulation interface; Construct an independent simulation node, and enable the virtual CAN bus to interact with third-party testing tools through the independent simulation node and the DDS interface; CAN node data is distributed via a virtual CAN bus, enabling communication with multiple peer nodes.

7. A virtual simulation and integration system for the MCP2515_CAN controller for hardware-in-the-loop testing, characterized in that, include: Module M1: Constructs the MCP virtual model; Module M2: Constructs a virtual CAN bus; Module M3: Constructs external interfaces; Module M4: Creates independent events for the MCP virtual model and uses an event triggering mechanism to achieve asynchronous data transmission and reception and interrupt handling; Module M5: Integrates the MCP virtual model, virtual CAN bus, and external interfaces into a unified simulation environment; The module M1 includes: Submodule M1: Constructs a register model, wherein the register model is used for: parsing SPI standard read and write instructions through functions, and executing GPIO chip select signals through functions; Submodule M2: Constructs a simulated CAN protocol layer, wherein the simulated CAN protocol layer is executed through functions: Transmission: Based on the data in the transmit buffer written by the MCU through the SPI interface and its write timing signals, the contents of the buffer are parsed, and a corresponding virtual CAN frame is generated according to the preset GPIO control signals for transmission. Reception: Based on preset shielding and filtering rules, the input frames received from the virtual CAN bus are filtered and processed; Interrupt: After completing the data transmission or reception operation, an interrupt flag is set and an interrupt signal is sent according to the event triggering mechanism; Submodule M3: Constructs the host emulation interface, which includes an SPI emulation interface and a GPIO emulation interface. The SPI emulation interface is used for data communication between the MCP virtual model and the MCU. The data communication between the MCP virtual model and the MCU includes: The MCP virtual model receives write instructions from the MCU registers and writes the SPI value into the virtual register model; The MCP virtual model receives register read instructions from the MCU, reads the corresponding register values ​​from the virtual register model, and returns them to the MCU. The GPIO simulation interface is used for signal communication between the MCP virtual model and the MCU: the signal communication between the MCP virtual model and the MCU includes: The MCP virtual model receives the MCU's chip select enable signal; The MCP virtual model triggers an interrupt event after data transmission or reception is completed, and feeds back the interrupt notification signal to the MCU.

8. The system according to claim 7, characterized in that, The independent events include: Event 1: Parsing or responding to SPI commands; Event 2: Receiving or sending CAN data frames; Event 3: Monitoring and notification interrupted.

Citation Information

Patent Citations

  • CAN network virtualization method, system, device and medium

    CN119835109A

  • System-level simulation test environment construction method based on DDS

    CN113221318A

  • Vehicle-mounted controller and communication virtualization system and method

    CN119396117A