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);
    }
}