peat-btle 0.3.3

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
// 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.

//! Batch Accumulator for Peat-Lite Sync
//!
//! Collects CRDT operations over a configurable time window or size limit,
//! then emits them as a batch for efficient BLE transmission.
//!
//! This reduces radio activity and power consumption on constrained devices.

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use super::crdt::CrdtOperation;

/// Configuration for batch accumulation
#[derive(Debug, Clone)]
pub struct BatchConfig {
    /// Maximum time to wait before sending (milliseconds)
    pub max_wait_ms: u64,
    /// Maximum bytes to accumulate before sending
    pub max_bytes: usize,
    /// Maximum number of operations to accumulate
    pub max_operations: usize,
    /// Minimum time between syncs (milliseconds)
    pub min_interval_ms: u64,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            max_wait_ms: 5000,     // 5 seconds
            max_bytes: 512,        // Half a typical MTU-extended packet
            max_operations: 20,    // Reasonable batch size
            min_interval_ms: 1000, // At most 1 sync/second
        }
    }
}

impl BatchConfig {
    /// Create a config optimized for power efficiency
    pub fn low_power() -> Self {
        Self {
            max_wait_ms: 30_000, // 30 seconds
            max_bytes: 1024,
            max_operations: 50,
            min_interval_ms: 10_000, // At most 1 sync every 10 seconds
        }
    }

    /// Create a config for more responsive sync
    pub fn responsive() -> Self {
        Self {
            max_wait_ms: 1000, // 1 second
            max_bytes: 256,
            max_operations: 10,
            min_interval_ms: 500,
        }
    }
}

/// Batch of operations ready to send
#[derive(Debug, Clone)]
pub struct OperationBatch {
    /// Operations in this batch
    pub operations: Vec<CrdtOperation>,
    /// Total size in bytes
    pub total_bytes: usize,
    /// Timestamp when batch was created
    pub created_at: u64,
}

impl OperationBatch {
    /// Check if batch is empty
    pub fn is_empty(&self) -> bool {
        self.operations.is_empty()
    }

    /// Get number of operations
    pub fn len(&self) -> usize {
        self.operations.len()
    }

    /// Encode all operations to bytes
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.total_bytes + 4);
        // Operation count
        buf.extend_from_slice(&(self.operations.len() as u16).to_le_bytes());
        // Encode each operation
        for op in &self.operations {
            let encoded = op.encode();
            buf.extend_from_slice(&(encoded.len() as u16).to_le_bytes());
            buf.extend_from_slice(&encoded);
        }
        buf
    }

    /// Decode operations from bytes
    pub fn decode(data: &[u8]) -> Option<Self> {
        if data.len() < 2 {
            return None;
        }

        let op_count = u16::from_le_bytes([data[0], data[1]]) as usize;
        let mut operations = Vec::with_capacity(op_count);
        let mut offset = 2;
        let mut total_bytes = 0;

        for _ in 0..op_count {
            if offset + 2 > data.len() {
                return None;
            }
            let op_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
            offset += 2;

            if offset + op_len > data.len() {
                return None;
            }
            let op = CrdtOperation::decode(&data[offset..offset + op_len])?;
            total_bytes += op.size();
            operations.push(op);
            offset += op_len;
        }

        Some(Self {
            operations,
            total_bytes,
            created_at: 0,
        })
    }
}

/// Accumulates CRDT operations for batched transmission
#[derive(Debug)]
pub struct BatchAccumulator {
    /// Configuration
    config: BatchConfig,
    /// Pending operations
    pending: Vec<CrdtOperation>,
    /// Accumulated bytes
    bytes_accumulated: usize,
    /// Time of first pending operation
    first_pending_time: Option<u64>,
    /// Time of last sync
    last_sync_time: u64,
}

impl BatchAccumulator {
    /// Create a new accumulator with the given config
    pub fn new(config: BatchConfig) -> Self {
        Self {
            config,
            pending: Vec::new(),
            bytes_accumulated: 0,
            first_pending_time: None,
            last_sync_time: 0,
        }
    }

    /// Create with default config
    pub fn with_defaults() -> Self {
        Self::new(BatchConfig::default())
    }

    /// Add an operation to the batch
    ///
    /// Returns true if the operation was added, false if batch is full
    pub fn add(&mut self, op: CrdtOperation, current_time_ms: u64) -> bool {
        let op_size = op.size();

        // Check if we have room
        if self.bytes_accumulated + op_size > self.config.max_bytes && !self.pending.is_empty() {
            return false;
        }
        if self.pending.len() >= self.config.max_operations {
            return false;
        }

        // Record first pending time
        if self.first_pending_time.is_none() {
            self.first_pending_time = Some(current_time_ms);
        }

        self.pending.push(op);
        self.bytes_accumulated += op_size;
        true
    }

    /// Check if the batch should be flushed
    pub fn should_flush(&self, current_time_ms: u64) -> bool {
        if self.pending.is_empty() {
            return false;
        }

        // Check if minimum interval has passed
        if current_time_ms < self.last_sync_time + self.config.min_interval_ms {
            return false;
        }

        // Check size limits
        if self.bytes_accumulated >= self.config.max_bytes {
            return true;
        }
        if self.pending.len() >= self.config.max_operations {
            return true;
        }

        // Check time limit
        if let Some(first_time) = self.first_pending_time {
            if current_time_ms >= first_time + self.config.max_wait_ms {
                return true;
            }
        }

        false
    }

    /// Flush pending operations into a batch
    pub fn flush(&mut self, current_time_ms: u64) -> Option<OperationBatch> {
        if self.pending.is_empty() {
            return None;
        }

        let batch = OperationBatch {
            operations: core::mem::take(&mut self.pending),
            total_bytes: self.bytes_accumulated,
            created_at: current_time_ms,
        };

        self.bytes_accumulated = 0;
        self.first_pending_time = None;
        self.last_sync_time = current_time_ms;

        Some(batch)
    }

    /// Force flush regardless of timing constraints
    pub fn force_flush(&mut self, current_time_ms: u64) -> Option<OperationBatch> {
        self.flush(current_time_ms)
    }

    /// Get number of pending operations
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }

    /// Get accumulated bytes
    pub fn accumulated_bytes(&self) -> usize {
        self.bytes_accumulated
    }

    /// Check if there are pending operations
    pub fn has_pending(&self) -> bool {
        !self.pending.is_empty()
    }

    /// Clear all pending operations without flushing
    pub fn clear(&mut self) {
        self.pending.clear();
        self.bytes_accumulated = 0;
        self.first_pending_time = None;
    }

    /// Get the config
    pub fn config(&self) -> &BatchConfig {
        &self.config
    }

    /// Update the config
    pub fn set_config(&mut self, config: BatchConfig) {
        self.config = config;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sync::crdt::Position;
    use crate::NodeId;

    fn make_position_op(node_id: u32, timestamp: u64) -> CrdtOperation {
        CrdtOperation::UpdatePosition {
            node_id: NodeId::new(node_id),
            position: Position::new(37.0, -122.0),
            timestamp,
        }
    }

    #[test]
    fn test_batch_config_defaults() {
        let config = BatchConfig::default();
        assert_eq!(config.max_wait_ms, 5000);
        assert_eq!(config.max_bytes, 512);
    }

    #[test]
    fn test_accumulator_add() {
        let mut acc = BatchAccumulator::with_defaults();

        let op = make_position_op(1, 1000);
        assert!(acc.add(op, 1000));
        assert_eq!(acc.pending_count(), 1);
        assert!(acc.has_pending());
    }

    #[test]
    fn test_accumulator_max_operations() {
        let config = BatchConfig {
            max_operations: 2,
            ..Default::default()
        };
        let mut acc = BatchAccumulator::new(config);

        assert!(acc.add(make_position_op(1, 1000), 1000));
        assert!(acc.add(make_position_op(2, 1001), 1001));
        assert!(!acc.add(make_position_op(3, 1002), 1002)); // Should fail
        assert_eq!(acc.pending_count(), 2);
    }

    #[test]
    fn test_accumulator_flush() {
        let mut acc = BatchAccumulator::with_defaults();

        acc.add(make_position_op(1, 1000), 1000);
        acc.add(make_position_op(2, 1001), 1001);

        let batch = acc.flush(2000).unwrap();
        assert_eq!(batch.len(), 2);
        assert!(!acc.has_pending());
    }

    #[test]
    fn test_should_flush_time() {
        let config = BatchConfig {
            max_wait_ms: 100,
            min_interval_ms: 0,
            ..Default::default()
        };
        let mut acc = BatchAccumulator::new(config);

        acc.add(make_position_op(1, 1000), 1000);

        // Not enough time passed
        assert!(!acc.should_flush(1050));

        // Time limit reached
        assert!(acc.should_flush(1100));
    }

    #[test]
    fn test_should_flush_size() {
        let config = BatchConfig {
            max_bytes: 20, // Small limit (each position op is ~21 bytes)
            min_interval_ms: 0,
            ..Default::default()
        };
        let mut acc = BatchAccumulator::new(config);

        // First op (21 bytes) exceeds max_bytes (20), but allowed since batch is empty
        assert!(acc.add(make_position_op(1, 1000), 1000));
        // Should flush because we've exceeded max_bytes
        assert!(acc.should_flush(1000));
    }

    #[test]
    fn test_min_interval() {
        let config = BatchConfig {
            max_wait_ms: 100,
            min_interval_ms: 1000,
            ..Default::default()
        };
        let mut acc = BatchAccumulator::new(config);

        acc.add(make_position_op(1, 0), 0);
        acc.flush(0);

        acc.add(make_position_op(2, 100), 100);

        // Min interval not passed
        assert!(!acc.should_flush(500));

        // Min interval passed
        assert!(acc.should_flush(1100));
    }

    #[test]
    fn test_batch_encode_decode() {
        let batch = OperationBatch {
            operations: vec![make_position_op(1, 1000), make_position_op(2, 2000)],
            total_bytes: 100,
            created_at: 3000,
        };

        let encoded = batch.encode();
        let decoded = OperationBatch::decode(&encoded).unwrap();

        assert_eq!(decoded.len(), 2);
    }

    #[test]
    fn test_clear() {
        let mut acc = BatchAccumulator::with_defaults();

        acc.add(make_position_op(1, 1000), 1000);
        acc.add(make_position_op(2, 1001), 1001);

        acc.clear();
        assert!(!acc.has_pending());
        assert_eq!(acc.accumulated_bytes(), 0);
    }

    #[test]
    fn test_force_flush() {
        let config = BatchConfig {
            min_interval_ms: 10000, // Long interval
            ..Default::default()
        };
        let mut acc = BatchAccumulator::new(config);

        acc.add(make_position_op(1, 0), 0);
        acc.flush(0);

        acc.add(make_position_op(2, 100), 100);

        // Normal flush blocked by min_interval
        assert!(!acc.should_flush(100));

        // Force flush works anyway
        let batch = acc.force_flush(100);
        assert!(batch.is_some());
    }
}