components
This commit is contained in:
513
1 software design/components/time_utils/COMPONENT.md
Normal file
513
1 software design/components/time_utils/COMPONENT.md
Normal file
@@ -0,0 +1,513 @@
|
||||
# Time Utils Component Specification
|
||||
|
||||
**Component ID:** C-TIME-001
|
||||
**Component Name:** Time Utils
|
||||
**Version:** 1.0
|
||||
**Date:** 2025-02-01
|
||||
**Location:** `application_layer/utils/time_utils/`
|
||||
|
||||
## 1. Component Overview
|
||||
|
||||
### 1.1 Purpose
|
||||
The Time Utils component provides centralized time management, timestamp generation, and time synchronization services for the ASF Sensor Hub. It ensures consistent time representation across all system components and provides accurate timestamps for sensor data, events, and system operations.
|
||||
|
||||
### 1.2 Scope
|
||||
- System time management and synchronization
|
||||
- High-precision timestamp generation
|
||||
- Time zone handling and conversion
|
||||
- Uptime and duration tracking
|
||||
- Time-based scheduling utilities
|
||||
- Time format conversion and validation
|
||||
|
||||
### 1.3 Responsibilities
|
||||
- Maintain accurate system time
|
||||
- Generate timestamps for sensor data and events
|
||||
- Provide time synchronization with external sources
|
||||
- Handle time zone conversions
|
||||
- Track system uptime and component operation durations
|
||||
- Provide time-based utility functions
|
||||
|
||||
## 2. Component Architecture
|
||||
|
||||
### 2.1 Static View
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Time Utils"
|
||||
TC[Time Controller]
|
||||
TS[Time Synchronizer]
|
||||
TG[Timestamp Generator]
|
||||
TZ[Timezone Handler]
|
||||
UT[Uptime Tracker]
|
||||
TF[Time Formatter]
|
||||
end
|
||||
|
||||
subgraph "Time Sources"
|
||||
RTC[RTC Hardware]
|
||||
NTP[NTP Server]
|
||||
GPS[GPS Module]
|
||||
MH[Main Hub]
|
||||
end
|
||||
|
||||
subgraph "External Components"
|
||||
SM[Sensor Manager]
|
||||
ES[Event System]
|
||||
DIAG[Diagnostics Manager]
|
||||
LOGGER[Logger]
|
||||
end
|
||||
|
||||
TC --> TS
|
||||
TC --> TG
|
||||
TC --> TZ
|
||||
TC --> UT
|
||||
TC --> TF
|
||||
|
||||
TS --> RTC
|
||||
TS --> NTP
|
||||
TS --> GPS
|
||||
TS --> MH
|
||||
|
||||
SM --> TG
|
||||
ES --> TG
|
||||
DIAG --> TG
|
||||
LOGGER --> TG
|
||||
```
|
||||
|
||||
### 2.2 Internal Components
|
||||
|
||||
#### 2.2.1 Time Controller
|
||||
- Central coordination of time management operations
|
||||
- Time source selection and prioritization
|
||||
- Time accuracy monitoring and validation
|
||||
|
||||
#### 2.2.2 Time Synchronizer
|
||||
- External time source synchronization
|
||||
- Time drift detection and correction
|
||||
- Synchronization scheduling and management
|
||||
|
||||
#### 2.2.3 Timestamp Generator
|
||||
- High-precision timestamp generation
|
||||
- Monotonic time tracking
|
||||
- Timestamp format standardization
|
||||
|
||||
#### 2.2.4 Timezone Handler
|
||||
- Time zone conversion and management
|
||||
- Daylight saving time handling
|
||||
- Local time calculation
|
||||
|
||||
#### 2.2.5 Uptime Tracker
|
||||
- System uptime monitoring
|
||||
- Component operation duration tracking
|
||||
- Performance timing utilities
|
||||
|
||||
#### 2.2.6 Time Formatter
|
||||
- Time format conversion utilities
|
||||
- String representation generation
|
||||
- Time parsing and validation
|
||||
|
||||
## 3. Interfaces
|
||||
|
||||
### 3.1 Provided Interfaces
|
||||
|
||||
#### 3.1.1 ITimeUtils
|
||||
```cpp
|
||||
class ITimeUtils {
|
||||
public:
|
||||
virtual ~ITimeUtils() = default;
|
||||
|
||||
// Time Management
|
||||
virtual Result<void> initialize() = 0;
|
||||
virtual Result<void> shutdown() = 0;
|
||||
virtual Result<void> synchronizeTime() = 0;
|
||||
virtual TimeStatus getTimeStatus() const = 0;
|
||||
|
||||
// Timestamp Generation
|
||||
virtual uint64_t getCurrentTimestampMs() const = 0;
|
||||
virtual uint64_t getCurrentTimestampUs() const = 0;
|
||||
virtual std::chrono::system_clock::time_point getCurrentTimePoint() const = 0;
|
||||
virtual uint64_t getMonotonicTimestampMs() const = 0;
|
||||
|
||||
// Time Conversion
|
||||
virtual std::string formatTimestamp(uint64_t timestamp_ms,
|
||||
TimeFormat format = TimeFormat::ISO8601) const = 0;
|
||||
virtual Result<uint64_t> parseTimestamp(const std::string& time_str,
|
||||
TimeFormat format = TimeFormat::ISO8601) const = 0;
|
||||
virtual Result<uint64_t> convertToUtc(uint64_t local_timestamp_ms) const = 0;
|
||||
virtual Result<uint64_t> convertToLocal(uint64_t utc_timestamp_ms) const = 0;
|
||||
|
||||
// Uptime and Duration
|
||||
virtual uint64_t getSystemUptimeMs() const = 0;
|
||||
virtual uint64_t getComponentUptimeMs(ComponentId component) const = 0;
|
||||
virtual Result<void> startDurationTracking(const std::string& operation_id) = 0;
|
||||
virtual Result<uint64_t> stopDurationTracking(const std::string& operation_id) = 0;
|
||||
|
||||
// Time Zone Management
|
||||
virtual Result<void> setTimeZone(const std::string& timezone) = 0;
|
||||
virtual std::string getCurrentTimeZone() const = 0;
|
||||
virtual bool isDaylightSavingTime() const = 0;
|
||||
|
||||
// Time Validation
|
||||
virtual bool isTimestampValid(uint64_t timestamp_ms) const = 0;
|
||||
virtual bool isTimeAccurate() const = 0;
|
||||
virtual std::chrono::milliseconds getTimeAccuracy() const = 0;
|
||||
};
|
||||
```
|
||||
|
||||
#### 3.1.2 ITimestampProvider
|
||||
```cpp
|
||||
class ITimestampProvider {
|
||||
public:
|
||||
virtual ~ITimestampProvider() = default;
|
||||
virtual uint64_t getTimestamp() const = 0;
|
||||
virtual uint64_t getMonotonicTimestamp() const = 0;
|
||||
virtual bool isTimestampAccurate() const = 0;
|
||||
};
|
||||
```
|
||||
|
||||
#### 3.1.3 ITimeFormatter
|
||||
```cpp
|
||||
class ITimeFormatter {
|
||||
public:
|
||||
virtual ~ITimeFormatter() = default;
|
||||
virtual std::string formatTime(uint64_t timestamp_ms, TimeFormat format) const = 0;
|
||||
virtual std::string formatDuration(uint64_t duration_ms) const = 0;
|
||||
virtual Result<uint64_t> parseTime(const std::string& time_str, TimeFormat format) const = 0;
|
||||
};
|
||||
```
|
||||
|
||||
### 3.2 Required Interfaces
|
||||
|
||||
#### 3.2.1 IRTCDriver
|
||||
- Real-time clock hardware access
|
||||
- RTC time reading and setting
|
||||
- RTC alarm and interrupt management
|
||||
|
||||
#### 3.2.2 INetworkTime
|
||||
- NTP client functionality
|
||||
- Network time synchronization
|
||||
- Time server communication
|
||||
|
||||
#### 3.2.3 IConfigurationManager
|
||||
- Time zone configuration
|
||||
- Synchronization settings
|
||||
- Time source preferences
|
||||
|
||||
#### 3.2.4 ILogger
|
||||
- Time synchronization event logging
|
||||
- Time accuracy monitoring logs
|
||||
- Error condition reporting
|
||||
|
||||
## 4. Dynamic View
|
||||
|
||||
### 4.1 Time Synchronization Sequence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant TC as Time Controller
|
||||
participant TS as Time Synchronizer
|
||||
participant NTP as NTP Client
|
||||
participant RTC as RTC Driver
|
||||
participant LOGGER as Logger
|
||||
|
||||
TC->>TS: synchronizeTime()
|
||||
TS->>NTP: requestTimeSync()
|
||||
NTP->>NTP: queryNTPServer()
|
||||
NTP-->>TS: ntp_time_response
|
||||
|
||||
alt NTP Sync Successful
|
||||
TS->>TS: validateTimeResponse(ntp_time)
|
||||
TS->>RTC: setSystemTime(ntp_time)
|
||||
RTC-->>TS: time_set_success
|
||||
TS->>TS: updateTimeAccuracy(HIGH)
|
||||
TS->>LOGGER: logTimeSyncSuccess(ntp_time)
|
||||
TS-->>TC: sync_successful
|
||||
else NTP Sync Failed
|
||||
TS->>RTC: getCurrentTime()
|
||||
RTC-->>TS: rtc_time
|
||||
TS->>TS: updateTimeAccuracy(LOW)
|
||||
TS->>LOGGER: logTimeSyncFailure(reason)
|
||||
TS-->>TC: sync_failed
|
||||
end
|
||||
```
|
||||
|
||||
### 4.2 Timestamp Generation Sequence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant SM as Sensor Manager
|
||||
participant TG as Timestamp Generator
|
||||
participant RTC as RTC Driver
|
||||
participant TC as Time Controller
|
||||
|
||||
SM->>TG: getCurrentTimestampMs()
|
||||
TG->>RTC: getSystemTime()
|
||||
RTC-->>TG: current_time
|
||||
TG->>TC: getTimeAccuracy()
|
||||
TC-->>TG: accuracy_status
|
||||
TG->>TG: generateTimestamp(current_time, accuracy)
|
||||
TG-->>SM: timestamp_ms
|
||||
|
||||
Note over SM,TG: Timestamp includes accuracy metadata
|
||||
```
|
||||
|
||||
### 4.3 Duration Tracking Sequence
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant COMP as Component
|
||||
participant UT as Uptime Tracker
|
||||
participant TG as Timestamp Generator
|
||||
|
||||
COMP->>UT: startDurationTracking("sensor_acquisition")
|
||||
UT->>TG: getMonotonicTimestamp()
|
||||
TG-->>UT: start_timestamp
|
||||
UT->>UT: storeStartTime("sensor_acquisition", start_timestamp)
|
||||
UT-->>COMP: tracking_started
|
||||
|
||||
Note over COMP,UT: Operation executes
|
||||
|
||||
COMP->>UT: stopDurationTracking("sensor_acquisition")
|
||||
UT->>TG: getMonotonicTimestamp()
|
||||
TG-->>UT: end_timestamp
|
||||
UT->>UT: calculateDuration(start_timestamp, end_timestamp)
|
||||
UT-->>COMP: operation_duration_ms
|
||||
```
|
||||
|
||||
## 5. Time Management
|
||||
|
||||
### 5.1 Time Sources Priority
|
||||
```cpp
|
||||
enum class TimeSource {
|
||||
NTP_SERVER = 0, // Highest priority - Network Time Protocol
|
||||
GPS_MODULE = 1, // High priority - GPS time
|
||||
MAIN_HUB = 2, // Medium priority - Main Hub time
|
||||
RTC_HARDWARE = 3, // Low priority - Hardware RTC
|
||||
SYSTEM_CLOCK = 4 // Lowest priority - System clock
|
||||
};
|
||||
```
|
||||
|
||||
### 5.2 Time Accuracy Levels
|
||||
```cpp
|
||||
enum class TimeAccuracy {
|
||||
HIGH, // ±1 second accuracy (NTP/GPS synchronized)
|
||||
MEDIUM, // ±10 seconds accuracy (Recent sync)
|
||||
LOW, // ±60 seconds accuracy (RTC only)
|
||||
UNKNOWN // Accuracy unknown (no sync)
|
||||
};
|
||||
```
|
||||
|
||||
### 5.3 Time Synchronization Strategy
|
||||
- **Primary Sync**: NTP server synchronization every 24 hours
|
||||
- **Backup Sync**: Main Hub time synchronization every 6 hours
|
||||
- **Drift Monitoring**: Continuous monitoring of time drift
|
||||
- **Accuracy Tracking**: Real-time accuracy assessment
|
||||
- **Fallback**: RTC hardware as last resort time source
|
||||
|
||||
## 6. Timestamp Generation
|
||||
|
||||
### 6.1 Timestamp Formats
|
||||
```cpp
|
||||
enum class TimeFormat {
|
||||
UNIX_TIMESTAMP_MS, // Milliseconds since Unix epoch
|
||||
UNIX_TIMESTAMP_US, // Microseconds since Unix epoch
|
||||
ISO8601, // ISO 8601 format (YYYY-MM-DDTHH:MM:SS.sssZ)
|
||||
RFC3339, // RFC 3339 format
|
||||
HUMAN_READABLE, // Human-readable format
|
||||
COMPACT // Compact format for storage
|
||||
};
|
||||
```
|
||||
|
||||
### 6.2 Timestamp Structure
|
||||
```cpp
|
||||
struct Timestamp {
|
||||
uint64_t timestamp_ms; // Milliseconds since epoch
|
||||
TimeAccuracy accuracy; // Timestamp accuracy level
|
||||
TimeSource source; // Time source used
|
||||
bool is_synchronized; // Whether time is synchronized
|
||||
std::chrono::milliseconds drift; // Estimated drift from accurate time
|
||||
};
|
||||
```
|
||||
|
||||
### 6.3 Monotonic Time Tracking
|
||||
- **Boot Time Reference**: Monotonic time since system boot
|
||||
- **Overflow Handling**: 64-bit counters to prevent overflow
|
||||
- **High Resolution**: Microsecond resolution for precise timing
|
||||
- **Drift Compensation**: Compensation for clock drift
|
||||
|
||||
## 7. Time Zone Management
|
||||
|
||||
### 7.1 Time Zone Support
|
||||
```cpp
|
||||
class TimeZoneManager {
|
||||
public:
|
||||
Result<void> setTimeZone(const std::string& timezone);
|
||||
std::string getCurrentTimeZone() const;
|
||||
bool isDaylightSavingTime(uint64_t timestamp_ms) const;
|
||||
uint64_t convertToUtc(uint64_t local_timestamp_ms) const;
|
||||
uint64_t convertToLocal(uint64_t utc_timestamp_ms) const;
|
||||
|
||||
private:
|
||||
std::string current_timezone_;
|
||||
int32_t utc_offset_minutes_;
|
||||
bool dst_active_;
|
||||
};
|
||||
```
|
||||
|
||||
### 7.2 Supported Time Zones
|
||||
- **UTC**: Coordinated Universal Time (default)
|
||||
- **Local**: Configurable local time zone
|
||||
- **DST Support**: Automatic daylight saving time handling
|
||||
- **Offset Calculation**: UTC offset calculation and conversion
|
||||
|
||||
## 8. Performance Monitoring
|
||||
|
||||
### 8.1 Uptime Tracking
|
||||
```cpp
|
||||
struct UptimeInfo {
|
||||
uint64_t system_uptime_ms; // Total system uptime
|
||||
uint64_t component_uptime_ms; // Component-specific uptime
|
||||
uint32_t boot_count; // Number of system boots
|
||||
uint64_t last_boot_time_ms; // Timestamp of last boot
|
||||
std::map<std::string, uint64_t> operation_durations; // Operation timing
|
||||
};
|
||||
```
|
||||
|
||||
### 8.2 Duration Tracking
|
||||
- **Operation Timing**: Track duration of specific operations
|
||||
- **Performance Metrics**: Calculate average, min, max durations
|
||||
- **Bottleneck Identification**: Identify slow operations
|
||||
- **Trend Analysis**: Monitor performance trends over time
|
||||
|
||||
## 9. Configuration
|
||||
|
||||
### 9.1 Time Utils Configuration
|
||||
```cpp
|
||||
struct TimeUtilsConfig {
|
||||
// Synchronization Configuration
|
||||
std::string ntp_server_url;
|
||||
std::chrono::hours sync_interval;
|
||||
std::chrono::seconds sync_timeout;
|
||||
bool automatic_sync_enabled;
|
||||
|
||||
// Time Zone Configuration
|
||||
std::string default_timezone;
|
||||
bool dst_enabled;
|
||||
int32_t utc_offset_minutes;
|
||||
|
||||
// Accuracy Configuration
|
||||
std::chrono::milliseconds max_acceptable_drift;
|
||||
TimeAccuracy minimum_required_accuracy;
|
||||
bool strict_accuracy_enforcement;
|
||||
|
||||
// Logging Configuration
|
||||
bool log_sync_events;
|
||||
bool log_accuracy_changes;
|
||||
bool log_time_jumps;
|
||||
|
||||
// Performance Configuration
|
||||
bool uptime_tracking_enabled;
|
||||
bool duration_tracking_enabled;
|
||||
uint32_t max_tracked_operations;
|
||||
};
|
||||
```
|
||||
|
||||
## 10. Error Handling
|
||||
|
||||
### 10.1 Time-Related Errors
|
||||
```cpp
|
||||
enum class TimeError {
|
||||
SYNC_FAILED, // Time synchronization failed
|
||||
INVALID_TIMESTAMP, // Invalid timestamp value
|
||||
TIMEZONE_INVALID, // Invalid time zone specification
|
||||
ACCURACY_INSUFFICIENT, // Time accuracy below requirements
|
||||
DRIFT_EXCESSIVE, // Time drift exceeds limits
|
||||
SOURCE_UNAVAILABLE, // Time source not available
|
||||
FORMAT_INVALID // Invalid time format
|
||||
};
|
||||
```
|
||||
|
||||
### 10.2 Error Recovery Strategies
|
||||
- **Sync Retry**: Retry synchronization with exponential backoff
|
||||
- **Source Fallback**: Fall back to alternative time sources
|
||||
- **Accuracy Degradation**: Continue with reduced accuracy
|
||||
- **Error Reporting**: Report time-related issues to diagnostics
|
||||
|
||||
## 11. Performance Characteristics
|
||||
|
||||
### 11.1 Timing Requirements
|
||||
- **Timestamp Generation**: < 1ms for timestamp generation
|
||||
- **Time Synchronization**: < 10 seconds for NTP synchronization
|
||||
- **Format Conversion**: < 5ms for time format conversion
|
||||
- **Duration Calculation**: < 1ms for duration tracking operations
|
||||
|
||||
### 11.2 Resource Usage
|
||||
- **Memory**: < 4KB for time management data structures
|
||||
- **Storage**: Minimal persistent storage for time zone data
|
||||
- **CPU**: < 0.5% average utilization for time operations
|
||||
- **Network**: Periodic NTP synchronization traffic
|
||||
|
||||
## 12. Security Considerations
|
||||
|
||||
### 12.1 Time Security
|
||||
- **NTP Security**: Secure NTP communication to prevent time attacks
|
||||
- **Time Validation**: Validate time sources and detect time jumps
|
||||
- **Accuracy Verification**: Verify time accuracy from multiple sources
|
||||
|
||||
### 12.2 Timestamp Security
|
||||
- **Monotonic Guarantees**: Ensure monotonic timestamp progression
|
||||
- **Tamper Detection**: Detect attempts to manipulate system time
|
||||
- **Audit Trail**: Maintain audit trail of time changes
|
||||
|
||||
## 13. Testing Strategy
|
||||
|
||||
### 13.1 Unit Tests
|
||||
- Timestamp generation accuracy
|
||||
- Time format conversion correctness
|
||||
- Duration tracking precision
|
||||
- Time zone conversion validation
|
||||
|
||||
### 13.2 Integration Tests
|
||||
- NTP synchronization functionality
|
||||
- RTC integration and fallback
|
||||
- Component timestamp consistency
|
||||
- Time accuracy maintenance
|
||||
|
||||
### 13.3 System Tests
|
||||
- Long-term time accuracy validation
|
||||
- Time synchronization under network failures
|
||||
- Performance impact of time operations
|
||||
- Time zone and DST handling
|
||||
|
||||
## 14. Dependencies
|
||||
|
||||
### 14.1 Internal Dependencies
|
||||
- Configuration Manager for time settings
|
||||
- Logger for time event logging
|
||||
- Network stack for NTP synchronization
|
||||
- Hardware drivers for RTC access
|
||||
|
||||
### 14.2 External Dependencies
|
||||
- ESP-IDF time and RTC APIs
|
||||
- NTP client library
|
||||
- Time zone database
|
||||
- Hardware RTC support
|
||||
|
||||
## 15. Constraints and Assumptions
|
||||
|
||||
### 15.1 Constraints
|
||||
- Time accuracy limited by available time sources
|
||||
- Network dependency for high-accuracy time synchronization
|
||||
- RTC hardware accuracy limitations
|
||||
- Memory constraints for time zone data
|
||||
|
||||
### 15.2 Assumptions
|
||||
- Network connectivity available for NTP synchronization
|
||||
- RTC hardware properly configured and functional
|
||||
- System clock reasonably stable between synchronizations
|
||||
- Time zone configuration provided during system setup
|
||||
|
||||
---
|
||||
|
||||
**Document Status:** Final for Implementation
|
||||
**Dependencies:** RTC Driver, Network Stack, Configuration Manager, Logger
|
||||
**Next Review:** After component implementation and accuracy validation
|
||||
Reference in New Issue
Block a user