Hardware-in-loop test-oriented MCP2515CAN controller virtual simulation and integration method and system
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 multi-node collaborative simulation and cross-platform testing.
Patent Information
- Application Number
- CN202511587037.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-31
- Publication Date
- 2025-12-02
- Estimated Expiration
- 2045-10-31
AI Technical Summary
Traditional hardware-in-the-loop testing methods rely on real hardware, resulting in high costs and complexity. They also make it difficult to achieve flexible multi-node collaborative simulation and complex network topology construction, and there are compatibility barriers between testing software from different vendors.
By constructing a virtual simulation model of the MCP2515_CAN controller, simulating network communication using virtual CAN bus middleware, and achieving interconnection with third-party testing tools through the DDS protocol, the controller logic can be run purely in software, and the system can be made more flexible, scalable, and compatible.
It reduces hardware costs and maintenance complexity, supports multi-node parallel communication and complex topology construction, achieves seamless integration with third-party tools, and improves system flexibility and compatibility.
Smart Images

Figure CN121050413A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer hardware virtualization, and more specifically, to a virtual simulation and integration method and system for the MCP2515_CAN controller for hardware-in-the-loop testing. Background Technology
[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 system integration and verification processes. Traditional testing methods require real hardware to achieve 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 scenarios involving multi-node collaborative simulation and complex network topology construction, traditional methods struggle to efficiently reproduce real communication environments due to the limited number of physical connections and network bandwidth. Furthermore, the lack of unified interface standards between current testing systems and the use of closed protocols by different vendors' testing software create compatibility barriers between third-party tools, hindering system-level debugging and cross-platform collaboration.
[0003] To address the aforementioned issues, a virtual simulation and integration method for the MCP2515_CAN controller, oriented towards hardware-in-the-loop testing, is proposed. This method achieves pure software-based operation of the controller logic by simulating the SPI registers and CAN protocol layer, eliminating dependence on the physical chip; it utilizes a virtual CAN bus middleware to simulate real network communication, supporting multi-node collaborative simulation and complex topology construction; and it achieves interoperability with third-party testing tools through a communication channel based on the DDS protocol, thereby significantly improving the system's flexibility, scalability, and compatibility.
[0004] Chinese patent application number CN202411810280.2 discloses a CAN network virtualization method, system, device and medium. This patent uses QEMU virtual machine to simulate CAN hardware, establishes a virtual CAN network, and uses KvaserVirtualCANDriver to connect virtual nodes to realize the simulation and operation of virtual CAN hardware nodes. However, it does not involve MCP simulation. Compared with the two, there are obvious differences in technical means. Summary of the Invention
[0005] To address the shortcomings of existing technologies, the purpose of this invention is to provide a virtual simulation and integration method and system for the MCP2515_CAN controller oriented towards 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 interruption status.
[0011] Preferably, the external interface is a DDS interface, wherein the DDS interface is used to: encapsulate virtual CAN frames into DDS data packets and send them to the test software; and parse the DDS packets from the test software to restore them into CAN frames and input them into the virtual CAN.
[0012] Preferably, in step five, the MCP virtual model and the virtual CAN bus are integrated in a unified simulation environment, including: connecting the MCP virtual model to the MCU through the SPI simulation interface; constructing an independent simulation node, and enabling the virtual CAN bus to interact with third-party testing tools through the independent simulation node and the DDS interface; allocating CAN node data through the virtual CAN bus and communicating with multiple peer nodes.
[0013] According to another aspect of the present invention, a virtual simulation and integration system for an MCP2515_CAN controller oriented to hardware-in-the-loop testing is provided, characterized in that it includes: module M1: constructing an MCP virtual model; module M2: constructing a virtual CAN bus; module M3: constructing an external interface; module M4: creating independent events for the MCP virtual model and using an event triggering mechanism to realize asynchronous data transmission and reception and interrupt handling; and module M5: integrating the MCP virtual model, the virtual CAN bus, and the external interface into a unified simulation environment.
[0014] Preferably, module M1 includes: submodule M1: 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; submodule M2: 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 according to the data written by the MCU through the SPI interface and its write timing signals, 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; interrupt: setting an interrupt flag and issuing an interrupt signal according to the event triggering mechanism after completing the data sending or receiving operation; submodule M3: constructing a host simulation interface, wherein... In the host emulation interface, there are SPI emulation interfaces and GPIO emulation interfaces. 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 receiving a write instruction from the MCU register and writing the SPI 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. 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; and the MCP virtual model triggering an interrupt event after data transmission or reception is completed and feeding back an interrupt notification signal to the MCU.
[0015] 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 interruption status.
[0016] Compared with the prior art, the present invention has the following beneficial effects: 1. By constructing a virtualized simulation model based on SPI registers and the CAN protocol layer, the controller logic was fully software-based, overcoming the strong dependence of traditional testing on physical chips and hardware connections. This approach allows standard SPI drivers to directly drive the virtual controller for data interaction, significantly reducing hardware costs and maintenance complexity, and providing an efficient means for early system verification and cross-platform development. 2. A scalable communication network model was constructed using a virtual CAN bus middleware, capable of simulating the frame scheduling, arbitration, and forwarding mechanisms of a real bus in the host environment. This middleware supports the access of any number of virtual nodes and parallel communication among multiple nodes, effectively addressing the limitations of traditional physical buses in collaborative testing, fault injection, and complex topology construction, significantly improving the system's flexibility and scalability.
[0017] 3. A standardized communication interface with third-party testing tools is achieved through the DDS protocol conversion channel, supporting data interoperability between different testing platforms (such as CANoe, dSPACE, VeriStand, etc.). This mechanism breaks down compatibility barriers between heterogeneous tools, enabling seamless integration of the virtual simulation system with the external testing environment, and providing a universal and efficient solution for cross-platform joint testing and distributed system verification. Attached Figure Description
[0018] Other features, objects, and advantages of the present invention will become more apparent from the following detailed description of non-limiting embodiments with reference to the accompanying drawings: Figure 1 A flowchart illustrating the virtual simulation and integration method for the MCP2515_CAN controller for hardware-in-the-loop testing. Figure 2 This is a schematic diagram of the integration method; Figure 3 This is a schematic diagram illustrating the processing of data and signals by a virtual MCP model. Detailed Implementation
[0019] The present invention will now be described in detail with reference to specific embodiments. These embodiments will help those skilled in the art to further understand the present invention, but do not limit the invention in any way. It should be noted that those skilled in the art can make several changes and improvements without departing from the concept of the present invention. These all fall within the protection scope of the present invention.
[0020] For ease of understanding, the terms or concepts involved in this application are explained below: (1) Register model The register model refers to the storage structure established in software that corresponds to the hardware registers of the MCP2515 controller. It is used to simulate register read / write operations, bit modification, and reset behavior, thereby realizing register access logic consistent with that of the real chip in a virtual environment.
[0021] (2) SPI emulation interface The SPI emulation interface is a software module that simulates the communication behavior of serial peripheral interfaces in the host environment. It is used to realize data interaction between the virtual controller and the main control unit and supports the parsing and response of standard SPI commands.
[0022] (3) GPIO emulation interface The GPIO emulation interface is used to transmit chip select signals and interrupt signals between the virtual controller and the main control unit, simulating the control and notification mechanisms of the physical pins in the MCP2515 chip.
[0023] (4) Simulate the CAN protocol layer The simulated 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 link layer functions such as frame filtering, arbitration, and error management.
[0024] (5) Virtual CAN bus middleware The virtual CAN bus middleware is a software component in the host environment used to realize data transmission and management between multiple virtual nodes. It is responsible for frame forwarding, broadcast distribution, arbitration, and link layer behavior simulation.
[0025] (6) Simulation Nodes The simulation node is a logical unit located in the host environment, used to perform data encapsulation, parsing and routing between the virtual CAN bus and the DDS interface, and to realize protocol conversion and bidirectional communication.
[0026] (7) DDS interface The DDS interface is a communication channel established based on the data distribution service protocol. It is used to enable data publishing, subscription and distribution between the host environment and external testing tools, and to achieve external interconnection of the virtual system.
[0027] (8) Event Mechanism The event mechanism is a task triggering and callback framework provided by the host system. It manages asynchronous operations through event registration and triggering functions, and is used to realize real-time response to SPI transactions, CAN transmission and reception, and interrupts.
[0028] (9) Interruption event An interrupt event refers to a notification action triggered by the virtual controller after completing data transmission or reception. It is used to simulate the interrupt signal of real hardware, enabling the main control unit to respond asynchronously to state changes.
[0029] (10) Host environment The host environment is the platform environment for the virtual simulation system to run. It provides computing resources, event scheduling, interface drivers and communication middleware support, enabling various software modules to run and interact under a unified framework.
[0030] This application provides a virtual simulation and integration method for the MCP2515_CAN controller for hardware-in-the-loop testing. This method simulates all hardware logic of the MCP2515 controller in a software manner within a host environment, achieving purely software-based operation of the controller's communication and testing processes. By constructing a register model and a CAN protocol layer, the system simulates the register operations and communication behavior of a real chip at the SPI interface layer, completing data reading, writing, sending, receiving, and interrupt response. The virtual CAN bus middleware establishes a scalable data transmission channel in the host system, simulating the arbitration and distribution mechanism of the link layer to achieve real-time communication between multiple nodes. The external interface is based on the DDS protocol, converting virtual CAN frames into standard DDS messages to achieve interoperability with third-party testing software. The entire system implements asynchronous data transmission and reception and interrupt handling through an event-triggered mechanism, enabling the virtual controller to possess communication characteristics consistent with the physical hardware in the host environment.
[0031] The following is combined Figure 1 , Figure 2 , Figure 3 A detailed explanation of this method is provided below: Step 1: Constructing the MCP Virtual Model The core objective of building the MCP virtual model in this step is to completely replicate the hardware behavior of the MCP2515 controller using pure software, enabling it to correctly respond to the MCU's SPI communication in the simulation environment. This virtual model consists of three parts: a register model, a CAN protocol simulation layer, and a host simulation interface. These three parts are coupled to the data bus through a unified event system, forming a complete controller simulation structure. The model needs to not only possess a register access mechanism consistent with the real chip but also be able to simulate communication timing, interrupt triggering, and protocol state changes, thereby achieving verifiable and scalable controller behavior at the software level.
[0032] The register model is the foundation of the MCP virtual controller, used to precisely map the addresses and functions of hardware registers. The system defines a global register set to store core information such as control registers, status registers, transmit and receive buffers, and filter and mask registers. Each register is organized as a structure, and a mapping table establishes the correspondence between addresses and register fields. Based on this, the system implements the standard SPI instruction set of the MCP2515, including READ, WRITE, BITMODIFY, RESET, and READSTATUS. Each instruction, upon execution, is parsed into a specific read / write operation on the register model, and the status register and interrupt flag are updated according to the operation result. For example, when the MCU writes a transmit request via SPI, the system automatically triggers the construction and transmission of a CAN frame, and updates the status bits upon task completion. To ensure timing consistency, the register model internally implements state machine logic to control the controller's transitions between various operating states such as RESET, CONFIG, NORMAL, SLEEP, and LOOPBACK. State changes can be triggered by SPI commands or driven by events, thus achieving the same workflow as real hardware.
[0033] The CAN protocol emulation layer handles frame transmission, reception, and interrupt management. In terms of transmission logic, after the MCU writes frame data into the transmission buffer, the system parses and generates the corresponding CAN data frame based on the register contents and submits it through the virtual CAN bus interface function. The reception logic receives frame data from the virtual bus and performs filtering and masking comparisons. Only when the identifier matches the current controller configuration is the frame stored in the reception buffer and the reception flag bit updated. Regarding the interrupt mechanism, when frame transmission is complete, a new frame is received, or an error occurs, the model sets the corresponding flag bit through the interrupt flag register and triggers an interrupt event, ultimately sending an interrupt signal to the main control MCU through the GPIO emulation interface. This mechanism ensures that the emulated controller maintains consistency with the real hardware in event triggering, timing response, and status feedback.
[0034] 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.
[0035] 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.
[0036] 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.
[0037] Step 2: Construct a virtual CAN bus 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.
[0038] The first part of the virtual CAN bus is the data distribution mechanism. This mechanism is responsible for forwarding CAN frames among 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 captures the frame and performs a distribution operation based on its identifier (ID) and node configuration. The system uses a message queue structure to manage all transmission tasks on the bus, with each frame entering the queue to await 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 requesting transmission simultaneously, the bus selects the winning node based on ID priority, and its frame is broadcast normally, while other nodes automatically enter a retransmission waiting state. This mechanism not only conforms to the bus arbitration rules of the CAN protocol but also guarantees data consistency and deterministic transmission timing in a multi-node environment.
[0039] To further enhance the realism of the simulation, a link-layer simulation module was built on top of the data distribution mechanism. This module simulates the behavior of the actual CAN bus at the physical and link layers using algorithms, including logic such as collision detection, error counting, and automatic recovery. Specifically, when a node detects a bit collision or erroneous frame during transmission, the system immediately updates the error counter and triggers the corresponding error state, such as "error active," "error passive," or "bus off" mode. During the error recovery phase, the system periodically checks the bus idle state and reactivates the node when the recovery conditions are met, allowing it to re-participate in communication. Furthermore, the link-layer simulation can also simulate low-level behaviors such as bit stuffing, acknowledgment bits, and CRC checks 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 possesses high-fidelity protocol consistency but also reproduces common anomalies and recovery processes in multi-node communication.
[0040] In terms of system architecture, the implementation of the virtual CAN bus relies on a bus middleware (CANBusMiddleware), which serves as the communication hub for all nodes. The middleware provides standardized send and receive interfaces, such as CAN_TxFrame() and CAN_RxFrame(), to manage 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 ensure ordered data flow scheduling. Through a multi-threaded mechanism, the middleware can handle send and receive requests from multiple nodes simultaneously, thus supporting parallel operation of multiple nodes. To ensure thread safety and real-time response, the system uses semaphores and mutexes to manage access control, avoiding data races or timing disorders under high concurrency. Furthermore, the message queue structure supports priority scheduling and timestamp marking, enabling the bus to accurately reproduce the communication timing of a real CAN network in simulation.
[0041] Link-layer behavior simulation is one of the key features of a virtual bus system. To realistically reflect the physical contention relationships in a CAN network, the system simulates master-slave logic for signal levels during each arbitration process: the master node controls the bus level by sending a dominant bit, while the slave node automatically abandons transmission upon detecting overwriting. This process is implemented in software using logical operations and time-series control, accurately simulating collision detection and priority decision-making for bus-layer signals. Furthermore, the system incorporates an error detection algorithm to determine whether bit errors, stuffing errors, CRC errors, or acknowledgment errors have occurred during frame transmission. Once an anomaly is detected, the bus immediately marks the error source node and updates the error counter, while simultaneously 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 possesses complete fault tolerance and recovery characteristics.
[0042] In terms of interface adaptation and expansion, the virtual CAN bus provides modular interface definitions to support flexible topologies and multi-node expansion. The standard interface layer includes transmit, receive, initialization, and error callback functions, enabling users to access the bus system through a unified API. To achieve system scalability, the virtual bus middleware supports dynamic node registration and deregistration mechanisms, allowing developers to add or remove nodes during simulation runtime without restarting the system. Furthermore, to adapt to different host system architectures, the interface layer is designed with an abstract driver layer, ensuring compatibility with various concurrent frameworks (such as POSIX threads or real-time operating system tasks). This enables rapid porting and deployment of the system across different development platforms (Windows, Linux, RTOS).
[0043] 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 log recording 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 key indicators such as bus load, error count, node status, and arbitration success rate in real time, thereby evaluating system performance. Furthermore, the system supports exporting virtual bus data to standard CAN log formats (such as .blf or .asc), facilitating integration with third-party analysis tools (such as VectorCANalyzer and 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.
[0044] In summary, the virtual CAN bus implements the data transmission, arbitration control, and error recovery mechanisms of a real bus at the software level. It provides a highly realistic 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 integration analysis without physical hardware, significantly reducing debugging costs and improving development efficiency. This module provides a solid communication foundation for subsequent integration of DDS external interfaces and hardware-in-the-loop simulation.
[0045] Step 3: Build the external interface The goal of this step is to build a DDS (Data Distribution Service) interface that acts as a bridge to the external world, enabling the virtual CAN system to perform highly reliable, low-latency, and configurable bidirectional data interaction with third-party test software or actual test platforms. The overall approach is to deploy a DDS communication layer and a separate protocol bridging node in the host environment: the former provides publish / subscribe and QoS management, while 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 bridging boundary, the internal simulation logic remains pure and testable, and external integration is decoupled and connected through a standardized topic and type system.
[0046] In DDS data communication, the system defines dedicated topic namespaces and message patterns for the virtual CAN network. For example, frames from the virtual bus are published to the " / can / bus / out" topic, and externally injected test data is subscribed to the " / can / bus / in" topic. The message payload includes fields such as timestamp, frame ID (including standard / extended bits), DLC, data area, error flag, node source, and bus sequence number. Simulation context information (such as arbitration results or retransmission counts) is also carried when necessary to facilitate accurate backtesting and consistency verification by external tools. Data serialization uses IDL description and CDR encoding, ensuring cross-language / cross-platform interoperability while allowing for field expansion without compatibility issues. The publisher / subscriber is configured with QoS policies such as reliability (Reliable / BestEffort), historical depth, keep-alive time, and latency budget, allowing for scenario-based switching between "real-time priority" and "integrity priority."
[0047] The protocol bridging node is responsible for format conversion, path control, and traffic management. Raw CAN frames output from the virtual bus are mapped to DDS messages within the bridging node and published according to topics. In the reverse path, the bridging node parses the DDS messages back into virtual CAN frames and then injects them into the virtual bus for transmission. To adapt to different test topologies, the bridging node provides two transmission modes: point-to-point and broadcast. Point-to-point mode forwards data according to the target node or routing table, suitable for diagnostics and single-node verification; broadcast mode distributes data across the entire network, suitable for consistency / robustness testing. Routing control supports filtering based on ID ranges, frame types, or custom tags to avoid external noise data contaminating the simulation environment, while also allowing priority boosting and accelerated forwarding of critical frames.
[0048] To meet the requirements of engineering practicality and observability, the DDS interface incorporates an end-to-end timestamp and clock alignment mechanism: key points at frame entry and exit from the bridging node are recorded, and latency measurement and jitter statistics are achieved by combining the host monotonic clock or an external clock source; when necessary, a time synchronization adaptation layer is supported to map the external platform's time base to the simulation time axis. To ensure stability under high load scenarios, the bridging node implements backpressure and buffering strategies: when the external subscriber's consumption rate is insufficient or the virtual bus is busy, the system selects a dropping strategy based on QoS (e.g., dropping the oldest frame or dropping non-critical frames according to filtering rules), and publishes congestion alarms and packet loss statistics through diagnostic topics, facilitating real-time parameter tuning by testers. Error channels and anomaly handling are also explicitly modeled: parsing failures, field out-of-bounds errors, CRC / length inconsistencies, and no subscribers generate diagnostic events with context, supporting automatic degradation and rapid location.
[0049] In terms of security and isolation, the DDS interface can enable domain- and partition-based naming isolation, coupled with whitelisted topics and type validation, to limit the scope of external data injection. When needed, it can be combined with security extensions to enable identity authentication and data encryption, ensuring transmission security during cross-host / cross-network integration. To reduce the binding degree to specific DDS implementations, the communication layer encapsulates commonly used APIs through adapters. Bridge nodes only rely on abstract interfaces to complete publish / subscribe and QoS configuration, thus facilitating replacement between different middlewares or the coexistence of multiple implementations. In terms of performance, bridge nodes adopt lock-free circular queues or a producer / consumer model with minimal lock granularity to achieve zero-copy or low-copy data paths. In multi-core environments, the send, receive, and serialization pipelines can be bound to cores and allocated to memory pools according to CPU affinity and NUMA topology, reducing jitter.
[0050] In terms of testing and verification, the system provides replay and comparison capabilities: on the one hand, it unifies the external DDS stream and virtual bus events into time-sorted logs (including simulation timestamps and real timestamps), supporting replay filtering by range, by ID, or by node; on the other hand, it provides golden test cases and consistency checkers, comparing the replay results frame-by-frame with the expected arbitration sequence and error count trajectory, outputting deviation reports and statistical indicators. Simultaneously, the interface exposes health probes and indicator endpoints (publishing rate, subscription lag, buffer usage, packet loss rate, end-to-end latency P50 / P95 / P99), facilitating automatic acceptance and regression monitoring in continuous integration pipelines and long-term stress tests.
[0051] In summary, step three, by constructing a DDS communication layer and protocol bridging nodes in the host environment, achieved bidirectional interoperability, controllable routing, and observable operation and maintenance between the virtual CAN system and the external test platform. This design ensures an engineering balance between real-time performance, reliability, and scalability, and facilitates smoother cross-platform integration through type and QoS standardization. It provides a robust external interface foundation for subsequent system-level SIL / HIL joint verification, heterogeneous toolchain integration, and large-scale scenario playback.
[0052] Step 4: Create independent events and use the event triggering mechanism to implement asynchronous data transmission and reception and interrupt handling. The goal of this step is to build a unified event triggering and scheduling mechanism covering three core event categories: SPI commands, CAN transmission and reception, and interrupt monitoring. This enables the virtual system to possess engineering capabilities such as asynchronous transmission and reception, real-time interrupt response, and predictable timing. The overall design adopts a combination of event-driven architecture and message queues: all changes from the MCU, virtual CAN bus, and internal state machine enter the scheduler as events; the scheduler processes events in order based on priority, timestamp, and resource availability, and drives the register model, protocol stack, and host simulation interface to evolve collaboratively through callbacks or task execution units. To enhance realism, the system simulates hardware-level latency (such as SPI clock and bit time, arbitration window, and interrupt propagation delay) in the critical path and presents it with configurable parameters, allowing testing to switch between "ideal link" and "high load / high jitter" scenarios.
[0053] SPI instruction events begin with the MCU chip select being pulled low. Upon receiving an edge trigger, the scheduler creates an "SPI transaction" event and locks the current chip select context. The event processing flow parses the command byte, address, and data length sequentially, mapping them to read / write / bit modification operations on the register model. For instructions that cross registers (e.g., writing to the TX buffer and setting the request bit), the processing function completes register updates and side-effect triggering within an atomic region, avoiding read / write contention. To closely resemble the hardware, SPI read / write throughput is limited by the simulated SCK frequency and mode (Mode 0~3). During long-frame read / write operations, sub-events are delivered in batches by byte, resulting in realistic timing interleaving of the returned data. For widely impactful instructions such as RESET and BITMODIFY, the event handler pushes a "state refresh" sub-event at the end, driving state machine transitions and recalculating interrupt flags to ensure that the subsequently visible register view is consistent with the actual chip.
[0054] CAN transmit and receive events are triggered by two sources: the transmit path and the receive path. The transmit path triggers when the request bit in any TX buffer is set, generating a "Frame to be Transmitted" event, reading register fields to assemble a standard / extended frame, and submitting it to the virtual bus. The receive path triggers when the bus middleware distributes arriving frames, generating a "Frame Arrived" event and performing filtering / masking matching. After entering the bus, transmit events undergo arbitration and simulated line-speed transmission. Upon completion, a "Transmission Completed" event is pushed back to update the TXIF, clear the request bit, and write the timestamp. Receive events write data to the RX buffer and set the RXIF upon successful matching. If the buffer is full, a strategy is used to overwrite, discard, or backtrack to the waiting queue, while simultaneously recording the overflow count. To ensure predictability in high-concurrency scenarios, the scheduler maintains separate priority queues for transmit and receive: the transmit queue is sorted by frame ID and entry time, while the receive queue is dynamically weighted by arrival time and buffer occupancy ratio. This ensures compliance with CAN priorities while preventing long-term starvation for some nodes.
[0055] Interrupt monitoring events are triggered by changes in register flags, continuously observing conditions such as transmission completion, reception completion, error count transitions, and mode switching. Once the triggering criteria are met, the scheduler sets the corresponding bit of CANINTF within the shortest safety window and pulls the INT pin high through the GPIO emulation interface, then enters an "interrupt pending" state to wait for MCU response. To reproduce hardware semantics, the system distinguishes between level-triggered and edge-aware behaviors: after the MCU reads the interrupt source and clears the flag, if there are still unprocessed events, it will maintain the INT level until all sources are cleared; if multiple sources overlap within a short period, the scheduler merges or splits interrupts 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 debouncing and minimum width settings to avoid false triggers caused by high-frequency state jitter; under extreme loads, if ISR processing lags, the system will switch to "backpressure mode," delaying new non-critical interrupts and issuing diagnostic events in an observable manner.
[0056] In terms of scheduling and concurrency control, the system employs a single-write, multiple-read register access strategy and fine-grained locking partitioning: the SPI, bus, and INT paths each hold their own fast mutual exclusion, and cross-domain modifications are transmitted through a lock-free circular queue to reduce critical section duration. The scheduler provides two strategies: priority preemption and time-slice round-robin. Preemption is enabled in high-real-time-requirement modes, allowing interrupt monitoring to interrupt low-priority batch SPI reads and writes; a time-slice strategy is used in throughput-priority batch processing modes to improve the efficiency of long transactions. To ensure repeatable timing, all events carry dual timestamps (simulation clock and host monotonic clock), which are used as the basis for sorting and measurement in playback and comparative tests.
[0057] In terms of performance and reliability, the event system supports rate limiting and backpressure: when an external driver triggers an SPI transaction at an abnormal rate or an external DDS injects a high-frequency frame, the scheduler reshapes the enqueue rate according to the waterline, prioritizing critical events (interrupts, reception, error transitions), while merging or discarding low-value repetitive reads and writes, and reporting rate limiting and discard statistics on the diagnostic channel. Error handling follows a tiered strategy: recoverable errors (buffer full, CRC check failure) are retried locally or fail quickly and counted; unrecoverable errors (invalid address, illegal instruction length) immediately generate error events, highlight the relevant register bits, and block subsequent dependent processes to prevent false propagation. The system provides a watchdog to monitor critical events that have not been completed for a long time (such as the end of a pending transmission) and trigger self-healing logic or export a core dump for easy offline location.
[0058] To enhance observability and testing convenience, the event framework includes subscribing-able tracing streams and metrics, such as event inbound / outbound rates, queue depth, ISR latency distribution (P50 / P95 / P99), interrupt merging ratio, buffer overflow counts, and retransmission statistics. It also supports writing event sequences and register snapshots to disk in chronological order, enabling deterministic replay in conjunction with a replay unit. Through the "Gold Sample" test case library, developers can compare a complete interaction (SPI configuration → transmission → arbitration → reception → interrupt clearing) frame-by-frame with the expected trajectory to quickly identify timing deviations or boundary condition vulnerabilities. Ultimately, this event triggering and scheduling mechanism achieves a balance between real-time performance, repeatability, and maintainability, enabling the virtual system to stably reproduce complex asynchronous transmission and reception and interrupt scenarios without physical hardware, providing a solid foundation for driver integration testing, protocol consistency verification, and stress testing.
[0059] Step 5: Integration into a unified simulation environment In this step, the system assembles and orchestrates the MCP virtual model, virtual CAN bus, and DDS external interface within the same simulation framework, forming a unified simulation environment supporting SIL / HIL. The overall design adheres to the principles of "layered decoupling, unified events, consistent timing, observability, and replayability": the bottom layer consists of controller-side logic composed of SPI / GPIOI / O adapters and register / protocol stacks; the middle layer uses virtual CAN middleware for broadcasting and arbitration; and the upper layer uses DDS bridging to achieve cross-platform interconnection with third-party tools. All three layers are connected by a unified event scheduler and message queue, and are managed by the same simulation clock domain and metronome. The data flow consists of the main link: MCU → SPI simulation → MCP register / protocol layer → virtual bus → multi-node distribution → DDS bridging → external tools; and the reverse link: external → DDS → bridging → virtual bus → target MCP node → interrupt reporting → MCU. Any state change in any link is event-driven and time-stamped (simulation clock and host monotonic clock) to ensure the timing of the entire link is traceable and replayable.
[0060] To ensure timing accuracy and system consistency, a unified simulation environment achieves multi-module synchronization through a single-source time base: the internal metronome drives the transmit / receive and ISR windows according to the configured bit time, arbitration window, and interrupt propagation delay; the SPI simulation uses SCK frequency and pattern slicing transactions; the virtual bus controls the arbitration order with a priority queue; and the DDS layer aligns with the external end rhythm through QoS delay budget and historical depth. The system provides three operating modes to handle different scenarios: a deterministic replay mode that advances through discrete events to ensure complete consistency in each execution; a real-time approximation mode that anchors the simulation clock to the host monotonic clock for "soft real-time" linkage with hardware or external tools; and an acceleration mode that bypasses non-critical delays for regression testing and large-scale scenario benchmarking. To improve robustness, the scheduler supports backpressure and water level control, merging or discarding low-priority frames when the queue approaches a threshold, and publishing congestion and packet loss statistics through a diagnostic channel.
[0061] Unified integration is also reflected in the engineering of the configuration and loading process. The system adopts a declarative configuration scheme to describe node topology, baud rate / bit timing, filtering / masking, DDS topics and QoS, log policies and indicator thresholds, etc. After the initiator reads the configuration, it initializes I / O adaptation, register default values, event bus, virtual bus and DDS bridging in sequence, and performs self-tests (register mapping verification, SPI loopback, bus arbitration and DDS loopback). To support HIL, the framework retains hardware abstraction boundaries at the I / O layer: the SPI / GPIO interface can be switched to a real interface card or logic probe, while maintaining the upper-layer event and protocol behavior unchanged; for peripheral / sensor data, real sampling streams can be imported through DDS or additional adaptation layers for closed-loop joint debugging with the virtual CAN network. In terms of security and isolation, the runtime restricts the scope of DDS injection through naming domains / partitions and topic whitelists, and audits and verifies signatures of critical register access and bridging policy changes to ensure data integrity during cross-host joint debugging.
[0062] 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.
[0063] 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.
[0064] 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.
[0065] Those skilled in the art will understand that, besides implementing the system and its various devices, modules, and units provided by this invention in the form of purely computer-readable program code, the same functions can be achieved entirely through logical programming of the method steps, making the system and its various devices, modules, and units of this invention function in the form of logic gates, switches, application-specific integrated circuits, programmable logic controllers, and embedded microcontrollers. Therefore, the system and its various devices, modules, and units provided by this invention can be considered as a hardware component, and the devices, modules, and units included therein for implementing various functions can also be considered as structures within the hardware component; alternatively, the devices, modules, and units for implementing various functions can be considered as both software modules implementing the method and structures within the hardware component.
[0066] Specific embodiments of the present invention have been described above. It should be understood that the present invention is not limited to the specific embodiments described above, and those skilled in the art can make various changes or modifications within the scope of the claims, which do not affect the essence of the present invention. Unless otherwise specified, the embodiments and features described in this application can be arbitrarily combined with each other.
Claims
1. A virtual simulation and integration method for the MCP2515_CAN controller oriented towards hardware-in-the-loop testing, 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.
2. The method according to claim 1, characterized in that, 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.
3. The method according to claim 2, characterized in that, 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.
4. The method according to claim 2, characterized in that, 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.
5. The method according to claim 1, 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.
6. The method according to claim 1, characterized in that, 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.
7. The method according to claim 2, characterized in that, 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 through a virtual CAN bus, enabling communication with multiple peer nodes.
8. 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.
9. The system according to claim 8, characterized in that, 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.
10. The system according to claim 8, 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
UVM based CAN controller IP verifying platform
CN106503308A
System-level simulation test environment construction method based on DDS
CN113221318A
Method and device for realizing virtual calibration of automobile based on virtual simulation platform
CN115981286A
Simulation system
CN116069453A
Cited By
Simulation system and method
CN122064339A
