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
use super::PROTOCOL_ID;
use alloc::collections::btree_map::BTreeMap;
use alloc::vec::Vec;
use log::info;
use unmp::net::{self, Id};
#[derive(Clone)]
pub struct Cfg {
pub interval: usize,
pub inc: usize,
pub times: usize,
}
struct Data {
buf: Vec<u8>,
id: Id,
cfg: Cfg,
t: usize,
}
pub struct Sender {
need_resend: bool,
datas: BTreeMap<u16, Data>,
}
impl Sender {
pub fn new() -> Self {
Sender {
need_resend: false,
datas: BTreeMap::new(),
}
}
pub fn send(&mut self, index: u16, buf: Vec<u8>, id: Id, cfg: Cfg) {
net::send(PROTOCOL_ID, &buf, Some(&id), None);
if self.need_resend {
let data = Data {
buf: buf,
id: id,
cfg: cfg,
t: 0,
};
self.datas.insert(index, data);
}
}
pub fn resend(&mut self) {
if self.need_resend != true {
self.need_resend = true;
}
let mut removes: Vec<u16> = Vec::new();
for (index, data) in &mut self.datas {
data.t += 1;
if data.t >= data.cfg.interval {
data.t = 0;
data.cfg.times -= 1;
net::send(PROTOCOL_ID, &data.buf, Some(&data.id), None);
if data.cfg.times <= 0 {
info!("etp msg {} timeout.", index);
removes.push(*index)
} else {
data.cfg.interval = data.cfg.interval + data.cfg.inc;
}
}
}
for index in &removes {
self.datas.remove(&index);
}
}
pub fn finish(&mut self, index: u16) {
self.datas.remove(&index);
}
}