peat-btle 0.4.0

Bluetooth Low Energy mesh transport for Peat Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// Copyright (c) 2025-2026 (r)evolve - Revolve Team LLC
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Auto-reconnection manager with exponential backoff
//!
//! BLE connections can be lost due to range, interference, or device issues.
//! This module provides automatic reconnection with configurable exponential
//! backoff, matching the behavior of the Android implementation.
//!
//! # Example
//!
//! ```ignore
//! use peat_btle::reconnect::{ReconnectionManager, ReconnectionConfig};
//!
//! let config = ReconnectionConfig::default();
//! let mut manager = ReconnectionManager::new(config);
//!
//! // When a peer disconnects
//! manager.track_disconnection(peer_address.clone());
//!
//! // Periodically check for peers to reconnect
//! for peer in manager.get_peers_to_reconnect() {
//!     if try_connect(&peer).is_ok() {
//!         manager.on_connection_success(&peer);
//!     }
//! }
//! ```

use std::collections::HashMap;
use std::time::{Duration, Instant};

/// Configuration for reconnection behavior
#[derive(Debug, Clone)]
pub struct ReconnectionConfig {
    /// Base delay between reconnection attempts (default: 2 seconds)
    pub base_delay: Duration,
    /// Maximum delay between attempts (default: 60 seconds)
    pub max_delay: Duration,
    /// Maximum number of reconnection attempts before giving up (default: 10)
    pub max_attempts: u32,
    /// Interval for checking which peers need reconnection (default: 5 seconds)
    pub check_interval: Duration,
    /// Use flat delay instead of exponential backoff (default: false)
    /// When true, every attempt uses `base_delay` with no exponential increase.
    pub use_flat_delay: bool,
    /// Auto-reset attempt counter when max_attempts is exhausted (default: false)
    /// When true, reaching max_attempts resets the counter instead of abandoning the peer.
    pub reset_on_exhaustion: bool,
}

impl Default for ReconnectionConfig {
    fn default() -> Self {
        Self {
            base_delay: Duration::from_secs(2),
            max_delay: Duration::from_secs(60),
            max_attempts: 10,
            check_interval: Duration::from_secs(5),
            use_flat_delay: false,
            reset_on_exhaustion: false,
        }
    }
}

impl ReconnectionConfig {
    /// Create a new configuration with custom values
    pub fn new(
        base_delay: Duration,
        max_delay: Duration,
        max_attempts: u32,
        check_interval: Duration,
    ) -> Self {
        Self {
            base_delay,
            max_delay,
            max_attempts,
            check_interval,
            use_flat_delay: false,
            reset_on_exhaustion: false,
        }
    }

    /// Create a fast reconnection config for testing
    pub fn fast() -> Self {
        Self {
            base_delay: Duration::from_millis(500),
            max_delay: Duration::from_secs(5),
            max_attempts: 5,
            check_interval: Duration::from_secs(1),
            use_flat_delay: false,
            reset_on_exhaustion: false,
        }
    }

    /// Create a conservative config for battery-constrained devices
    pub fn conservative() -> Self {
        Self {
            base_delay: Duration::from_secs(5),
            max_delay: Duration::from_secs(120),
            max_attempts: 5,
            check_interval: Duration::from_secs(10),
            use_flat_delay: false,
            reset_on_exhaustion: false,
        }
    }

    /// Kotlin Android normal mode: base=1s, max=15s, 20 attempts, exponential backoff
    pub fn kotlin_normal() -> Self {
        Self {
            base_delay: Duration::from_millis(1000),
            max_delay: Duration::from_millis(15000),
            max_attempts: 20,
            check_interval: Duration::from_secs(5),
            use_flat_delay: false,
            reset_on_exhaustion: false,
        }
    }

    /// Kotlin Android high-priority mode: base=1s, flat delay, auto-reset on exhaustion
    pub fn kotlin_high_priority() -> Self {
        Self {
            base_delay: Duration::from_millis(1000),
            max_delay: Duration::from_millis(15000),
            max_attempts: 20,
            check_interval: Duration::from_secs(5),
            use_flat_delay: true,
            reset_on_exhaustion: true,
        }
    }
}

/// State for tracking a single peer's reconnection
#[derive(Debug, Clone)]
struct PeerReconnectionState {
    /// Number of reconnection attempts made
    attempts: u32,
    /// When the last attempt was made
    last_attempt: Instant,
    /// When the peer was first marked for reconnection
    disconnected_at: Instant,
}

impl PeerReconnectionState {
    fn new() -> Self {
        let now = Instant::now();
        Self {
            attempts: 0,
            last_attempt: now,
            disconnected_at: now,
        }
    }
}

/// Result of checking if a peer should be reconnected
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReconnectionStatus {
    /// Ready to attempt reconnection
    Ready,
    /// Waiting for backoff delay to expire
    Waiting {
        /// Time remaining until next attempt is allowed
        remaining: Duration,
    },
    /// Maximum attempts exceeded, peer is abandoned
    Exhausted {
        /// Number of attempts that were made
        attempts: u32,
    },
    /// Peer is not being tracked for reconnection
    NotTracked,
}

/// Manager for auto-reconnection with exponential backoff
///
/// Tracks disconnected peers and determines when to attempt reconnection
/// based on exponential backoff.
#[derive(Debug)]
pub struct ReconnectionManager {
    /// Configuration
    config: ReconnectionConfig,
    /// Per-peer reconnection state
    peers: HashMap<String, PeerReconnectionState>,
}

impl ReconnectionManager {
    /// Create a new reconnection manager with the given configuration
    pub fn new(config: ReconnectionConfig) -> Self {
        Self {
            config,
            peers: HashMap::new(),
        }
    }

    /// Create a manager with default configuration
    pub fn with_defaults() -> Self {
        Self::new(ReconnectionConfig::default())
    }

    /// Track a peer for reconnection after disconnection
    ///
    /// Call this when a peer disconnects unexpectedly.
    pub fn track_disconnection(&mut self, address: String) {
        use std::collections::hash_map::Entry;

        if let Entry::Vacant(entry) = self.peers.entry(address.clone()) {
            log::debug!("Tracking {} for reconnection", address);
            entry.insert(PeerReconnectionState::new());
        }
    }

    /// Check if a peer is being tracked for reconnection
    pub fn is_tracked(&self, address: &str) -> bool {
        self.peers.contains_key(address)
    }

    /// Get the reconnection status for a peer
    pub fn get_status(&self, address: &str) -> ReconnectionStatus {
        match self.peers.get(address) {
            None => ReconnectionStatus::NotTracked,
            Some(state) => {
                if state.attempts >= self.config.max_attempts {
                    if self.config.reset_on_exhaustion {
                        // Will be reset on next get_peers_to_reconnect() call
                        return ReconnectionStatus::Ready;
                    }
                    return ReconnectionStatus::Exhausted {
                        attempts: state.attempts,
                    };
                }

                // First attempt should be immediate (no delay)
                if state.attempts == 0 {
                    return ReconnectionStatus::Ready;
                }

                // Subsequent attempts use exponential backoff
                let delay = self.calculate_delay(state.attempts);
                let elapsed = state.last_attempt.elapsed();

                if elapsed >= delay {
                    ReconnectionStatus::Ready
                } else {
                    ReconnectionStatus::Waiting {
                        remaining: delay - elapsed,
                    }
                }
            }
        }
    }

    /// Calculate the backoff delay for a given attempt number
    ///
    /// Uses exponential backoff: delay = min(base * 2^attempts, max)
    /// In flat delay mode, always returns base_delay.
    fn calculate_delay(&self, attempts: u32) -> Duration {
        if self.config.use_flat_delay {
            return self.config.base_delay;
        }
        let multiplier = 1u64 << attempts.min(30); // Prevent overflow
        let delay_ms = self.config.base_delay.as_millis() as u64 * multiplier;
        let max_ms = self.config.max_delay.as_millis() as u64;
        Duration::from_millis(delay_ms.min(max_ms))
    }

    /// Get all peers that are ready for a reconnection attempt
    ///
    /// Returns addresses of peers that:
    /// - Haven't exceeded max attempts (or will be auto-reset if `reset_on_exhaustion` is true)
    /// - Have waited long enough since the last attempt (first attempt is immediate)
    pub fn get_peers_to_reconnect(&mut self) -> Vec<String> {
        // Auto-reset exhausted peers when configured
        if self.config.reset_on_exhaustion {
            let max = self.config.max_attempts;
            for state in self.peers.values_mut() {
                if state.attempts >= max {
                    log::debug!("Auto-resetting exhausted peer (reset_on_exhaustion)");
                    state.attempts = 0;
                    state.last_attempt = Instant::now();
                }
            }
        }

        self.peers
            .iter()
            .filter_map(|(address, state)| {
                if state.attempts >= self.config.max_attempts {
                    return None;
                }

                // First attempt is immediate
                if state.attempts == 0 {
                    return Some(address.clone());
                }

                // Subsequent attempts use exponential backoff (or flat delay)
                let delay = self.calculate_delay(state.attempts);
                if state.last_attempt.elapsed() >= delay {
                    Some(address.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Record a reconnection attempt for a peer
    ///
    /// Call this when starting a reconnection attempt.
    pub fn record_attempt(&mut self, address: &str) {
        let attempts = if let Some(state) = self.peers.get_mut(address) {
            state.attempts += 1;
            state.last_attempt = Instant::now();
            Some(state.attempts)
        } else {
            None
        };

        if let Some(attempts) = attempts {
            let next_delay = self.calculate_delay(attempts);
            log::debug!(
                "Reconnection attempt {} for {} (next delay: {:?})",
                attempts,
                address,
                next_delay
            );
        }
    }

    /// Called when a connection succeeds
    ///
    /// Removes the peer from reconnection tracking.
    pub fn on_connection_success(&mut self, address: &str) {
        if self.peers.remove(address).is_some() {
            log::debug!(
                "Connection succeeded for {}, removed from reconnection tracking",
                address
            );
        }
    }

    /// Stop tracking a peer (e.g., peer was intentionally removed)
    pub fn stop_tracking(&mut self, address: &str) {
        if self.peers.remove(address).is_some() {
            log::debug!("Stopped tracking {} for reconnection", address);
        }
    }

    /// Clear all reconnection tracking
    pub fn clear(&mut self) {
        let count = self.peers.len();
        self.peers.clear();
        if count > 0 {
            log::debug!("Cleared reconnection tracking for {} peers", count);
        }
    }

    /// Get the number of peers being tracked
    pub fn tracked_count(&self) -> usize {
        self.peers.len()
    }

    /// Get statistics for a peer
    pub fn get_peer_stats(&self, address: &str) -> Option<PeerReconnectionStats> {
        self.peers.get(address).map(|state| PeerReconnectionStats {
            attempts: state.attempts,
            max_attempts: self.config.max_attempts,
            disconnected_duration: state.disconnected_at.elapsed(),
            next_attempt_delay: if state.attempts >= self.config.max_attempts {
                Duration::MAX // Exhausted
            } else if state.attempts == 0 {
                Duration::ZERO // First attempt is immediate
            } else {
                self.calculate_delay(state.attempts)
            },
        })
    }

    /// Get the check interval from configuration
    pub fn check_interval(&self) -> Duration {
        self.config.check_interval
    }
}

/// Statistics for a peer's reconnection state
#[derive(Debug, Clone)]
pub struct PeerReconnectionStats {
    /// Number of attempts made
    pub attempts: u32,
    /// Maximum allowed attempts
    pub max_attempts: u32,
    /// How long since the peer disconnected
    pub disconnected_duration: Duration,
    /// Computed delay for the next reconnection attempt (ZERO if ready, MAX if exhausted).
    /// This is the configured delay (flat or exponential), not the remaining wait time.
    /// Use `get_status()` for remaining-time semantics.
    pub next_attempt_delay: Duration,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_exponential_backoff() {
        let config = ReconnectionConfig {
            base_delay: Duration::from_secs(2),
            max_delay: Duration::from_secs(60),
            max_attempts: 10,
            check_interval: Duration::from_secs(5),
            use_flat_delay: false,
            reset_on_exhaustion: false,
        };
        let manager = ReconnectionManager::new(config);

        // Check backoff delays
        assert_eq!(manager.calculate_delay(0), Duration::from_secs(2));
        assert_eq!(manager.calculate_delay(1), Duration::from_secs(4));
        assert_eq!(manager.calculate_delay(2), Duration::from_secs(8));
        assert_eq!(manager.calculate_delay(3), Duration::from_secs(16));
        assert_eq!(manager.calculate_delay(4), Duration::from_secs(32));
        assert_eq!(manager.calculate_delay(5), Duration::from_secs(60)); // Capped at max
        assert_eq!(manager.calculate_delay(6), Duration::from_secs(60));
    }

    #[test]
    fn test_track_and_status() {
        let mut manager = ReconnectionManager::new(ReconnectionConfig::fast());

        // Not tracked initially
        assert_eq!(
            manager.get_status("00:11:22:33:44:55"),
            ReconnectionStatus::NotTracked
        );

        // Track a disconnection
        manager.track_disconnection("00:11:22:33:44:55".to_string());
        assert!(manager.is_tracked("00:11:22:33:44:55"));

        // Should be ready immediately
        assert_eq!(
            manager.get_status("00:11:22:33:44:55"),
            ReconnectionStatus::Ready
        );
    }

    #[test]
    fn test_connection_success_clears_tracking() {
        let mut manager = ReconnectionManager::with_defaults();

        manager.track_disconnection("00:11:22:33:44:55".to_string());
        assert!(manager.is_tracked("00:11:22:33:44:55"));

        manager.on_connection_success("00:11:22:33:44:55");
        assert!(!manager.is_tracked("00:11:22:33:44:55"));
        assert_eq!(
            manager.get_status("00:11:22:33:44:55"),
            ReconnectionStatus::NotTracked
        );
        assert_eq!(manager.tracked_count(), 0);
    }

    #[test]
    fn test_max_attempts_exhaustion() {
        let config = ReconnectionConfig {
            base_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(10),
            max_attempts: 3,
            check_interval: Duration::from_millis(1),
            use_flat_delay: false,
            reset_on_exhaustion: false,
        };
        let mut manager = ReconnectionManager::new(config);

        manager.track_disconnection("test".to_string());

        // Record 3 attempts
        for _ in 0..3 {
            manager.record_attempt("test");
        }

        // Should be exhausted
        assert_eq!(
            manager.get_status("test"),
            ReconnectionStatus::Exhausted { attempts: 3 }
        );
    }

    // === Kotlin parity tests ===

    #[test]
    fn test_kotlin_normal_config_backoff() {
        // Verify delay sequence matches Kotlin normal mode:
        // base=1000ms, max=15000ms, 20 attempts, exponential backoff
        let config = ReconnectionConfig::kotlin_normal();
        assert_eq!(config.base_delay, Duration::from_millis(1000));
        assert_eq!(config.max_delay, Duration::from_millis(15000));
        assert_eq!(config.max_attempts, 20);
        assert!(!config.use_flat_delay);
        assert!(!config.reset_on_exhaustion);

        let manager = ReconnectionManager::new(config);

        // Kotlin backoff: min(base * 2^attempts, max)
        // attempt 0: 1000 * 1 = 1000ms
        assert_eq!(manager.calculate_delay(0), Duration::from_millis(1000));
        // attempt 1: 1000 * 2 = 2000ms
        assert_eq!(manager.calculate_delay(1), Duration::from_millis(2000));
        // attempt 2: 1000 * 4 = 4000ms
        assert_eq!(manager.calculate_delay(2), Duration::from_millis(4000));
        // attempt 3: 1000 * 8 = 8000ms
        assert_eq!(manager.calculate_delay(3), Duration::from_millis(8000));
        // attempt 4: 1000 * 16 = 15000ms (capped at max)
        assert_eq!(manager.calculate_delay(4), Duration::from_millis(15000));
        // attempt 5: still capped
        assert_eq!(manager.calculate_delay(5), Duration::from_millis(15000));
    }

    #[test]
    fn test_flat_delay_mode() {
        // High-priority mode: flat delay (no exponential backoff)
        let config = ReconnectionConfig::kotlin_high_priority();
        assert!(config.use_flat_delay);

        let manager = ReconnectionManager::new(config);

        // Every attempt should use base_delay = 1000ms
        assert_eq!(manager.calculate_delay(0), Duration::from_millis(1000));
        assert_eq!(manager.calculate_delay(1), Duration::from_millis(1000));
        assert_eq!(manager.calculate_delay(5), Duration::from_millis(1000));
        assert_eq!(manager.calculate_delay(19), Duration::from_millis(1000));
    }

    #[test]
    fn test_reset_on_exhaustion() {
        let config = ReconnectionConfig {
            base_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(10),
            max_attempts: 3,
            check_interval: Duration::from_millis(1),
            use_flat_delay: true,
            reset_on_exhaustion: true,
        };
        let mut manager = ReconnectionManager::new(config);

        manager.track_disconnection("test".to_string());

        // Exhaust all 3 attempts
        for _ in 0..3 {
            manager.record_attempt("test");
        }

        // With reset_on_exhaustion, status should show Ready (not Exhausted)
        assert_eq!(manager.get_status("test"), ReconnectionStatus::Ready);

        // get_peers_to_reconnect should reset and return the peer
        std::thread::sleep(Duration::from_millis(5));
        let peers = manager.get_peers_to_reconnect();
        assert!(peers.contains(&"test".to_string()));

        // After reset, attempts should be back to 0
        let stats = manager.get_peer_stats("test").unwrap();
        assert_eq!(stats.attempts, 0);
    }

    #[test]
    fn test_stop_tracking_matches_reset() {
        // Verify stop_tracking() has same effect as on_connection_success():
        // complete removal from tracking
        let mut manager = ReconnectionManager::with_defaults();

        manager.track_disconnection("peer1".to_string());
        manager.track_disconnection("peer2".to_string());
        assert_eq!(manager.tracked_count(), 2);

        manager.stop_tracking("peer1");
        assert!(!manager.is_tracked("peer1"));
        assert_eq!(manager.get_status("peer1"), ReconnectionStatus::NotTracked);
        assert_eq!(manager.tracked_count(), 1);

        // on_connection_success has same effect
        manager.on_connection_success("peer2");
        assert!(!manager.is_tracked("peer2"));
        assert_eq!(manager.get_status("peer2"), ReconnectionStatus::NotTracked);
        assert_eq!(manager.tracked_count(), 0);
    }
}