VirtualBus is a modern C++ embedded system framework providing a virtual communication bus for task-based systems. It enables efficient inter-task communication with support for threading, configuration management, error handling, and external MQTT connectivity.
- Features
- Project Overview
- Directory Structure
- Quick Start
- Installation
- Usage
- Architecture
- Configuration
- API Reference
- Examples
- License
- Virtual Communication Bus: Task-to-task message passing with thread-safe queue management
- Thread Pool: Configurable multi-threaded task execution
- Configuration Management: JSON-based application configuration
- Logging: Dual logging backends (spdlog for production, stdout for debugging)
- Error Handling: Comprehensive error handling with severity levels
- MQTT Support: External communication via Paho MQTT (C and C++ libraries)
- Task Management: Attach/detach tasks dynamically with callback support
- AUTOSAR Compliance: Naming conventions and structure follow AUTOSAR Adaptive standards
VirtualBus is an embedded communication framework designed for real-time systems like inverters, battery management systems (BMS), and IoT devices. It provides:
- Virtual Bus Architecture: A central message broker for all task communications
- Sender/Receiver Model: Asynchronous message passing between tasks
- Command Pattern: Type-safe command objects for structured message passing
- Configuration System: Dynamic configuration loading and management
- Robust Logging: Structured logging with multiple backends
- Battery Management Systems (BMS)
- Power Inverter Control
- Solar Charge Controllers
- IoT Gateway Applications
- Real-time Embedded Systems
VirtualBus/
├── src/ # Application source code
│ ├── main.cpp # Main application entry point
│ ├── SendTask.h # Task for sending commands
│ ├── ReciveTask.h # Task for receiving commands
│ ├── InverterCommand.h # Inverter-specific command implementation
│ ├── InverterCommandParser.h # Parser for inverter commands
│ ├── BatteryCommand.h # Battery-specific command implementation
│ └── BatteryCommandParser.h # Parser for battery commands
│
├── libs/unicore/ # Core framework library
│ ├── include/ # Header files
│ │ ├── VirtualBus.h # Main bus implementation
│ │ ├── VirtualBusCmd.h # Base command class
│ │ ├── Task.h # Base task class
│ │ ├── ThreadPool.h # Thread pool implementation
│ │ ├── Configuration.h # Configuration management
│ │ ├── JsonStorage.h # JSON storage backend
│ │ ├── ErrorHandler.h # Error handling utilities
│ │ ├── ILogger.h # Logger interface
│ │ ├── SpdLogWrapper.h # spdlog wrapper implementation
│ │ ├── StdCoutLogger.h # stdout logger implementation
│ │ ├── DiagnosticTask.h # Diagnostic utilities
│ │ └── Watchdog.h # Watchdog timer
│ │
│ └── src/ # Implementation files
│ ├── VirtualBus.cpp
│ ├── VirtualBusCmd.cpp
│ ├── ThreadPool.cpp
│ ├── ErrorHandler.cpp
│ └── VirtualBusCmd.cpp
│
├── tests/ # Unit tests
├── cmake/ # CMake modules
├── externallib/ # External dependencies
├── CMakeLists.txt # CMake build configuration
├── fetch_and_build.sh # Linux/macOS build script
├── fetch_and_build.ps1 # Windows build script
├── fetch_and_build.py # Python cross-platform build script
├── config.json # Configuration file (example)
├── version.txt # Project version
└── README.md # This file
- C++ Compiler: C++17 or later
- CMake: Version 3.15 or higher
- Python: For build scripts (optional)
- OpenSSL: For MQTT secure connections
- Git: For cloning the repository
# Clone the repository
git clone https://github.com/rtsysembedded/VirtualBus.git
cd VirtualBus
# Build using the provided script
bash fetch_and_build.sh
# Run the application
./build/CPPProject# Using PowerShell
.\fetch_and_build.ps1python3 fetch_and_build.py# Install dependencies
sudo apt-get update
sudo apt-get install -y \
build-essential \
cmake \
libssl-dev \
git \
python3# Install dependencies using Homebrew
brew install cmake openssl git python3# Using vcpkg (recommended)
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
.\vcpkg integrate install
.\vcpkg install openssl:x64-windows-
Clone the Repository
git clone https://github.com/rtsysembedded/VirtualBus.git cd VirtualBus -
Configure Build
mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=Release -
Build
cmake --build . --config Release -
Install (Optional)
sudo cmake --install .
See INSTALLATION.md for detailed platform-specific instructions.
#include "VirtualBus.h"
#include "SendTask.h"
#include "ReciveTask.h"
int main() {
// Create logger
auto logger = std::make_shared<SpdLogWrapper>();
// Initialize virtual bus
VirtualBus bus(logger);
// Create and attach tasks
SendTask sender("Sender", bus, logger);
ReceiveTask receiver("Receiver", bus, logger);
bus.attach(sender.getID(), sender.getName());
bus.attach(receiver.getID(), receiver.getName());
// Start tasks
sender.start();
receiver.start();
// Let tasks run
std::this_thread::sleep_for(std::chrono::seconds(10));
// Cleanup
sender.stop();
receiver.stop();
bus.shutdown();
sender.join();
receiver.join();
return 0;
}See USAGE.md for comprehensive usage examples and API documentation.
The VirtualBus employs a message-passing architecture:
┌─────────────────────────────────────────┐
│ Virtual Bus Core │
│ ┌─────────────────────────────────┐ │
│ │ Message Queue Manager │ │
│ │ - Task registration │ │
│ │ - Message routing │ │
│ │ - Callback management │ │
│ └─────────────────────────────────┘ │
└──────────────┬──────────────────────────┘
│
┌──────────┼──────────┐
│ │ │
┌───▼───┐ ┌──▼───┐ ┌───▼───┐
│TaskA │ │TaskB │ │TaskC │
│ │ │ │ │ │
│Send │ │Recv │ │Process│
└───────┘ └──────┘ └───────┘
- VirtualBus: Central message broker
- Task: Base class for runnable components
- VirtualBusCmd: Base class for commands/messages
- ThreadPool: Manages worker threads
- Configuration: Manages application settings
- Logger: Provides logging functionality
- ErrorHandler: Centralized error management
See ARCHITECTURE.md for detailed architecture documentation.
{
"log_level": "info",
"max_threads": "4",
"mqtt_broker": "mqtt://localhost:1883",
"mqtt_client_id": "virtualbus_client",
"task_timeout": "5000",
"enable_watchdog": true,
"watchdog_timeout": "30000"
}Configuration& config = Configuration::getInstance();
config.setLogger(logger);
config.setStorage(std::make_unique<JsonStorage>(logger));
if (config.load("config.json")) {
std::string logLevel = config.getConfig("log_level");
}config.setConfig("log_level", "debug");
config.save("updated_config.json");See CONFIGURATION.md for detailed configuration options.
class VirtualBus {
public:
// Attach a task to the bus
ReturnType attach(int taskId, const std::string& taskName);
// Detach a task from the bus
void detach(int taskId);
// Register a callback for message handling
void registerCallback(int taskId, CallbackFunction callback);
// Send a message from a sender to the bus
void sendMessage(int senderId, const std::shared_ptr<VirtualBusCmd>& message);
// Receive a message for a specific task
bool receiveMessage(int taskId, std::shared_ptr<VirtualBusCmd>& message);
// Shutdown the bus
void shutdown();
};class Task {
public:
virtual ~Task() = default;
// Start the task execution
virtual void start();
// Stop the task execution
virtual void stop();
// Wait for task completion
virtual void join();
// Get task ID
int getID() const;
// Get task name
std::string getName() const;
protected:
// Override this method to implement task logic
virtual void run() = 0;
};See API.md for complete API documentation.
// Create an inverter command
auto command = std::make_shared<InverterCommand>();
command->setVoltage(48.6);
command->setCurrent(15.0);
command->setMode(InverterCommand::Mode::Charging);
command->updateTimestamp();
// Send via bus
bus.sendMessage(senderId, command);class MyCustomTask : public Task {
protected:
void run() override {
while (running_) {
auto msg = std::make_shared<VirtualBusCmd>();
bus_.sendMessage(id_, msg);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
};See EXAMPLES.md for more detailed examples.
# Enable/disable spdlog
cmake .. -DENABLE_SPDLOG=ON
# Set build type
cmake .. -DCMAKE_BUILD_TYPE=Release
# Use custom toolchain
cmake .. -DCMAKE_TOOLCHAIN_FILE=<path/to/toolchain.cmake>- Linux/macOS:
bash fetch_and_build.sh - Windows:
.\fetch_and_build.ps1 - Cross-platform:
python3 fetch_and_build.py
- spdlog (Production): High-performance structured logging
- StdCoutLogger (Development): Simple console logging
#ifdef USE_SPDLOG
auto logger = std::make_shared<SpdLogWrapper>();
#else
auto logger = std::make_shared<StdCoutLogger>();
#endif
logger->info("Application started");
logger->warn("Warning message");
logger->error("Error message");Run unit tests (if available):
cd build
ctest --output-on-failure- README.md - Project overview (this file)
- INSTALLATION.md - Detailed installation instructions
- USAGE.md - Comprehensive usage guide
- ARCHITECTURE.md - System architecture details
- API.md - Complete API reference
- CONFIGURATION.md - Configuration options
- EXAMPLES.md - Code examples and recipes
- TROUBLESHOOTING.md - Common issues and solutions
The project uses CMake for cross-platform building:
- Minimum CMake: 3.15
- C++ Standard: C++17
- Supported Platforms: Linux, macOS, Windows
- Paho MQTT: Message Queuing Telemetry Transport
- spdlog: Fast C++ logging library
- OpenSSL: Cryptographic library for MQTT secure connections
The project includes automatic version management:
# Version is in version.txt
cat version.txt
# Version is automatically incremented on builds
# via increment_version.pyContributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit changes with clear messages
- Push to the branch
- Open a Pull Request
See CONTRIBUTING.md for detailed guidelines.
- AUTOSAR Standards: https://www.autosar.org/
- C++ Reference: https://en.cppreference.com/
- CMake Documentation: https://cmake.org/documentation/
- spdlog GitHub: https://github.com/gabime/spdlog
- Paho MQTT: https://www.eclipse.org/paho/
- CMake not found: Ensure CMake 3.15+ is installed
- OpenSSL not found: Install libssl-dev (Linux) or use vcpkg (Windows)
- Python 3 not found: Required for version management scripts
See TROUBLESHOOTING.md for detailed solutions.
This project is licensed under the MIT License - see the LICENSE file for details.
Copyright © 2025 rtsysEmbedded
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check TROUBLESHOOTING.md
- Review EXAMPLES.md for common patterns
- Study the example code in
src/directory - Review the header files in
libs/unicore/include/ - Check the example tasks (SendTask, ReceiveTask)
- Explore configuration examples in
config.json
- Read this README
- Follow INSTALLATION.md to set up
- Build the project successfully
- Run the example application
- Review USAGE.md for API usage
- Check EXAMPLES.md for code patterns
- Read ARCHITECTURE.md for system design
Happy coding with VirtualBus! 🚀
