Skip to content

Commit d41f836

Browse files
Merge pull request #103 from IvanArkhipov1999/time-sync
Add time synchronization example for ESP32
2 parents c3e3d80 + b7ab7e8 commit d41f836

File tree

20 files changed

+3409
-0
lines changed

20 files changed

+3409
-0
lines changed

c-library/xtensa-esp32/Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/README.md

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Martos RTOS Documentation
2+
3+
Welcome to the Martos RTOS documentation. This directory contains comprehensive documentation for the Martos Real-Time Operating System.
4+
5+
## Table of Contents
6+
7+
1. [Time Synchronization System](./time-synchronization.md) - Complete guide to the distributed time synchronization system
8+
2. [Time Synchronization Diagrams](./time-sync-diagrams.md) - Visual diagrams and flowcharts for the time synchronization system
9+
10+
## Time Synchronization System
11+
12+
The Martos RTOS implements a sophisticated distributed time synchronization system using ESP-NOW communication protocol. This system enables precise time coordination across multiple ESP32 and ESP32-C6 devices in wireless networks.
13+
14+
### Key Features
15+
16+
- **Local Voting Protocol**: Implements a distributed consensus algorithm for time synchronization
17+
- **Cross-Platform Compatibility**: Works seamlessly between ESP32 (Xtensa) and ESP32-C6 (RISC-V) platforms
18+
- **ESP-NOW Communication**: Uses low-latency, broadcast communication for efficient synchronization
19+
- **Monotonic Time**: Ensures time can only accelerate, never go backwards
20+
- **Adaptive Quality**: Automatically adjusts synchronization parameters based on network conditions
21+
22+
### Quick Start
23+
24+
```rust
25+
use martos::time_sync::{TimeSyncManager, SyncConfig};
26+
27+
// Initialize sync manager with defaults
28+
let mut sync_manager = TimeSyncManager::new(SyncConfig::default());
29+
30+
// Enable synchronization
31+
sync_manager.enable_sync();
32+
```
33+
34+
### Documentation Structure
35+
36+
#### [Time Synchronization System](./time-synchronization.md)
37+
Comprehensive documentation covering:
38+
- System architecture and components
39+
- Communication protocol details
40+
- Local Voting Protocol algorithm
41+
- Message flow and synchronization cycles
42+
- Implementation details and virtual time system
43+
- Configuration parameters and tuning
44+
- Performance characteristics and metrics
45+
- Cross-platform compatibility
46+
- Usage examples and code samples
47+
- Troubleshooting guide
48+
49+
#### [Time Synchronization Diagrams](./time-sync-diagrams.md)
50+
Visual documentation including:
51+
- System architecture overview
52+
- Message flow sequences
53+
- Local Voting Protocol algorithm flow
54+
- Virtual time system operation
55+
- Network topology examples
56+
- Performance metrics visualization
57+
- Cross-platform communication flow
58+
- Troubleshooting diagnosis flow
59+
60+
## Examples
61+
62+
The time synchronization system includes working examples for both ESP32 and ESP32-C6 platforms:
63+
64+
- [`xtensa-esp32/time-sync`](../examples/rust-examples/xtensa-esp32/time-sync/) - ESP32 (Xtensa) example
65+
- [`risc-v-esp32-c6/time-sync`](../examples/rust-examples/risc-v-esp32-c6/time-sync/) - ESP32-C6 (RISC-V) example
66+
67+
## API Reference
68+
69+
The complete API documentation is available in the source code:
70+
71+
- [`src/time_sync.rs`](../src/time_sync.rs) - Main synchronization manager
72+
- [`src/time_sync/sync_algorithm.rs`](../src/time_sync/sync_algorithm.rs) - Local Voting Protocol implementation
73+
- [`src/time_sync/esp_now_protocol.rs`](../src/time_sync/esp_now_protocol.rs) - ESP-NOW communication layer
74+
75+
## Getting Help
76+
77+
If you have questions or need assistance:
78+
79+
1. Check the [troubleshooting section](./time-synchronization.md#troubleshooting) in the main documentation
80+
2. Review the [example applications](../examples/rust-examples/) for usage patterns
81+
3. Examine the [API documentation](../src/time_sync.rs) for detailed function descriptions
82+
4. Look at the [diagrams](./time-sync-diagrams.md) for visual understanding of the system
83+
84+
## Contributing
85+
86+
When contributing to the time synchronization system:
87+
88+
1. Follow the existing code style and documentation patterns
89+
2. Add comprehensive documentation for new features
90+
3. Include examples and usage patterns
91+
4. Update diagrams when architectural changes are made
92+
5. Test on both ESP32 and ESP32-C6 platforms
93+
94+
---
95+
96+
*This documentation is part of the Martos RTOS project. For more information, visit the [main project repository](../README.md).*

docs/time-sync-diagrams.md

Lines changed: 399 additions & 0 deletions
Large diffs are not rendered by default.

docs/time-synchronization.md

Lines changed: 513 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[build]
2+
rustflags = [
3+
"-C", "link-arg=-Tlinkall.x",
4+
"-C", "force-frame-pointers",
5+
"-C", "link-arg=-Trom_functions.x",
6+
]
7+
8+
target = "riscv32imac-unknown-none-elf"
9+
10+
[unstable]
11+
build-std = ["core", "alloc"]
12+
13+
[target.'cfg(any(target_arch = "riscv32", target_arch = "xtensa"))']
14+
runner = "espflash flash --monitor"
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[package]
2+
name = "time-sync"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[profile.release]
7+
debug = true
8+
9+
[dependencies]
10+
martos = { path = "../../../../", features = ["network"] }
11+
esp-hal = "0.21.1"
12+
esp-backtrace = { version = "0.14.1", features = ["esp32c6", "panic-handler", "exception-handler", "println"] }
13+
esp-println = { version = "0.11.0", features = ["esp32c6"] }
14+
esp-wifi = { version = "0.10.1", features = ["wifi", "esp-now"] }
15+
static_cell = "2.0.0"
16+
17+
[features]
18+
default = ["esp-hal/esp32c6", "esp-backtrace/esp32c6", "esp-println/esp32c6", "esp-wifi/esp32c6"]
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
# ESP32-C6 Time Synchronization Example
2+
3+
This example demonstrates the time synchronization system implemented in Martos RTOS using ESP-NOW communication protocol. The system implements a **Local Voting Protocol** that allows time to accelerate but prevents it from going backwards, ensuring monotonic time progression.
4+
5+
## Features
6+
7+
- **Time Synchronization**: Synchronizes time across multiple ESP32-C6 nodes using broadcast messages
8+
- **ESP-NOW Communication**: Uses ESP-NOW for low-latency peer-to-peer communication
9+
- **Local Voting Protocol**: Implements dynamic time acceleration algorithm with monotonic time guarantee
10+
- **Broadcast-based Sync**: Uses broadcast messages for efficient multi-node synchronization
11+
- **Quality Monitoring**: Tracks synchronization quality and peer performance
12+
- **Cross-platform**: Compatible with ESP32 (Xtensa) and ESP32-C6 (RISC-V) platforms
13+
14+
## Architecture
15+
16+
The example consists of several key components:
17+
18+
1. **TimeSyncManager**: Main synchronization controller
19+
2. **ESP-NOW Protocol**: Communication layer for time data exchange
20+
3. **Sync Algorithm**: Core synchronization algorithm with dynamic correction
21+
4. **Timer Integration**: Integration with Martos timer system
22+
23+
## Configuration
24+
25+
The synchronization system is configured with the following parameters:
26+
27+
- **Sync Interval**: 500ms (default broadcast frequency)
28+
- **Max Correction**: 1000μs (default maximum time correction per cycle)
29+
- **Acceleration Factor**: 0.1 (default acceleration rate)
30+
- **Deceleration Factor**: 0.05 (default deceleration rate)
31+
- **Max Peers**: 10 (maximum number of participants considered in consensus)
32+
33+
## Usage
34+
35+
### Building and Flashing
36+
37+
```bash
38+
# Build the example
39+
cargo build --release --example time-sync
40+
41+
# Flash to ESP32 (adjust port as needed)
42+
espflash flash --release --example time-sync /dev/ttyUSB0
43+
```
44+
45+
### Running Multiple Nodes
46+
47+
To test synchronization between multiple nodes:
48+
49+
1. Flash the example to multiple ESP32-C6 devices (ESP32 and ESP32-C6)
50+
2. Ensure devices are within ESP-NOW communication range
51+
3. Monitor serial output to see synchronization progress
52+
4. Watch the `diff` value decrease as synchronization improves
53+
54+
### Expected Output
55+
56+
```
57+
ESP32-C6: Setup time synchronization!
58+
ESP32-C6: Time synchronization setup complete!
59+
ESP32-C6: Received timestamp: 30288013μs, corrected time: 936751μs, diff: 29351262μs
60+
ESP32-C6: Current offset: 100000μs
61+
ESP32-C6: Received timestamp: 32278010μs, corrected time: 3036532μs, diff: 29241478μs
62+
ESP32-C6: Current offset: 200000μs
63+
ESP32-C6: Received timestamp: 34268014μs, corrected time: 5136548μs, diff: 29131466μs
64+
ESP32-C6: Current offset: 200000μs
65+
ESP32-C6: Received timestamp: 36258013μs, corrected time: 7136562μs, diff: 29121451μs
66+
ESP32-C6: Current offset: 300000μs
67+
ESP32-C6: Received timestamp: 38248009μs, corrected time: 9236609μs, diff: 29011400μs
68+
ESP32-C6: Current offset: 400000μs
69+
ESP32-C6: Received timestamp: 40238008μs, corrected time: 11336665μs, diff: 28901343μs
70+
ESP32-C6: Current offset: 400000μs
71+
ESP32-C6: Received timestamp: 42228012μs, corrected time: 13336653μs, diff: 28891359μs
72+
ESP32-C6: Current offset: 500000μs
73+
ESP32-C6: Received timestamp: 44218013μs, corrected time: 15436722μs, diff: 28781291μs
74+
ESP32-C6: Current offset: 600000μs
75+
ESP32-C6: Received timestamp: 46208013μs, corrected time: 17538108μs, diff: 28669905μs
76+
```
77+
78+
**Key observations:**
79+
- `Received timestamp`: Time from the remote node
80+
- `corrected time`: Local time adjusted by the synchronization offset
81+
- `diff`: Time difference between remote and local (should decrease over time)
82+
- `Current offset`: Virtual time offset applied to local time
83+
84+
## Synchronization Algorithm
85+
86+
The example implements a **Local Voting Protocol** algorithm with the following characteristics:
87+
88+
1. **Broadcast Communication**: Nodes send time broadcasts every 2 seconds
89+
2. **Time Difference Calculation**: Compares received timestamps with local corrected time
90+
3. **Monotonic Time**: Time can only accelerate, never go backwards
91+
4. **Dynamic Correction**: Applies corrections based on weighted peer consensus
92+
5. **Convergence Detection**: Algorithm detects when nodes are synchronized
93+
94+
### Algorithm Details
95+
96+
- **Acceleration Factor**: 0.1 (default; tune for convergence)
97+
- **Deceleration Factor**: 0.05 (default; tune for stability)
98+
- **Max Correction**: 1000μs (default; increase carefully for faster initial sync)
99+
- **Convergence Threshold**: 50% of max correction threshold
100+
101+
## Customization
102+
103+
// Broadcast-only: peers are not managed explicitly
104+
105+
### Adjusting Synchronization Parameters
106+
107+
```rust
108+
let sync_config = SyncConfig {
109+
sync_interval_ms: 1000, // More frequent broadcasts
110+
max_correction_threshold_us: 50000, // Smaller corrections
111+
acceleration_factor: 0.9, // More aggressive acceleration
112+
deceleration_factor: 0.7, // More aggressive deceleration
113+
// ... other parameters
114+
};
115+
```
116+
117+
### Monitoring Synchronization Quality
118+
119+
```rust
120+
println!("Quality: {:.2}, Offset: {}μs",
121+
sync_manager.get_sync_quality(),
122+
sync_manager.get_time_offset_us());
123+
```
124+
125+
## Troubleshooting
126+
127+
### No Synchronization
128+
129+
- Check ESP-NOW communication range
130+
- Ensure synchronization is enabled
131+
132+
### Poor Synchronization Quality
133+
134+
- Increase sync frequency
135+
- Adjust acceleration/deceleration factors
136+
- Check network conditions
137+
138+
### Large Time Corrections
139+
140+
- Reduce max correction threshold
141+
- Increase sync interval
142+
- Check for network delays
143+
144+
## Performance Considerations
145+
146+
- **CPU Usage**: Synchronization processing is lightweight
147+
- **Network Traffic**: Minimal ESP-NOW traffic (few bytes per sync cycle)
148+
- **Power Consumption**: ESP-NOW is power-efficient for IoT applications
149+
150+
## Cross-Platform Compatibility
151+
152+
This example is designed to work seamlessly between ESP32 (Xtensa) and ESP32-C6 (RISC-V) platforms:
153+
154+
- **ESP-NOW Compatibility**: ESP-NOW works between different ESP chipset architectures
155+
- **Shared Protocol**: Both platforms use the same synchronization message format
156+
- **Automatic Detection**: The system automatically detects and adapts to the target platform
157+
- **Unified API**: Same Martos API works on both platforms
158+
159+
### Testing Cross-Platform Synchronization
160+
161+
1. Flash ESP32 example to an ESP32 device
162+
2. Flash ESP32-C6 example to an ESP32-C6 device
163+
3. Both devices will automatically discover and synchronize with each other
164+
4. Monitor both serial outputs to see synchronization progress
165+
166+
## Future Enhancements
167+
168+
- **Encryption**: Add ESP-NOW encryption for secure time synchronization
169+
- **Mesh Support**: Extend to multi-hop mesh networks
170+
- **GPS Integration**: Use GPS for absolute time reference
171+
- **Adaptive Algorithms**: Implement machine learning-based synchronization
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[toolchain]
2+
channel = "esp"

0 commit comments

Comments
 (0)