-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
220 lines (182 loc) · 6.09 KB
/
lib.rs
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
mod error;
pub mod log;
pub mod param;
pub mod commander;
mod value;
// Async executor selection
#[cfg(feature = "async-std")]
pub(crate) use async_std::task::spawn as spawn;
#[cfg(feature = "wasm-bindgen-futures")]
use wasm_bindgen_futures::spawn_local as spawn;
pub use crate::error::{Error, Result};
pub(crate) use crate::log::Log;
pub(crate) use crate::param::Param;
pub(crate) use crate::commander::Commander;
pub use crate::value::{Value, ValueType};
use async_trait::async_trait;
use crazyflie_link::Packet;
use flume as channel;
use flume::{Receiver, Sender};
use std::collections::BTreeMap;
use std::{
convert::{TryFrom, TryInto},
sync::Arc,
};
#[derive(Debug)]
pub struct Crazyflie {
uplink: channel::Sender<Packet>,
pub log: Log,
pub param: Param,
pub commander: Commander,
}
impl Crazyflie {
pub async fn connect_from_uri(link_context: &crazyflie_link::LinkContext, uri: &str) -> Self {
let link = link_context.open_link(uri).await.unwrap();
Self::connect_from_link(link).await
}
pub async fn connect_from_link(link: crazyflie_link::Connection) -> Self {
// Downlink dispatcher
let link = Arc::new(link);
let mut dispatcher = CrtpDispatch::new(link.clone());
// Uplink queue
let (uplink, rx) = channel::unbounded();
spawn(async move {
while let Ok(pk) = rx.recv_async().await {
if link.send_packet(pk).await.is_err() {
break;
}
}
});
// Create subsystems one by one
// The future is passed to join!() later down so that all modules initializes at the same time
let log_downlink = dispatcher.get_port_receiver(5).unwrap();
let log = Log::new(log_downlink, uplink.clone());
let param_downlink = dispatcher.get_port_receiver(2).unwrap();
let param = Param::new(param_downlink, uplink.clone());
let commander = Commander::new(uplink.clone());
// Start the downlink packet dispatcher
dispatcher.run().await;
// Intitialize all modules in parallel
let (log, param) = futures::join!(log, param);
Crazyflie { uplink, log, param, commander }
}
}
struct CrtpDispatch {
link: Arc<crazyflie_link::Connection>,
// port_callbacks: [Arc<Mutex<Option<Sender<Packet>>>>; 15]
port_channels: BTreeMap<u8, Sender<Packet>>,
}
impl CrtpDispatch {
fn new(link: Arc<crazyflie_link::Connection>) -> Self {
CrtpDispatch {
link,
port_channels: BTreeMap::new(),
}
}
#[allow(clippy::map_entry)]
fn get_port_receiver(&mut self, port: u8) -> Option<Receiver<Packet>> {
if self.port_channels.contains_key(&port) {
None
} else {
let (tx, rx) = channel::unbounded();
self.port_channels.insert(port, tx);
Some(rx)
}
}
async fn run(self) {
let link = self.link.clone();
spawn(async move {
loop {
let packet = link.recv_packet().await.unwrap();
if packet.get_port() < 16 {
let channel = self.port_channels.get(&packet.get_port()); // get(packet.get_port()).lock().await;
if let Some(channel) = channel.as_ref() {
let _ = channel.send_async(packet).await;
}
}
}
});
}
}
#[async_trait]
trait WaitForPacket {
async fn wait_packet(&self, port: u8, channel: u8, data_prefix: &[u8]) -> Packet;
}
#[async_trait]
impl WaitForPacket for channel::Receiver<Packet> {
async fn wait_packet(&self, port: u8, channel: u8, data_prefix: &[u8]) -> Packet {
let mut pk = self.recv_async().await.unwrap();
loop {
if pk.get_port() == port
&& pk.get_channel() == channel
&& pk.get_data().starts_with(data_prefix)
{
break;
}
pk = self.recv_async().await.unwrap();
}
pk
}
}
const TOC_CHANNEL: u8 = 0;
const TOC_GET_ITEM: u8 = 2;
const TOC_INFO: u8 = 3;
async fn fetch_toc<T, E>(
port: u8,
uplink: channel::Sender<Packet>,
downlink: channel::Receiver<Packet>,
) -> std::collections::BTreeMap<String, (u16, T)>
where
T: TryFrom<u8, Error = E>,
E: std::fmt::Debug,
{
let pk = Packet::new(port, 0, vec![TOC_INFO]);
uplink.send_async(pk).await.unwrap();
let pk = downlink.wait_packet(port, TOC_CHANNEL, &[TOC_INFO]).await;
let toc_len = u16::from_le_bytes(pk.get_data()[1..3].try_into().unwrap());
let mut toc = std::collections::BTreeMap::new();
for i in 0..toc_len {
let pk = Packet::new(
port,
0,
vec![TOC_GET_ITEM, (i & 0x0ff) as u8, (i >> 8) as u8],
);
uplink.send_async(pk).await.unwrap();
let pk = downlink.wait_packet(port, 0, &[TOC_GET_ITEM]).await;
let mut strings = pk.get_data()[4..].split(|b| *b == 0);
let group = String::from_utf8_lossy(strings.next().expect("TOC packet format error"));
let name = String::from_utf8_lossy(strings.next().expect("TOC packet format error"));
let id = u16::from_le_bytes(pk.get_data()[1..3].try_into().unwrap());
let item_type = pk.get_data()[3].try_into().unwrap();
toc.insert(format!("{}.{}", group, name), (id, item_type));
}
toc
}
pub fn crtp_channel_dispatcher(
downlink: channel::Receiver<Packet>,
) -> (
Receiver<Packet>,
Receiver<Packet>,
Receiver<Packet>,
Receiver<Packet>,
) {
let (mut senders, mut receivers) = (Vec::new(), Vec::new());
for _ in 0..4 {
let (tx, rx) = channel::unbounded();
senders.push(tx);
receivers.insert(0, rx);
}
spawn(async move {
while let Ok(pk) = downlink.recv_async().await {
if pk.get_channel() < 4 {
let _ = senders[pk.get_channel() as usize].send_async(pk).await;
}
}
});
(
receivers.pop().unwrap(),
receivers.pop().unwrap(),
receivers.pop().unwrap(),
receivers.pop().unwrap(),
)
}