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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]

pub mod ble;
use ble::{BleChannel, BleConfig};
pub mod flrc;
use flrc::{FlrcChannel, FlrcConfig};
pub mod gfsk;
use gfsk::{GfskChannel, GfskConfig};
pub mod lora;
use lora::{LoRaChannel, LoRaConfig};

pub mod common;


/// Sx128x general configuration object
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub struct Config {
    /// Regulator mode configuration
    pub regulator_mode: RegulatorMode,

    /// Power amplifier configuration
    pub pa_config: PaConfig,

    /// Internal packet type field to track configurations
    pub(crate) packet_type: PacketType,
        
    /// RF Modem configuration
    /// 
    /// (note this must match the modulation configuration)
    pub modem: Modem,

    /// RF Modulation / Channel configuration
    /// 
    /// (note this must match the packet configuration)
    pub channel: Channel,
    
    pub timeout: Timeout,
}

impl Default for Config {
    fn default() -> Self {
        Config{
            regulator_mode: RegulatorMode::Dcdc,
            pa_config: PaConfig{ power: 10, ramp_time: RampTime::Ramp20Us },
            packet_type: PacketType::None,
            modem: Modem::LoRa(LoRaConfig::default()),
            channel: Channel::LoRa(LoRaChannel::default()),
            //timeout: Timeout::Configurable{ step: TickSize::TickSize1000us, count: 1000 },
            timeout: Timeout::Single,
        }
    }
}

/// Radio modem configuration contains fields for each modem mode
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum Modem {
    Gfsk(GfskConfig),
    LoRa(LoRaConfig),
    Flrc(FlrcConfig),
    Ble(BleConfig),
    Ranging(LoRaConfig),
    None,
}

impl Modem {
    pub fn set_payload_len(&mut self, len: u8) {
        match self {
            Modem::Gfsk(c) => c.payload_length = len,
            Modem::LoRa(c) => c.payload_length = len,
            Modem::Flrc(c) => c.payload_length = len,
            _ => (),
        }
    }
}

impl From<&Modem> for PacketType {
    fn from(m: &Modem) -> Self {
         match m {
            Modem::Gfsk(_) => PacketType::Gfsk,
            Modem::LoRa(_) => PacketType::LoRa,
            Modem::Ranging(_) => PacketType::LoRa,
            Modem::Flrc(_) => PacketType::Flrc,
            Modem::Ble(_) => PacketType::Ble,
            Modem::None => PacketType::None,
        }
    }
}

/// Radio channel configuration contains channel options for each mode
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum Channel {
    Gfsk(GfskChannel),
    LoRa(LoRaChannel),
    Flrc(FlrcChannel),
    Ble(BleChannel),
    Ranging(LoRaChannel),
}

impl Default for Channel {
    fn default() -> Self {
        Channel::LoRa(LoRaChannel::default())
    }
}

impl Channel {
    /// Fetch frequency for a given modulation configuration
    pub fn frequency(&self) -> u32 {
        use Channel::*;

        match self {
            Gfsk(c) => c.freq,
            LoRa(c) => c.freq,
            Flrc(c) => c.freq,
            Ble(c) => c.freq,
            Ranging(c) => c.freq,
        }
    }
}

impl From<&Channel> for PacketType {
    fn from(m: &Channel) -> Self {
        use Channel::*;

        match m {
            Gfsk(_) => PacketType::Gfsk,
            LoRa(_) => PacketType::LoRa,
            Ranging(_) => PacketType::LoRa,
            Flrc(_) => PacketType::Flrc,
            Ble(_) => PacketType::Ble,
        }
    }
}

/// Radio state
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum State {
    Sleep       = 0x00,
    StandbyRc   = 0x01,
    StandbyXosc = 0x02,
    Fs          = 0x03,
    Tx          = 0x04,
    Rx          = 0x05,
    Cad         = 0x06,
}

impl core::convert::TryFrom<u8> for State {
    type Error = ();

    fn try_from(v: u8) -> Result<State, ()> {
        match v {
            0x00 => Ok(State::Sleep),
            0x01 => Ok(State::StandbyRc),
            0x02 => Ok(State::StandbyXosc),
            0x03 => Ok(State::Fs),
            0x04 => Ok(State::Tx),
            0x05 => Ok(State::Rx),
            0x06 => Ok(State::Cad),
            _ => Err(())
        }
    }
}

/// Power Amplifier configuration
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub struct PaConfig {
    /// Power in dBm
    pub power: i8,
    /// Ramp time for power amplifier
    pub ramp_time: RampTime,
}

/// Receive packet information
#[derive(Clone, Debug, PartialEq)]
pub struct PacketInfo {
    pub rssi: i16,
    pub rssi_sync: Option<i16>,
    pub snr: Option<i16>,

    pub packet_status: PacketStatus,
    pub tx_rx_status: TxRxStatus,
    pub sync_addr_status: u8,
}

impl Default for PacketInfo {
    fn default() -> Self {
        Self {
            rssi: -100,
            rssi_sync: None,
            snr: None,
            packet_status: PacketStatus::empty(),
            tx_rx_status: TxRxStatus::empty(),
            sync_addr_status: 0,
        }
    }
}

/// Regulator operating mode
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum RegulatorMode {
    /// Internal LDO
    Ldo  = 0x00,
    /// Internal DC/DC converter
    Dcdc = 0x01,
}

/// Power amplifier ramp time
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum RampTime {
    /// Ramp over 2us
    Ramp02Us = 0x00,
    /// Ramp over 4us
    Ramp04Us = 0x20,
    /// Ramp over 6us
    Ramp06Us = 0x40,
    /// Ramp over 8us
    Ramp08Us = 0x60,
    /// Ramp over 10us
    Ramp10Us = 0x80,
    /// Ramp over 12us
    Ramp12Us = 0xA0,
    /// Ramp over 16us
    Ramp16Us = 0xC0,
    /// Ramp over 20us
    Ramp20Us = 0xE0,
}

/// Packet type enumeration
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum PacketType {
    Gfsk     = 0x00,
    LoRa     = 0x01,
    Ranging  = 0x02,
    Flrc     = 0x03,
    Ble      = 0x04,
    None     = 0x0F,
}

/// Radio commands
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum Commands {
    GetStatus                = 0xC0,
    WiteRegister             = 0x18,
    ReadRegister             = 0x19,
    WriteBuffer              = 0x1A,
    ReadBuffer               = 0x1B,
    SetSleep                 = 0x84,
    SetStandby               = 0x80,
    SetFs                    = 0xC1,
    SetTx                    = 0x83,
    SetRx                    = 0x82,
    SetRxDutyCycle           = 0x94,
    SetCad                   = 0xC5,
    SetTxContinuousWave      = 0xD1,
    SetTxContinuousPreamble  = 0xD2,
    SetPacketType            = 0x8A,
    GetPacketType            = 0x03,
    SetRfFrequency           = 0x86,
    SetTxParams              = 0x8E,
    SetCadParams             = 0x88,
    SetBufferBaseAddress     = 0x8F,
    SetModulationParams      = 0x8B,
    SetPacketParams          = 0x8C,
    GetRxBufferStatus        = 0x17,
    GetPacketStatus          = 0x1D,
    GetRssiInst              = 0x1F,
    SetDioIrqParams          = 0x8D,
    GetIrqStatus             = 0x15,
    ClearIrqStatus           = 0x97,
    Calibrate                = 0x89,
    SetRegulatorMode         = 0x96,
    SetSaveContext           = 0xD5,
    SetAutoTx                = 0x98,
    SetAutoFs                = 0x9E,
    SetLongPreamble          = 0x9B,
    SetUartSpeed             = 0x9D,
    SetRangingRole           = 0xA3,
}

/// Radio registers
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum Registers {
    LrFirmwareVersionMsb               = 0x0153,
    LrCrcSeedBaseAddr                  = 0x09C8,
    LrCrcPolyBaseAddr                  = 0x09C6,
    LrWhitSeedBaseAddr                 = 0x09C5,
    LrRangingIdCheckLength             = 0x0931,
    LrDeviceRangingAddr                = 0x0916,
    LrRequestRangingAddr               = 0x0912,
    LrRangingResultConfig              = 0x0924,
    LrRangingResultBaseAddr            = 0x0961,
    LrRangingResultsFreeze             = 0x097F,
    LrRangingReRxTxDelayCal            = 0x092C,
    LrRangingFilterWindowSize          = 0x091E,
    LrRangingResultClearReg            = 0x0923,
    RangingRssi                        = 0x0964,
    LrPacketParams                     = 0x903,
    LrPayloadLength                    = 0x901,
    LrSyncWordBaseAddress1             = 0x09CE,
    LrSyncWordBaseAddress2             = 0x09D3,
    LrSyncWordBaseAddress3             = 0x09D8,
    LrEstimatedFrequencyErrorMsb       = 0x0954,
    LrSyncWordTolerance                = 0x09CD,
    LrBleAccessAddress                 = 0x09CF,
    LnaRegime                          = 0x0891,
    EnableManuaLGainControl            = 0x089F,
    DemodDetection                     = 0x0895,
    ManualGainValue                    = 0x089E,
}

pub const MASK_RANGINGMUXSEL: u8       = 0xCF;
pub const MASK_LNA_REGIME: u8          = 0xC0;
pub const MASK_MANUAL_GAIN_CONTROL: u8 = 0x80;
pub const MASK_DEMOD_DETECTION: u8     = 0xFE;
pub const MASK_MANUAL_GAIN_VALUE: u8   = 0xF0;

pub const MASK_LR_ESTIMATED_FREQUENCY_ERROR: u32 = 0x0FFFFF;

pub const AUTO_RX_TX_OFFSET: u16 = 33;

#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum AutoTx {
    /// Enable AutoTX with the provided timeout in microseconds (uS)
    Enabled(u16),
    /// Disable AutoTx
    Disabled,
}

bitflags! {
    /// Interrupt flags register 
    pub struct Irq: u16 {
        const TX_DONE                             = 0x0001;
        const RX_DONE                             = 0x0002;
        const SYNCWORD_VALID                      = 0x0004;
        const SYNCWORD_ERROR                      = 0x0008;
        const HEADER_VALID                        = 0x0010;
        const HEADER_ERROR                        = 0x0020;
        const CRC_ERROR                           = 0x0040;
        const RANGING_SLAVE_RESPONSE_DONE         = 0x0080;
        const RANGING_SLAVE_REQUEST_DISCARDED     = 0x0100;
        const RANGING_MASTER_RESULT_VALID         = 0x0200;
        const RANGING_MASTER_RESULT_TIMEOUT       = 0x0400;
        const RANGING_SLAVE_REQUEST_VALID         = 0x0800;
        const CAD_DONE                            = 0x1000;
        const CAD_ACTIVITY_DETECTED               = 0x2000;
        const RX_TX_TIMEOUT                       = 0x4000;
        const PREAMBLE_DETECTED                   = 0x8000;
    }
}


bitflags! {
    /// Packet status register
    pub struct PacketStatus: u8 {
        /// Top flag value unknown due to lack of complete datasheet
        const UNKNOWN               = (1 << 7);
        const SYNC_ERROR            = (1 << 6);
        const LENGTH_ERROR          = (1 << 5);
        const CRC_ERROR             = (1 << 4);
        const ABORT_ERROR           = (1 << 3);
        const HEADER_RECEIVED       = (1 << 2);
        const PACKET_RECEIVED       = (1 << 1);
        const PACKET_CONTROLER_BUSY = (1 << 0);
    }
}


bitflags! {
    /// TxRx status packet status byte
    pub struct TxRxStatus: u8 {
        /// Top flag value unknown due to lack of complete datasheet
        const RX_NO_ACK             = (1 << 5);
        const PACKET_SENT           = (1 << 0);
    }
}

bitflags! {
    /// TxRx status register
    pub struct SyncAddrStatus: u8 {
        const SYNC_ERROR            = (1 << 6);
    }
}


bitflags! {
    /// Radio calibration parameters
    pub struct CalibrationParams: u8 {
        const ADCBulkPEnable    = (1 << 5);
        const ADCBulkNEnable    = (1 << 4);
        const ADCPulseEnable    = (1 << 3);
        const PLLEnable         = (1 << 2);
        const RC13MEnable       = (1 << 1);
        const RC64KEnable       = (1 << 0);
    }
}

/// Ranging mode role
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum RangingRole {
    /// Responder listens for ranging requests and responds
    Responder = 0x00,
    /// Initiator sends ranging requests and awaits responses
    Initiator = 0x01,
}

/// TickSize for timeout calculations
#[derive(Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum TickSize {
    // 15us tick size
    TickSize0015us   = 0x00,
    // 62us tick size
    TickSize0062us   = 0x01,
    // 1000us tick size
    TickSize1000us   = 0x02,
    // 4000us tick size
    TickSize4000us   = 0x03,
}

/// Timeout confguration for autonomous radio operations
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] 
pub enum Timeout {
    /// Single tx/rx mode
    Single,
    // Configurable timeout
    Configurable {
        /// Timeout step size
        step: TickSize,
        /// Number of steps to timeout
        count: u16,
    },
    /// Continuous rx/tx mode
    Continuous,
}

impl Timeout {
    /// Fetch the TickSize from a timeout configuration
    pub fn step(&self) -> TickSize  {
        match self {
            Timeout::Single          => TickSize::TickSize0015us,
            Timeout::Configurable{step, count: _} => *step,
            Timeout::Continuous      => TickSize::TickSize0015us,
        }
    }

    /// Fetch the step count for a timeout configuration
    pub fn count(&self) -> u16 {
        match self {
            Timeout::Single          => 0x0000,
            Timeout::Configurable{step: _, count} => *count,
            Timeout::Continuous      => 0xFFFF,
        }
    }
}