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
//! # 网络层
//!
//! 网络层(net)规定了数据包格式(Packet),负责维护路由表

mod history;
pub mod packet;
mod route;

use crate::feature;
use crate::id::*;
use crate::link::Link;
use crate::protocol;
use crate::Connection;
use history::History;
use log::{info, warn};
use packet::{Packet, PacketHeader};
pub use route::get_link;
use spin::RwLock;

static CFG: RwLock<Config> = RwLock::new(Config {
    id: Id::new(&[]),
    relay: false,
});
static HISTORY: History = History::new();

/// 配置
#[derive(Default)]
pub struct Config {
    /// 本设备ID
    id: Id,
    /// 转发开关
    relay: bool,
}
impl Config {
    pub fn new(id: Id) -> Self {
        Config {
            id: id,
            relay: false,
        }
    }
    pub fn id(&self) -> &Id {
        &self.id
    }
    pub fn set_id(&mut self, id: Id) {
        self.id = id;
    }
    pub fn relay(&self) -> bool {
        self.relay
    }
    pub fn set_relay(&mut self, relay: bool) {
        self.relay = relay;
    }
}

/// 初始化
pub fn init(cfg: Config) {
    *CFG.write() = cfg;
    feature::init();
}
/// 读取本机ID
pub fn get_id() -> Id {
    return CFG.read().id.clone();
}
/// 通用发送函数
fn send_common(
    head: &PacketHeader,
    data: &[u8],
    dst: Option<&Id>,
    dst_link: Option<&Link>,
    origin: Option<&Link>,
) {
    let buf = head.generate(data);
    info!("net send: {:02X?}.", buf);
    let id: &Id = if let Some(id) = dst { id } else { head.dst() };
    if let Some(link) = dst_link {
        if let Some(origin) = origin {
            if origin == link {
                return;
            }
        }
        if feature::offline::is_enabled(id) {
            feature::offline::push(id, &buf);
            return;
        }
        let _err = link.send(&buf);
    } else {
        if dst == Some(&ID_ALL) {
            Link::broadcast(&buf);
            return;
        }
        if feature::offline::is_enabled(id) {
            feature::offline::push(id, &buf);
            return;
        }
        let id = id.clone();
        let origin = origin.cloned();
        task_stream::spawn(async move { route::sendto(&id, &buf, origin.as_ref()).await });
    }
}
/// 发送数据包到指定设备
pub fn send(protocol: u8, data: &[u8], id: &Id, link: Option<&Link>) {
    let mut head = PacketHeader::new(get_id(), id.clone());
    head.set_ttl(if id == &ID_ALL { 0 } else { 8 });
    head.set_protocol(protocol);
    send_common(&head, &data, Some(&id), link, None);
}
/// 收到了数据包
pub fn when_recv(link: &Link, buf: &[u8]) {
    info!("net recv: {:02X?}, from {}.", buf, link);
    let pkt = match Packet::parse(buf) {
        Ok(result) => result,
        Err(err) => {
            warn!("net recv err: {}", err);
            return;
        }
    };
    if !HISTORY.add(&pkt) {
        info!("net packet repeat.");
        return;
    }
    let mut head = pkt.head().clone();
    let data = pkt.data();

    if head.src() != &ID_PARENT && head.src() != &ID_ALL {
        connect(&head.src(), link.clone());
    }

    if head.dst() == &CFG.read().id || head.dst() == &ID_PARENT || head.dst() == &ID_ALL {
        let mut conn = Connection::new(head.src().clone());
        conn.set_link(link.clone());
        protocol::distribute(head.protocol(), conn, &data);
    } else if CFG.read().relay {
        if head.ttl() > 0 {
            head.set_ttl(head.ttl() - 1);
            send_common(&head, &data, None, None, Some(link));
        } else {
            info!("unmp TTL is 0.");
        }
    }
}
/// 更新路由
pub fn connect(id: &Id, link: Link) {
    route::add(id, link);
}
/// 链路断开
pub fn when_link_disconnect(link: &Link) {
    route::when_link_disconnect(link);
}
/// 注册设备断开回调
pub fn on_disconnect(cb: fn(&Id)) {
    route::on_disconnect(cb);
}