-
Notifications
You must be signed in to change notification settings - Fork 46
/
lib.rs
364 lines (331 loc) · 13.4 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
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
#![no_std]
#![allow(async_fn_in_trait)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
#[cfg(feature = "lorawan-radio")]
#[cfg_attr(docsrs, doc(cfg(feature = "lorawan-radio")))]
/// Provides an implementation of the async LoRaWAN device trait.
pub mod lorawan_radio;
/// The read/write interface between an embedded framework/MCU combination and a LoRa chip
pub(crate) mod interface;
/// InterfaceVariant implementations using `embedded-hal`.
pub mod iv;
/// Parameters used across the lora-phy crate to support various use cases
pub mod mod_params;
/// Traits implemented externally or internally to support control of LoRa chips
pub mod mod_traits;
/// Specific implementation to support Semtech Sx126x chips
pub mod sx126x;
/// Specific implementation to support Semtech Sx127x chips
pub mod sx127x;
pub use crate::mod_params::RxMode;
pub use embedded_hal_async::delay::DelayNs;
use interface::*;
use mod_params::*;
use mod_traits::*;
/// Provides the physical layer API to support LoRa chips
pub struct LoRa<RK, DLY>
where
RK: RadioKind,
DLY: DelayNs,
{
radio_kind: RK,
delay: DLY,
radio_mode: RadioMode,
enable_public_network: bool,
cold_start: bool,
calibrate_image: bool,
}
impl<RK, DLY> LoRa<RK, DLY>
where
RK: RadioKind,
DLY: DelayNs,
{
/// Build and return a new instance of the LoRa physical layer API to control an initialized LoRa radio
pub async fn new(radio_kind: RK, enable_public_network: bool, delay: DLY) -> Result<Self, RadioError> {
let mut lora = Self {
radio_kind,
delay,
radio_mode: RadioMode::Sleep,
enable_public_network,
cold_start: true,
calibrate_image: true,
};
lora.init().await?;
Ok(lora)
}
/// Wait for an IRQ event to occur
pub async fn wait_for_irq(&mut self) -> Result<(), RadioError> {
self.radio_kind.await_irq().await
}
/// Process an IRQ event and return the new state of the radio
pub async fn process_irq_event(&mut self) -> Result<Option<IrqState>, RadioError> {
self.radio_kind.process_irq_event(self.radio_mode, None, false).await
}
/// Create modulation parameters for a communication channel
pub fn create_modulation_params(
&mut self,
spreading_factor: SpreadingFactor,
bandwidth: Bandwidth,
coding_rate: CodingRate,
frequency_in_hz: u32,
) -> Result<ModulationParams, RadioError> {
self.radio_kind
.create_modulation_params(spreading_factor, bandwidth, coding_rate, frequency_in_hz)
}
/// Create packet parameters for a send operation on a communication channel
pub fn create_tx_packet_params(
&mut self,
preamble_length: u16,
implicit_header: bool,
crc_on: bool,
iq_inverted: bool,
modulation_params: &ModulationParams,
) -> Result<PacketParams, RadioError> {
self.radio_kind.create_packet_params(
preamble_length,
implicit_header,
0,
crc_on,
iq_inverted,
modulation_params,
)
}
/// Create packet parameters for a receive operation on a communication channel
pub fn create_rx_packet_params(
&mut self,
preamble_length: u16,
implicit_header: bool,
max_payload_length: u8,
crc_on: bool,
iq_inverted: bool,
modulation_params: &ModulationParams,
) -> Result<PacketParams, RadioError> {
self.radio_kind.create_packet_params(
preamble_length,
implicit_header,
max_payload_length,
crc_on,
iq_inverted,
modulation_params,
)
}
/// Initialize a Semtech chip as the radio for LoRa physical layer communications
pub async fn init(&mut self) -> Result<(), RadioError> {
self.cold_start = true;
self.radio_kind.reset(&mut self.delay).await?;
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
self.do_cold_start().await
}
async fn do_cold_start(&mut self) -> Result<(), RadioError> {
self.radio_kind.init_lora(self.enable_public_network).await?;
self.radio_kind.set_tx_power_and_ramp_time(0, None, false).await?;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
self.cold_start = false;
self.calibrate_image = true;
Ok(())
}
/// Place the LoRa physical layer in standby mode
pub async fn enter_standby(&mut self) -> Result<(), RadioError> {
self.radio_kind.set_standby().await
}
/// Place the LoRa physical layer in low power mode, specifying cold or warm start (if the Semtech chip supports it)
pub async fn sleep(&mut self, warm_start_if_possible: bool) -> Result<(), RadioError> {
if self.radio_mode != RadioMode::Sleep {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind
.set_sleep(warm_start_if_possible, &mut self.delay)
.await?;
if !warm_start_if_possible {
self.cold_start = true;
}
self.radio_mode = RadioMode::Sleep;
}
Ok(())
}
/// Prepare the Semtech chip for a send operation
pub async fn prepare_for_tx(
&mut self,
mdltn_params: &ModulationParams,
tx_pkt_params: &mut PacketParams,
output_power: i32,
buffer: &[u8],
) -> Result<(), RadioError> {
self.prepare_modem(mdltn_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind
.set_tx_power_and_ramp_time(output_power, Some(mdltn_params), true)
.await?;
self.radio_kind.ensure_ready(self.radio_mode).await?;
if self.radio_mode != RadioMode::Standby {
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
tx_pkt_params.set_payload_length(buffer.len())?;
self.radio_kind.set_packet_params(tx_pkt_params).await?;
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_kind.set_payload(buffer).await?;
self.radio_mode = RadioMode::Transmit;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
Ok(())
}
/// Execute a send operation
pub async fn tx(&mut self) -> Result<(), RadioError> {
if let RadioMode::Transmit = self.radio_mode {
self.radio_kind.do_tx().await?;
loop {
self.wait_for_irq().await?;
match self.radio_kind.process_irq_event(self.radio_mode, None, true).await {
Ok(Some(IrqState::Done | IrqState::PreambleReceived)) => {
self.radio_mode = RadioMode::Standby;
return Ok(());
}
Ok(None) => continue,
Err(err) => {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
return Err(err);
}
}
}
} else {
Err(RadioError::InvalidRadioMode)
}
}
/// Prepare radio to receive a frame in either single or continuous packet mode.
/// Notes:
/// * sx126x SetRx(0 < timeout < MAX) will listen util LoRa packet header is detected,
/// therefore we only use 0 (Single Mode) and MAX (continuous) values.
/// TODO: Find a way to express timeout for sx126x, allowing waiting for packet upto 262s
/// TODO: Allow DutyCycle as well?
pub async fn prepare_for_rx(
&mut self,
listen_mode: RxMode,
mdltn_params: &ModulationParams,
rx_pkt_params: &PacketParams,
) -> Result<(), RadioError> {
defmt::trace!("RX mode: {}", listen_mode);
self.prepare_modem(mdltn_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind.set_packet_params(rx_pkt_params).await?;
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_mode = listen_mode.into();
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
Ok(())
}
/// Start receiving and wait for result
pub async fn rx(
&mut self,
packet_params: &PacketParams,
receiving_buffer: &mut [u8],
) -> Result<(u8, PacketStatus), RadioError> {
if let RadioMode::Receive(listen_mode) = self.radio_mode {
self.radio_kind.do_rx(listen_mode).await?;
loop {
self.wait_for_irq().await?;
match self.radio_kind.process_irq_event(self.radio_mode, None, true).await {
Ok(Some(actual_state)) => match actual_state {
IrqState::PreambleReceived => continue,
IrqState::Done => {
let received_len = self.radio_kind.get_rx_payload(packet_params, receiving_buffer).await?;
let rx_pkt_status = self.radio_kind.get_rx_packet_status().await?;
return Ok((received_len, rx_pkt_status));
}
},
Ok(None) => continue,
Err(err) => {
// if in rx continuous mode, allow the caller to determine whether to keep receiving
if self.radio_mode != RadioMode::Receive(RxMode::Continuous) {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
return Err(err);
}
}
}
} else {
Err(RadioError::InvalidRadioMode)
}
}
/// Prepare the Semtech chip for a channel activity detection operation
pub async fn prepare_for_cad(&mut self, mdltn_params: &ModulationParams) -> Result<(), RadioError> {
self.prepare_modem(mdltn_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_mode = RadioMode::ChannelActivityDetection;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
Ok(())
}
/// Start channel activity detection operation and return the result
pub async fn cad(&mut self, mdltn_params: &ModulationParams) -> Result<bool, RadioError> {
if self.radio_mode == RadioMode::ChannelActivityDetection {
self.radio_kind.do_cad(mdltn_params).await?;
self.wait_for_irq().await?;
let mut cad_activity_detected = false;
match self
.radio_kind
.process_irq_event(self.radio_mode, Some(&mut cad_activity_detected), true)
.await
{
Ok(Some(IrqState::Done)) => Ok(cad_activity_detected),
Err(err) => {
self.radio_kind.ensure_ready(self.radio_mode).await?;
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
Err(err)
}
Ok(_) => unreachable!(),
}
} else {
Err(RadioError::InvalidRadioMode)
}
}
/// Place radio in continuous wave mode, generally for regulatory testing
///
/// SemTech app note AN1200.26 “Semtech LoRa FCC 15.247 Guidance” covers usage.
///
/// Presumes that init() is called before this function
pub async fn continuous_wave(
&mut self,
mdltn_params: &ModulationParams,
output_power: i32,
) -> Result<(), RadioError> {
self.prepare_modem(mdltn_params).await?;
let tx_pkt_params = self
.radio_kind
.create_packet_params(0, false, 16, false, false, mdltn_params)?;
self.radio_kind.set_packet_params(&tx_pkt_params).await?;
self.radio_kind.set_modulation_params(mdltn_params).await?;
self.radio_kind
.set_tx_power_and_ramp_time(output_power, Some(mdltn_params), true)
.await?;
self.radio_kind.ensure_ready(self.radio_mode).await?;
if self.radio_mode != RadioMode::Standby {
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
self.radio_kind.set_channel(mdltn_params.frequency_in_hz).await?;
self.radio_mode = RadioMode::Transmit;
self.radio_kind.set_irq_params(Some(self.radio_mode)).await?;
self.radio_kind.set_tx_continuous_wave_mode().await
}
async fn prepare_modem(&mut self, mdltn_params: &ModulationParams) -> Result<(), RadioError> {
self.radio_kind.ensure_ready(self.radio_mode).await?;
if self.radio_mode != RadioMode::Standby {
self.radio_kind.set_standby().await?;
self.radio_mode = RadioMode::Standby;
}
if self.cold_start {
self.do_cold_start().await?;
}
if self.calibrate_image {
self.radio_kind.calibrate_image(mdltn_params.frequency_in_hz).await?;
self.calibrate_image = false;
}
Ok(())
}
}