Update Radiolib version to 7.1.0

This commit is contained in:
lewisxhe
2024-12-20 10:30:28 +08:00
parent ec34aea9f7
commit 7f7f0022fe
185 changed files with 5193 additions and 2116 deletions
+10 -20
View File
@@ -81,13 +81,6 @@
#define RADIOLIB_LOW_LEVEL (0)
#endif
/*
* Enable pre-defined modules when using RadioShield, disabled by default.
*/
#if !defined(RADIOLIB_RADIOSHIELD)
#define RADIOLIB_RADIOSHIELD (0)
#endif
/*
* Enable interrupt-based timing control
* For details, see https://github.com/jgromes/RadioLib/wiki/Interrupt-Based-Timing
@@ -136,13 +129,12 @@
* Platform-specific configuration.
*
* RADIOLIB_PLATFORM - platform name, used in debugging to quickly check the correct platform is detected.
* RADIOLIB_NC - alias for unused pin, usually the largest possible value of uint8_t.
* RADIOLIB_NC - alias for unused pin, usually the largest possible value of uint32_t.
* RADIOLIB_DEFAULT_SPI - default SPIClass instance to use.
* RADIOLIB_NONVOLATILE - macro to place variable into program storage (usually Flash).
* RADIOLIB_NONVOLATILE_READ_BYTE - function/macro to read variables saved in program storage (usually Flash).
* RADIOLIB_TYPE_ALIAS - construct to create an alias for a type, usually vai the `using` keyword.
* RADIOLIB_TONE_UNSUPPORTED - some platforms do not have tone()/noTone(), which is required for AFSK.
* RADIOLIB_BUILTIN_MODULE - some platforms have a builtin radio module on fixed pins, this macro is used to specify that pinout.
*
* In addition, some platforms may require RadioLib to disable specific drivers (such as ESP8266).
*
@@ -320,10 +312,6 @@
#define RADIOLIB_ARDUINOHAL_PIN_MODE_CAST (PINMODE)
#define RADIOLIB_ARDUINOHAL_INTERRUPT_MODE_CAST (IrqModes)
// provide an easy access to the on-board module
#include "board-config.h"
#define RADIOLIB_BUILTIN_MODULE RADIO_NSS, RADIO_DIO_1, RADIO_RESET, RADIO_BUSY
// CubeCell doesn't seem to define nullptr, let's do something like that now
#define nullptr NULL
@@ -434,7 +422,7 @@
// generic non-Arduino platform
#define RADIOLIB_PLATFORM "Generic"
#define RADIOLIB_NC (0xFF)
#define RADIOLIB_NC (0xFFFFFFFF)
#define RADIOLIB_NONVOLATILE
#define RADIOLIB_NONVOLATILE_READ_BYTE(addr) (*((uint8_t *)(void *)(addr)))
#define RADIOLIB_NONVOLATILE_READ_DWORD(addr) (*((uint32_t *)(void *)(addr)))
@@ -473,10 +461,10 @@
#if RADIOLIB_DEBUG
#if defined(RADIOLIB_BUILD_ARDUINO)
#define RADIOLIB_DEBUG_PRINT(...) Module::serialPrintf(__VA_ARGS__)
#define RADIOLIB_DEBUG_PRINTLN(M, ...) Module::serialPrintf(M "\n", ##__VA_ARGS__)
#define RADIOLIB_DEBUG_PRINT_LVL(LEVEL, M, ...) Module::serialPrintf(LEVEL "" M, ##__VA_ARGS__)
#define RADIOLIB_DEBUG_PRINTLN_LVL(LEVEL, M, ...) Module::serialPrintf(LEVEL "" M "\n", ##__VA_ARGS__)
#define RADIOLIB_DEBUG_PRINT(...) rlb_printf(__VA_ARGS__)
#define RADIOLIB_DEBUG_PRINTLN(M, ...) rlb_printf(M "\n", ##__VA_ARGS__)
#define RADIOLIB_DEBUG_PRINT_LVL(LEVEL, M, ...) rlb_printf(LEVEL "" M, ##__VA_ARGS__)
#define RADIOLIB_DEBUG_PRINTLN_LVL(LEVEL, M, ...) rlb_printf(LEVEL "" M "\n", ##__VA_ARGS__)
// some platforms do not support printf("%f"), so it has to be done this way
#define RADIOLIB_DEBUG_PRINT_FLOAT(LEVEL, VAL, DECIMALS) RADIOLIB_DEBUG_PRINT(LEVEL); RADIOLIB_DEBUG_PORT.print(VAL, DECIMALS)
@@ -492,7 +480,7 @@
#define RADIOLIB_DEBUG_PRINT_FLOAT(LEVEL, VAL, DECIMALS) RADIOLIB_DEBUG_PRINT(LEVEL "%.3f", VAL)
#endif
#define RADIOLIB_DEBUG_HEXDUMP(LEVEL, ...) Module::hexdump(LEVEL, __VA_ARGS__)
#define RADIOLIB_DEBUG_HEXDUMP(LEVEL, ...) rlb_hexdump(LEVEL, __VA_ARGS__)
#else
#define RADIOLIB_DEBUG_PRINT(...) {}
#define RADIOLIB_DEBUG_PRINTLN(...) {}
@@ -561,8 +549,10 @@
*/
#if RADIOLIB_VERBOSE_ASSERT
#define RADIOLIB_ASSERT(STATEVAR) { if((STATEVAR) != RADIOLIB_ERR_NONE) { RADIOLIB_DEBUG_BASIC_PRINTLN("%d at %s:%d", STATEVAR, __FILE__, __LINE__); return(STATEVAR); } }
#define RADIOLIB_ASSERT_PTR(PTR) { if((PTR) == NULL) { RADIOLIB_DEBUG_BASIC_PRINTLN("NULL at %s:%d", __FILE__, __LINE__); return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED); } }
#else
#define RADIOLIB_ASSERT(STATEVAR) { if((STATEVAR) != RADIOLIB_ERR_NONE) { return(STATEVAR); } }
#define RADIOLIB_ASSERT_PTR(PTR) { if((PTR) == NULL) { return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED); } }
#endif
/*!
@@ -587,7 +577,7 @@
// version definitions
#define RADIOLIB_VERSION_MAJOR 7
#define RADIOLIB_VERSION_MINOR 0
#define RADIOLIB_VERSION_MINOR 1
#define RADIOLIB_VERSION_PATCH 0
#define RADIOLIB_VERSION_EXTRA 0
+23 -112
View File
@@ -1,17 +1,11 @@
#include "Module.h"
// the following is probably only needed on non-Arduino builds
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#if RADIOLIB_DEBUG
// needed for debug print
#include <stdarg.h>
#endif
#if defined(RADIOLIB_BUILD_ARDUINO)
#include "ArduinoHal.h"
#include "hal/Arduino/ArduinoHal.h"
Module::Module(uint32_t cs, uint32_t irq, uint32_t rst, uint32_t gpio) : csPin(cs), irqPin(irq), rstPin(rst), gpioPin(gpio) {
this->hal = new ArduinoHal();
@@ -339,18 +333,20 @@ int16_t Module::SPItransferStream(const uint8_t* cmd, uint8_t cmdLen, bool write
}
// ensure GPIO is low
if(this->gpioPin == RADIOLIB_NC) {
this->hal->delay(50);
} else {
RadioLibTime_t start = this->hal->millis();
while(this->hal->digitalRead(this->gpioPin)) {
this->hal->yield();
if(this->hal->millis() - start >= this->spiConfig.timeout) {
RADIOLIB_DEBUG_BASIC_PRINTLN("GPIO pre-transfer timeout, is it connected?");
#if !RADIOLIB_STATIC_ONLY
delete[] buffOut;
#endif
return(RADIOLIB_ERR_SPI_CMD_TIMEOUT);
if(waitForGpio) {
if(this->gpioPin == RADIOLIB_NC) {
this->hal->delay(50);
} else {
RadioLibTime_t start = this->hal->millis();
while(this->hal->digitalRead(this->gpioPin)) {
this->hal->yield();
if(this->hal->millis() - start >= this->spiConfig.timeout) {
RADIOLIB_DEBUG_BASIC_PRINTLN("GPIO pre-transfer timeout, is it connected?");
#if !RADIOLIB_STATIC_ONLY
delete[] buffOut;
#endif
return(RADIOLIB_ERR_SPI_CMD_TIMEOUT);
}
}
}
}
@@ -459,69 +455,7 @@ void Module::waitForMicroseconds(RadioLibTime_t start, RadioLibTime_t len) {
#endif
}
uint32_t Module::reflect(uint32_t in, uint8_t bits) {
uint32_t res = 0;
for(uint8_t i = 0; i < bits; i++) {
res |= (((in & ((uint32_t)1 << i)) >> i) << (bits - i - 1));
}
return(res);
}
#if RADIOLIB_DEBUG
void Module::hexdump(const char* level, uint8_t* data, size_t len, uint32_t offset, uint8_t width, bool be) {
size_t rem_len = len;
for(size_t i = 0; i < len; i+=16) {
char str[120];
sprintf(str, "%08" PRIx32 ": ", (uint32_t)i+offset);
size_t line_len = 16;
if(rem_len < line_len) {
line_len = rem_len;
}
for(size_t j = 0; j < line_len; j+=width) {
if(width > 1) {
int m = 0;
int step = width/2;
if(be) {
step *= -1;
}
for(int32_t k = width - 1; k >= -width + 1; k+=step) {
sprintf(&str[10 + (j+m)*3], "%02x ", data[i+j+k+m]);
m++;
}
} else {
sprintf(&str[10 + (j)*3], "%02x ", data[i+j]);
}
}
for(size_t j = line_len; j < 16; j++) {
sprintf(&str[10 + j*3], " ");
}
//str[56] = '|';
str[58] = ' ';
// at this point we need to start escaping "%" characters
char* strPtr = &str[59];
for(size_t j = 0; j < line_len; j++) {
char c = data[i+j];
if((c < ' ') || (c > '~')) {
c = '.';
} else if(c == '%') {
*strPtr++ = '%';
}
sprintf(strPtr++, "%c", c);
}
for(size_t j = line_len; j < 16; j++) {
sprintf(strPtr++, " ");
}
if(level) {
RADIOLIB_DEBUG_PRINT(level);
}
RADIOLIB_DEBUG_PRINT(str);
RADIOLIB_DEBUG_PRINTLN();
rem_len -= 16;
}
}
void Module::regdump(const char* level, uint16_t start, size_t len) {
#if RADIOLIB_STATIC_ONLY
uint8_t buff[RADIOLIB_STATIC_ARRAY_SIZE];
@@ -529,39 +463,13 @@ void Module::regdump(const char* level, uint16_t start, size_t len) {
uint8_t* buff = new uint8_t[len];
#endif
SPIreadRegisterBurst(start, len, buff);
hexdump(level, buff, len, start);
rlb_hexdump(level, buff, len, start);
#if !RADIOLIB_STATIC_ONLY
delete[] buff;
#endif
}
#endif
#if RADIOLIB_DEBUG && defined(RADIOLIB_BUILD_ARDUINO)
// https://github.com/esp8266/Arduino/blob/65579d29081cb8501e4d7f786747bf12e7b37da2/cores/esp8266/Print.cpp#L50
size_t Module::serialPrintf(const char* format, ...) {
va_list arg;
va_start(arg, format);
char temp[64];
char* buffer = temp;
size_t len = vsnprintf(temp, sizeof(temp), format, arg);
va_end(arg);
if (len > sizeof(temp) - 1) {
buffer = new char[len + 1];
if (!buffer) {
return 0;
}
va_start(arg, format);
vsnprintf(buffer, len + 1, format, arg);
va_end(arg);
}
len = RADIOLIB_DEBUG_PORT.write(reinterpret_cast<const uint8_t*>(buffer), len);
if (buffer != temp) {
delete[] buffer;
}
return len;
}
#endif
void Module::setRfSwitchPins(uint32_t rxEn, uint32_t txEn) {
// This can be on the stack, setRfSwitchTable copies the contents
const uint32_t pins[] = {
@@ -581,15 +489,17 @@ void Module::setRfSwitchPins(uint32_t rxEn, uint32_t txEn) {
void Module::setRfSwitchTable(const uint32_t (&pins)[RFSWITCH_MAX_PINS], const RfSwitchMode_t table[]) {
memcpy(this->rfSwitchPins, pins, sizeof(this->rfSwitchPins));
this->rfSwitchTable = table;
for(size_t i = 0; i < RFSWITCH_MAX_PINS; i++)
for(size_t i = 0; i < RFSWITCH_MAX_PINS; i++) {
this->hal->pinMode(pins[i], this->hal->GpioModeOutput);
}
}
const Module::RfSwitchMode_t *Module::findRfSwitchMode(uint8_t mode) const {
const RfSwitchMode_t *row = this->rfSwitchTable;
while (row && row->mode != MODE_END_OF_TABLE) {
if (row->mode == mode)
while(row && row->mode != MODE_END_OF_TABLE) {
if(row->mode == mode) {
return row;
}
++row;
}
return nullptr;
@@ -606,8 +516,9 @@ void Module::setRfSwitchState(uint8_t mode) {
const uint32_t *value = &row->values[0];
for(size_t i = 0; i < RFSWITCH_MAX_PINS; i++) {
uint32_t pin = this->rfSwitchPins[i];
if (pin != RADIOLIB_NC)
if(!(pin & RFSWITCH_PIN_FLAG)) {
this->hal->digitalWrite(pin, *value);
}
++value;
}
}
+8 -23
View File
@@ -3,6 +3,7 @@
#include "TypeDef.h"
#include "Hal.h"
#include "utils/Utils.h"
#if defined(RADIOLIB_BUILD_ARDUINO)
#include <SPI.h>
@@ -18,6 +19,13 @@
*/
#define END_OF_MODE_TABLE { Module::MODE_END_OF_TABLE, {} }
/*!
\def RFSWITCH_PIN_FLAG Bit flag used to mark unused pins in RF switch pin map. This can be either
unconnected pin marked with RADIOLIB_NC, or a pin controlled by the radio (e.g. DIOx pins on LR11x0),
as opposed to an MCU-controlled GPIO pin.
*/
#define RFSWITCH_PIN_FLAG (0x01UL << 31)
/*!
\defgroup module_spi_command_pos Position of commands in Module::spiConfig command array.
\{
@@ -505,26 +513,7 @@ class Module {
*/
void waitForMicroseconds(RadioLibTime_t start, RadioLibTime_t len);
/*!
\brief Function to reflect bits within a byte.
\param in The input to reflect.
\param bits Number of bits to reflect.
\return The reflected input.
*/
static uint32_t reflect(uint32_t in, uint8_t bits);
#if RADIOLIB_DEBUG
/*!
\brief Function to dump data as hex into the debug port.
\param level RadioLib debug level, set to NULL to not print.
\param data Data to dump.
\param len Number of bytes to dump.
\param offset Address offset to add when printing the data.
\param width Word width (1 for uint8_t, 2 for uint16_t, 4 for uint32_t).
\param be Print multi-byte data as big endian. Defaults to false.
*/
static void hexdump(const char* level, uint8_t* data, size_t len, uint32_t offset = 0, uint8_t width = 1, bool be = false);
/*!
\brief Function to dump device registers as hex into the debug port.
\param level RadioLib debug level, set to NULL to not print.
@@ -534,10 +523,6 @@ class Module {
void regdump(const char* level, uint16_t start, size_t len);
#endif
#if RADIOLIB_DEBUG and defined(RADIOLIB_BUILD_ARDUINO)
static size_t serialPrintf(const char* format, ...);
#endif
#if !RADIOLIB_GODMODE
private:
#endif
+1 -43
View File
@@ -40,7 +40,7 @@
#include "Hal.h"
#if defined(RADIOLIB_BUILD_ARDUINO)
#include "ArduinoHal.h"
#include "hal/Arduino/ArduinoHal.h"
#endif
@@ -114,46 +114,4 @@
#include "utils/CRC.h"
#include "utils/Cryptography.h"
// only create Radio class when using RadioShield
#if RADIOLIB_RADIOSHIELD
// RadioShield pin definitions
#define RADIOSHIELD_CS_A 10
#define RADIOSHIELD_IRQ_A 2
#define RADIOSHIELD_RST_A 9
#define RADIOSHIELD_GPIO_A 8
#define RADIOSHIELD_CS_B 5
#define RADIOSHIELD_IRQ_B 3
#define RADIOSHIELD_RST_B 7
#define RADIOSHIELD_GPIO_B 6
/*!
\class Radio
\brief Library control object when using RadioShield.
Contains two pre-configured "modules", which correspond to the slots on shield.
*/
class Radio {
public:
Module* ModuleA;
Module* ModuleB;
/*!
\brief Default constructor. Only used to set ModuleA and ModuleB configuration.
*/
Radio() {
ModuleA = new Module(RADIOSHIELD_CS_A, RADIOSHIELD_IRQ_A, RADIOSHIELD_RST_A, RADIOSHIELD_GPIO_A);
ModuleB = new Module(RADIOSHIELD_CS_B, RADIOSHIELD_IRQ_B, RADIOSHIELD_RST_B, RADIOSHIELD_GPIO_B);
}
#if RADIOLIB_GODMODE
private:
#endif
};
Radio RadioShield;
#endif
#endif
+26
View File
@@ -250,6 +250,11 @@
*/
#define RADIOLIB_ERR_NULL_POINTER (-28)
/*!
\brief The requested IRQ configuration is not valid for this module.
*/
#define RADIOLIB_ERR_INVALID_IRQ (-29)
// RF69-specific status codes
/*!
@@ -600,6 +605,27 @@
*/
#define RADIOLIB_ERR_INVALID_WIFI_TYPE (-1200)
/*!
\brief GNSS subframe not available in the next 2.3 seconds.
*/
#define RADIOLIB_ERR_GNSS_SUBFRAME_NOT_AVAILABLE (-1201)
/*!
\brief Offset of GNSS demodulator errors.
See LR11x0 datasheet for details on the actual demodulator error
*/
#define RADIOLIB_ERR_GNSS_DEMOD_OFFSET (-1210)
#define RADIOLIB_ERR_GNSS_DEMOD(X) (RADIOLIB_ERR_GNSS_DEMOD_OFFSET + (X))
#define RADIOLIB_GET_GNSS_DEMOD_ERROR(X) ((X) - RADIOLIB_ERR_GNSS_DEMOD_OFFSET)
/*!
\brief GNSS solver errors.
See LR11x0 datasheet for details on the actual solver error
*/
#define RADIOLIB_ERR_GNSS_SOLVER_OFFSET (-1230)
#define RADIOLIB_ERR_GNSS_SOLVER(X) (RADIOLIB_ERR_GNSS_SOLVER_OFFSET - (X))
#define RADIOLIB_GET_GNSS_SOLVER_ERROR(X) (-((X) - RADIOLIB_ERR_GNSS_SOLVER_OFFSET))
/*!
\}
*/
@@ -1,5 +1,5 @@
// make sure this is always compiled
#include "TypeDef.h"
#include "../../TypeDef.h"
#if !defined(_RADIOLIB_ARDUINOHAL_H)
#define _RADIOLIB_ARDUINOHAL_H
+322
View File
@@ -0,0 +1,322 @@
#ifndef ESP_HAL_H
#define ESP_HAL_H
// include RadioLib
#include <RadioLib.h>
// this example only works on ESP32 and is unlikely to work on ESP32S2/S3 etc.
// if you need high portability, you should probably use Arduino anyway ...
#if CONFIG_IDF_TARGET_ESP32 == 0
#error Target is not ESP32!
#endif
// include all the dependencies
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp32/rom/gpio.h"
#include "soc/rtc.h"
#include "soc/dport_reg.h"
#include "soc/spi_reg.h"
#include "soc/spi_struct.h"
#include "driver/gpio.h"
#include "hal/gpio_hal.h"
#include "esp_timer.h"
#include "esp_log.h"
// define Arduino-style macros
#define LOW (0x0)
#define HIGH (0x1)
#define INPUT (0x01)
#define OUTPUT (0x03)
#define RISING (0x01)
#define FALLING (0x02)
#define NOP() asm volatile ("nop")
#define MATRIX_DETACH_OUT_SIG (0x100)
#define MATRIX_DETACH_IN_LOW_PIN (0x30)
// all of the following is needed to calculate SPI clock divider
#define ClkRegToFreq(reg) (apb_freq / (((reg)->clkdiv_pre + 1) * ((reg)->clkcnt_n + 1)))
typedef union {
uint32_t value;
struct {
uint32_t clkcnt_l: 6;
uint32_t clkcnt_h: 6;
uint32_t clkcnt_n: 6;
uint32_t clkdiv_pre: 13;
uint32_t clk_equ_sysclk: 1;
};
} spiClk_t;
uint32_t getApbFrequency() {
rtc_cpu_freq_config_t conf;
rtc_clk_cpu_freq_get_config(&conf);
if(conf.freq_mhz >= 80) {
return(80 * MHZ);
}
return((conf.source_freq_mhz * MHZ) / conf.div);
}
uint32_t spiFrequencyToClockDiv(uint32_t freq) {
uint32_t apb_freq = getApbFrequency();
if(freq >= apb_freq) {
return SPI_CLK_EQU_SYSCLK;
}
const spiClk_t minFreqReg = { 0x7FFFF000 };
uint32_t minFreq = ClkRegToFreq((spiClk_t*) &minFreqReg);
if(freq < minFreq) {
return minFreqReg.value;
}
uint8_t calN = 1;
spiClk_t bestReg = { 0 };
int32_t bestFreq = 0;
while(calN <= 0x3F) {
spiClk_t reg = { 0 };
int32_t calFreq;
int32_t calPre;
int8_t calPreVari = -2;
reg.clkcnt_n = calN;
while(calPreVari++ <= 1) {
calPre = (((apb_freq / (reg.clkcnt_n + 1)) / freq) - 1) + calPreVari;
if(calPre > 0x1FFF) {
reg.clkdiv_pre = 0x1FFF;
} else if(calPre <= 0) {
reg.clkdiv_pre = 0;
} else {
reg.clkdiv_pre = calPre;
}
reg.clkcnt_l = ((reg.clkcnt_n + 1) / 2);
calFreq = ClkRegToFreq(&reg);
if(calFreq == (int32_t) freq) {
memcpy(&bestReg, &reg, sizeof(bestReg));
break;
} else if(calFreq < (int32_t) freq) {
if(RADIOLIB_ABS(freq - calFreq) < RADIOLIB_ABS(freq - bestFreq)) {
bestFreq = calFreq;
memcpy(&bestReg, &reg, sizeof(bestReg));
}
}
}
if(calFreq == (int32_t) freq) {
break;
}
calN++;
}
return(bestReg.value);
}
// create a new ESP-IDF hardware abstraction layer
// the HAL must inherit from the base RadioLibHal class
// and implement all of its virtual methods
// this is pretty much just copied from Arduino ESP32 core
class EspHal : public RadioLibHal {
public:
// default constructor - initializes the base HAL and any needed private members
EspHal(int8_t sck, int8_t miso, int8_t mosi)
: RadioLibHal(INPUT, OUTPUT, LOW, HIGH, RISING, FALLING),
spiSCK(sck), spiMISO(miso), spiMOSI(mosi) {
}
void init() override {
// we only need to init the SPI here
spiBegin();
}
void term() override {
// we only need to stop the SPI here
spiEnd();
}
// GPIO-related methods (pinMode, digitalWrite etc.) should check
// RADIOLIB_NC as an alias for non-connected pins
void pinMode(uint32_t pin, uint32_t mode) override {
if(pin == RADIOLIB_NC) {
return;
}
gpio_hal_context_t gpiohal;
gpiohal.dev = GPIO_LL_GET_HW(GPIO_PORT_0);
gpio_config_t conf = {
.pin_bit_mask = (1ULL<<pin),
.mode = (gpio_mode_t)mode,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = (gpio_int_type_t)gpiohal.dev->pin[pin].int_type,
};
gpio_config(&conf);
}
void digitalWrite(uint32_t pin, uint32_t value) override {
if(pin == RADIOLIB_NC) {
return;
}
gpio_set_level((gpio_num_t)pin, value);
}
uint32_t digitalRead(uint32_t pin) override {
if(pin == RADIOLIB_NC) {
return(0);
}
return(gpio_get_level((gpio_num_t)pin));
}
void attachInterrupt(uint32_t interruptNum, void (*interruptCb)(void), uint32_t mode) override {
if(interruptNum == RADIOLIB_NC) {
return;
}
gpio_install_isr_service((int)ESP_INTR_FLAG_IRAM);
gpio_set_intr_type((gpio_num_t)interruptNum, (gpio_int_type_t)(mode & 0x7));
// this uses function typecasting, which is not defined when the functions have different signatures
// untested and might not work
gpio_isr_handler_add((gpio_num_t)interruptNum, (void (*)(void*))interruptCb, NULL);
}
void detachInterrupt(uint32_t interruptNum) override {
if(interruptNum == RADIOLIB_NC) {
return;
}
gpio_isr_handler_remove((gpio_num_t)interruptNum);
gpio_wakeup_disable((gpio_num_t)interruptNum);
gpio_set_intr_type((gpio_num_t)interruptNum, GPIO_INTR_DISABLE);
}
void delay(unsigned long ms) override {
vTaskDelay(ms / portTICK_PERIOD_MS);
}
void delayMicroseconds(unsigned long us) override {
uint64_t m = (uint64_t)esp_timer_get_time();
if(us) {
uint64_t e = (m + us);
if(m > e) { // overflow
while((uint64_t)esp_timer_get_time() > e) {
NOP();
}
}
while((uint64_t)esp_timer_get_time() < e) {
NOP();
}
}
}
unsigned long millis() override {
return((unsigned long)(esp_timer_get_time() / 1000ULL));
}
unsigned long micros() override {
return((unsigned long)(esp_timer_get_time()));
}
long pulseIn(uint32_t pin, uint32_t state, unsigned long timeout) override {
if(pin == RADIOLIB_NC) {
return(0);
}
this->pinMode(pin, INPUT);
uint32_t start = this->micros();
uint32_t curtick = this->micros();
while(this->digitalRead(pin) == state) {
if((this->micros() - curtick) > timeout) {
return(0);
}
}
return(this->micros() - start);
}
void spiBegin() {
// enable peripheral
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI2_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI2_RST);
// reset the control struct
this->spi->slave.trans_done = 0;
this->spi->slave.val = 0;
this->spi->pin.val = 0;
this->spi->user.val = 0;
this->spi->user1.val = 0;
this->spi->ctrl.val = 0;
this->spi->ctrl1.val = 0;
this->spi->ctrl2.val = 0;
this->spi->clock.val = 0;
this->spi->user.usr_mosi = 1;
this->spi->user.usr_miso = 1;
this->spi->user.doutdin = 1;
for(uint8_t i = 0; i < 16; i++) {
this->spi->data_buf[i] = 0x00000000;
}
// set SPI mode 0
this->spi->pin.ck_idle_edge = 0;
this->spi->user.ck_out_edge = 0;
// set bit order to MSB first
this->spi->ctrl.wr_bit_order = 0;
this->spi->ctrl.rd_bit_order = 0;
// set the clock
this->spi->clock.val = spiFrequencyToClockDiv(2000000);
// initialize pins
this->pinMode(this->spiSCK, OUTPUT);
this->pinMode(this->spiMISO, INPUT);
this->pinMode(this->spiMOSI, OUTPUT);
gpio_matrix_out(this->spiSCK, HSPICLK_OUT_IDX, false, false);
gpio_matrix_in(this->spiMISO, HSPIQ_OUT_IDX, false);
gpio_matrix_out(this->spiMOSI, HSPID_IN_IDX, false, false);
}
void spiBeginTransaction() {
// not needed - in ESP32 Arduino core, this function
// repeats clock div, mode and bit order configuration
}
uint8_t spiTransferByte(uint8_t b) {
this->spi->mosi_dlen.usr_mosi_dbitlen = 7;
this->spi->miso_dlen.usr_miso_dbitlen = 7;
this->spi->data_buf[0] = b;
this->spi->cmd.usr = 1;
while(this->spi->cmd.usr);
return(this->spi->data_buf[0] & 0xFF);
}
void spiTransfer(uint8_t* out, size_t len, uint8_t* in) {
for(size_t i = 0; i < len; i++) {
in[i] = this->spiTransferByte(out[i]);
}
}
void spiEndTransaction() {
// nothing needs to be done here
}
void spiEnd() {
// detach pins
gpio_matrix_out(this->spiSCK, MATRIX_DETACH_OUT_SIG, false, false);
gpio_matrix_in(this->spiMISO, MATRIX_DETACH_IN_LOW_PIN, false);
gpio_matrix_out(this->spiMOSI, MATRIX_DETACH_OUT_SIG, false, false);
}
private:
// the HAL can contain any additional private members
int8_t spiSCK;
int8_t spiMISO;
int8_t spiMOSI;
spi_dev_t * spi = (volatile spi_dev_t *)(DR_REG_SPI2_BASE);
};
#endif
+261
View File
@@ -0,0 +1,261 @@
#ifndef PI_HAL_LGPIO_H
#define PI_HAL_LGPIO_H
// include RadioLib
#include <RadioLib.h>
// include the library for Raspberry GPIO pins
#include <lgpio.h>
#define PI_RISING (LG_RISING_EDGE)
#define PI_FALLING (LG_FALLING_EDGE)
#define PI_INPUT (0)
#define PI_OUTPUT (1)
#define PI_MAX_USER_GPIO (31)
// forward declaration of alert handler that will be used to emulate interrupts
static void lgpioAlertHandler(int num_alerts, lgGpioAlert_p alerts, void *userdata);
// create a new Raspberry Pi hardware abstraction layer
// using the lgpio library
// the HAL must inherit from the base RadioLibHal class
// and implement all of its virtual methods
class PiHal : public RadioLibHal {
public:
// default constructor - initializes the base HAL and any needed private members
PiHal(uint8_t spiChannel, uint32_t spiSpeed = 2000000, uint8_t spiDevice = 0, uint8_t gpioDevice = 0)
: RadioLibHal(PI_INPUT, PI_OUTPUT, LG_LOW, LG_HIGH, PI_RISING, PI_FALLING),
_gpioDevice(gpioDevice),
_spiDevice(spiDevice),
_spiChannel(spiChannel),
_spiSpeed(spiSpeed) {
}
void init() override {
if(_gpioHandle != -1) {
return;
}
// first initialise lgpio library
if((_gpioHandle = lgGpiochipOpen(_gpioDevice)) < 0) {
fprintf(stderr, "Could not open GPIO chip: %s\n", lguErrorText(_gpioHandle));
return;
}
// now the SPI
spiBegin();
}
void term() override {
// stop the SPI
spiEnd();
// finally, stop the lgpio library
lgGpiochipClose(_gpioHandle);
_gpioHandle = -1;
}
// GPIO-related methods (pinMode, digitalWrite etc.) should check
// RADIOLIB_NC as an alias for non-connected pins
void pinMode(uint32_t pin, uint32_t mode) override {
if(pin == RADIOLIB_NC) {
return;
}
int result;
int flags = 0;
switch(mode) {
case PI_INPUT:
result = lgGpioClaimInput(_gpioHandle, 0, pin);
break;
case PI_OUTPUT:
result = lgGpioClaimOutput(_gpioHandle, flags, pin, LG_HIGH);
break;
default:
fprintf(stderr, "Unknown pinMode mode %" PRIu32 "\n", mode);
return;
}
if(result < 0) {
fprintf(stderr, "Could not claim pin %" PRIu32 " for mode %" PRIu32 ": %s\n",
pin, mode, lguErrorText(result));
}
}
void digitalWrite(uint32_t pin, uint32_t value) override {
if(pin == RADIOLIB_NC) {
return;
}
int result = lgGpioWrite(_gpioHandle, pin, value);
if(result < 0) {
fprintf(stderr, "Error writing value to pin %" PRIu32 ": %s\n", pin, lguErrorText(result));
}
}
uint32_t digitalRead(uint32_t pin) override {
if(pin == RADIOLIB_NC) {
return(0);
}
int result = lgGpioRead(_gpioHandle, pin);
if(result < 0) {
fprintf(stderr, "Error writing reading from pin %" PRIu32 ": %s\n", pin, lguErrorText(result));
}
return result;
}
void attachInterrupt(uint32_t interruptNum, void (*interruptCb)(void), uint32_t mode) override {
if((interruptNum == RADIOLIB_NC) || (interruptNum > PI_MAX_USER_GPIO)) {
return;
}
// set lgpio alert callback
int result = lgGpioClaimAlert(_gpioHandle, 0, mode, interruptNum, -1);
if(result < 0) {
fprintf(stderr, "Could not claim pin %" PRIu32 " for alert: %s\n", interruptNum, lguErrorText(result));
return;
}
// enable emulated interrupt
interruptEnabled[interruptNum] = true;
interruptModes[interruptNum] = mode;
interruptCallbacks[interruptNum] = interruptCb;
lgGpioSetAlertsFunc(_gpioHandle, interruptNum, lgpioAlertHandler, (void *)this);
}
void detachInterrupt(uint32_t interruptNum) override {
if((interruptNum == RADIOLIB_NC) || (interruptNum > PI_MAX_USER_GPIO)) {
return;
}
// clear emulated interrupt
interruptEnabled[interruptNum] = false;
interruptModes[interruptNum] = 0;
interruptCallbacks[interruptNum] = NULL;
// disable lgpio alert callback
lgGpioFree(_gpioHandle, interruptNum);
lgGpioSetAlertsFunc(_gpioHandle, interruptNum, NULL, NULL);
}
void delay(unsigned long ms) override {
if(ms == 0) {
sched_yield();
return;
}
lguSleep(ms / 1000.0);
}
void delayMicroseconds(unsigned long us) override {
if(us == 0) {
sched_yield();
return;
}
lguSleep(us / 1000000.0);
}
void yield() override {
sched_yield();
}
unsigned long millis() override {
uint32_t time = lguTimestamp() / 1000000UL;
return time;
}
unsigned long micros() override {
uint32_t time = lguTimestamp() / 1000UL;
return time;
}
long pulseIn(uint32_t pin, uint32_t state, unsigned long timeout) override {
if(pin == RADIOLIB_NC) {
return(0);
}
this->pinMode(pin, PI_INPUT);
uint32_t start = this->micros();
uint32_t curtick = this->micros();
while(this->digitalRead(pin) == state) {
if((this->micros() - curtick) > timeout) {
return(0);
}
}
return(this->micros() - start);
}
void spiBegin() {
if(_spiHandle < 0) {
if((_spiHandle = lgSpiOpen(_spiDevice, _spiChannel, _spiSpeed, 0)) < 0) {
fprintf(stderr, "Could not open SPI handle on 0: %s\n", lguErrorText(_spiHandle));
}
}
}
void spiBeginTransaction() {}
void spiTransfer(uint8_t* out, size_t len, uint8_t* in) {
int result = lgSpiXfer(_spiHandle, (char *)out, (char*)in, len);
if(result < 0) {
fprintf(stderr, "Could not perform SPI transfer: %s\n", lguErrorText(result));
}
}
void spiEndTransaction() {}
void spiEnd() {
if(_spiHandle >= 0) {
lgSpiClose(_spiHandle);
_spiHandle = -1;
}
}
void tone(uint32_t pin, unsigned int frequency, unsigned long duration = 0) {
lgTxPwm(_gpioHandle, pin, frequency, 50, 0, duration);
}
void noTone(uint32_t pin) {
lgTxPwm(_gpioHandle, pin, 0, 0, 0, 0);
}
// interrupt emulation
bool interruptEnabled[PI_MAX_USER_GPIO + 1];
uint32_t interruptModes[PI_MAX_USER_GPIO + 1];
typedef void (*RadioLibISR)(void);
RadioLibISR interruptCallbacks[PI_MAX_USER_GPIO + 1];
private:
// the HAL can contain any additional private members
const unsigned int _spiSpeed;
const uint8_t _gpioDevice;
const uint8_t _spiDevice;
const uint8_t _spiChannel;
int _gpioHandle = -1;
int _spiHandle = -1;
};
// this handler emulates interrupts
static void lgpioAlertHandler(int num_alerts, lgGpioAlert_p alerts, void *userdata) {
if(!userdata)
return;
// PiHal instance is passed via the user data
PiHal* hal = (PiHal*)userdata;
// check the interrupt is enabled, the level matches and a callback exists
for(lgGpioAlert_t *alert = alerts; alert < (alerts + num_alerts); alert++) {
if((hal->interruptEnabled[alert->report.gpio]) &&
(hal->interruptModes[alert->report.gpio] == alert->report.level) &&
(hal->interruptCallbacks[alert->report.gpio])) {
hal->interruptCallbacks[alert->report.gpio]();
}
}
}
#endif
+198
View File
@@ -0,0 +1,198 @@
#ifndef PICO_HAL_H
#define PICO_HAL_H
// include RadioLib
#include <RadioLib.h>
// include the necessary Pico libraries
#include <pico/stdlib.h>
#include "hardware/spi.h"
#include "hardware/timer.h"
#include "hardware/pwm.h"
#include "hardware/clocks.h"
#include "pico/multicore.h"
uint32_t toneLoopPin;
unsigned int toneLoopFrequency;
unsigned long toneLoopDuration;
// pre-calculated pulse-widths for 1200 and 2200Hz
// we do this to save calculation time (see https://github.com/khoih-prog/RP2040_PWM/issues/6)
#define SLEEP_1200 416.666
#define SLEEP_2200 227.272
// === NOTE ===
// The tone(...) implementation uses the second core on the RPi Pico. This is to diminish as much
// jitter in the output tones as possible.
void toneLoop(){
gpio_set_dir(toneLoopPin, GPIO_OUT);
uint32_t sleep_dur;
if (toneLoopFrequency == 1200) {
sleep_dur = SLEEP_1200;
} else if (toneLoopFrequency == 2200) {
sleep_dur = SLEEP_2200;
} else {
sleep_dur = 500000 / toneLoopFrequency;
}
// tone bitbang
while(1){
gpio_put(toneLoopPin, 1);
sleep_us(sleep_dur);
gpio_put(toneLoopPin, 0);
sleep_us(sleep_dur);
tight_loop_contents();
}
}
// create a new Raspberry Pi Pico hardware abstraction
// layer using the Pico SDK
// the HAL must inherit from the base RadioLibHal class
// and implement all of its virtual methods
class PicoHal : public RadioLibHal {
public:
PicoHal(spi_inst_t *spiChannel, uint32_t misoPin, uint32_t mosiPin, uint32_t sckPin, uint32_t spiSpeed = 500 * 1000)
: RadioLibHal(GPIO_IN, GPIO_OUT, 0, 1, GPIO_IRQ_EDGE_RISE, GPIO_IRQ_EDGE_FALL),
_spiChannel(spiChannel),
_spiSpeed(spiSpeed),
_misoPin(misoPin),
_mosiPin(mosiPin),
_sckPin(sckPin){}
void init() override {
stdio_init_all();
spiBegin();
}
void term() override {
spiEnd();
}
// GPIO-related methods (pinMode, digitalWrite etc.) should check
// RADIOLIB_NC as an alias for non-connected pins
void pinMode(uint32_t pin, uint32_t mode) override {
if (pin == RADIOLIB_NC) {
return;
}
gpio_init(pin);
gpio_set_dir(pin, mode);
}
void digitalWrite(uint32_t pin, uint32_t value) override {
if (pin == RADIOLIB_NC) {
return;
}
gpio_put(pin, (bool)value);
}
uint32_t digitalRead(uint32_t pin) override {
if (pin == RADIOLIB_NC) {
return 0;
}
return gpio_get(pin);
}
void attachInterrupt(uint32_t interruptNum, void (*interruptCb)(void), uint32_t mode) override {
if (interruptNum == RADIOLIB_NC) {
return;
}
gpio_set_irq_enabled_with_callback(interruptNum, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, true, (gpio_irq_callback_t)interruptCb);
}
void detachInterrupt(uint32_t interruptNum) override {
if (interruptNum == RADIOLIB_NC) {
return;
}
gpio_set_irq_enabled_with_callback(interruptNum, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, false, NULL);
}
void delay(unsigned long ms) override {
sleep_ms(ms);
}
void delayMicroseconds(unsigned long us) override {
sleep_us(us);
}
unsigned long millis() override {
return to_ms_since_boot(get_absolute_time());
}
unsigned long micros() override {
return to_us_since_boot(get_absolute_time());
}
long pulseIn(uint32_t pin, uint32_t state, unsigned long timeout) override {
if (pin == RADIOLIB_NC) {
return 0;
}
this->pinMode(pin, GPIO_IN);
uint32_t start = this->micros();
uint32_t curtick = this->micros();
while (this->digitalRead(pin) == state) {
if ((this->micros() - curtick) > timeout) {
return 0;
}
}
return (this->micros() - start);
}
void tone(uint32_t pin, unsigned int frequency, unsigned long duration = 0) override {
// tones on the Pico are generated using bitbanging. This process is offloaded to the Pico's second core
multicore_reset_core1();
toneLoopPin = pin;
toneLoopFrequency = frequency;
toneLoopDuration = duration;
multicore_launch_core1(toneLoop);
}
void noTone(uint32_t pin) override {
multicore_reset_core1();
}
void spiBegin() {
spi_init(_spiChannel, _spiSpeed);
spi_set_format(_spiChannel, 8, SPI_CPOL_0, SPI_CPHA_0, SPI_MSB_FIRST);
gpio_set_function(_sckPin, GPIO_FUNC_SPI);
gpio_set_function(_mosiPin, GPIO_FUNC_SPI);
gpio_set_function(_misoPin, GPIO_FUNC_SPI);
}
void spiBeginTransaction() {}
void spiTransfer(uint8_t *out, size_t len, uint8_t *in) {
spi_write_read_blocking(_spiChannel, out, in, len);
}
void yield() override {
tight_loop_contents();
}
void spiEndTransaction() {}
void spiEnd() {
spi_deinit(_spiChannel);
}
private:
// the HAL can contain any additional private members
spi_inst_t *_spiChannel;
uint32_t _spiSpeed;
uint32_t _misoPin;
uint32_t _mosiPin;
uint32_t _sckPin;
};
#endif
+225
View File
@@ -0,0 +1,225 @@
/*
RadioLib Non-Arduino Tock Library helper functions
Licensed under the MIT License
Copyright (c) 2023 Alistair Francis <alistair@alistair23.me>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef TOCK_HAL_H
#define TOCK_HAL_H
// include RadioLib
#include <RadioLib.h>
// include all the dependencies
#include "libtock/net/lora_phy.h"
#include "libtock/net/syscalls/lora_phy_syscalls.h"
#include "libtock-sync/net/lora_phy.h"
#include "libtock/peripherals/gpio.h"
#include "libtock-sync/services/alarm.h"
#include "libtock/kernel/read_only_state.h"
#define RADIO_BUSY 1
#define RADIO_DIO_1 2
#define RADIO_DIO_3 3
#define RADIO_RESET 4
// Skip the chips select as Tock handles this for us
#define RADIO_NSS RADIOLIB_NC
// define Arduino-style macros
#define PIN_LOW (0x0)
#define PIN_HIGH (0x1)
#define PIN_INPUT (0x01)
#define PIN_OUTPUT (0x03)
#define PIN_RISING (0x01)
#define PIN_FALLING (0x02)
typedef void (*gpioIrqFn)(void);
gpioIrqFn gpio_funcs[4] = { NULL, NULL, NULL, NULL};
uint32_t frequency = 0;
/*
* Get the the timer frequency in Hz.
*/
int alarm_internal_frequency(uint32_t* frequency) {
syscall_return_t rval = command(0x0, 1, 0, 0);
return tock_command_return_u32_to_returncode(rval, frequency);
}
int alarm_internal_read(uint32_t* time) {
syscall_return_t rval = command(0x0, 2, 0, 0);
return tock_command_return_u32_to_returncode(rval, time);
}
static void lora_phy_gpio_Callback (int gpioPin,
__attribute__ ((unused)) int arg2,
__attribute__ ((unused)) int arg3,
void* userdata)
{
gpioIrqFn fn = gpio_funcs[gpioPin - 1];
if (fn != NULL ) {
fn();
}
}
class TockHal : public RadioLibHal {
public:
// default constructor - initializes the base HAL and any needed private members
TockHal()
: RadioLibHal(PIN_INPUT, PIN_OUTPUT, PIN_LOW, PIN_HIGH, PIN_RISING, PIN_FALLING) {
}
void init() override {
}
void term() override {
}
// GPIO-related methods (pinMode, digitalWrite etc.) should check
// RADIOLIB_NC as an alias for non-connected pins
void pinMode(uint32_t pin, uint32_t mode) override {
if(pin == RADIOLIB_NC) {
return;
}
if (mode == PIN_OUTPUT) {
libtock_lora_phy_gpio_enable_output(pin);
} else if (mode == PIN_INPUT) {
libtock_lora_phy_gpio_enable_input(pin, libtock_pull_down);
}
}
void digitalWrite(uint32_t pin, uint32_t value) override {
if(pin == RADIOLIB_NC) {
return;
}
if (value) {
libtock_lora_phy_gpio_set(pin);
} else {
libtock_lora_phy_gpio_clear(pin);
}
}
uint32_t digitalRead(uint32_t pin) override {
int value;
if(pin == RADIOLIB_NC) {
return 0;
}
libtock_lora_phy_gpio_read(pin, &value);
return value;
}
void attachInterrupt(uint32_t interruptNum, gpioIrqFn interruptCb, uint32_t mode) override {
if(interruptNum == RADIOLIB_NC) {
return;
}
gpio_funcs[interruptNum - 1] = interruptCb;
libtock_lora_phy_gpio_command_interrupt_callback(lora_phy_gpio_Callback, NULL);
// set GPIO as input and enable interrupts on it
libtock_lora_phy_gpio_enable_input(interruptNum, libtock_pull_down);
libtock_lora_phy_gpio_enable_interrupt(interruptNum, libtock_change);
}
void detachInterrupt(uint32_t interruptNum) override {
if(interruptNum == RADIOLIB_NC) {
return;
}
gpio_funcs[interruptNum - 1] = NULL;
libtock_lora_phy_gpio_disable_interrupt(interruptNum);
}
void delay(unsigned long ms) override {
#if !defined(RADIOLIB_CLOCK_DRIFT_MS)
libtocksync_alarm_delay_ms(ms);
#else
libtocksync_alarm_delay_ms(ms * 1000 / (1000 + RADIOLIB_CLOCK_DRIFT_MS));
#endif
}
void delayMicroseconds(unsigned long us) override {
#if !defined(RADIOLIB_CLOCK_DRIFT_MS)
libtocksync_alarm_delay_ms(us / 1000);
#else
libtocksync_alarm_delay_ms((us * 1000 / (1000 + RADIOLIB_CLOCK_DRIFT_MS)) / 1000);
#endif
}
unsigned long millis() override {
uint32_t now;
unsigned long ms;
if (frequency == 0) {
alarm_internal_frequency(&frequency);
}
alarm_internal_read(&now);
ms = now / (frequency / 1000);
#if !defined(RADIOLIB_CLOCK_DRIFT_MS)
return ms;
#else
return ms * 1000 / (1000 + RADIOLIB_CLOCK_DRIFT_MS);
#endif
}
unsigned long micros() override {
return millis() / 1000;
}
long pulseIn(uint32_t pin, uint32_t state, unsigned long timeout) override {
return 0;
}
void spiBegin() {
}
void spiBeginTransaction() {
}
void spiTransfer(uint8_t* out, size_t len, uint8_t* in) {
libtocksync_lora_phy_read_write(out, in, len);
}
void spiEndTransaction() {
}
void spiEnd() {
}
void yield() {
::yield_no_wait();
}
private:
};
#endif
+5 -1
View File
@@ -234,8 +234,12 @@ int16_t CC1101::receiveDirect(bool sync) {
// set RF switch (if present)
this->mod->setRfSwitchState(Module::MODE_RX);
// enable promiscuous mode - needed for protocols that decode in software (e.g. PagerClient)
int16_t state = setPromiscuousMode(true);
RADIOLIB_ASSERT(state);
// activate direct mode
int16_t state = directMode(sync);
state = directMode(sync);
RADIOLIB_ASSERT(state);
// start receiving
@@ -116,4 +116,20 @@ int16_t LLCC68::checkDataRate(DataRate_t dr) {
return(state);
}
int16_t LLCC68::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
case(ModemType_t::LRFHSS): {
return(this->beginLRFHSS());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+8
View File
@@ -69,6 +69,14 @@ class LLCC68: public SX1262 {
\returns \ref status_codes
*/
int16_t checkDataRate(DataRate_t dr) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK, LoRa or LR-FHSS.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
+30 -9
View File
@@ -1,4 +1,6 @@
#include "LR1110.h"
#include <math.h>
#if !RADIOLIB_EXCLUDE_LR11X0
LR1110::LR1110(Module* mod) : LR11x0(mod) {
@@ -31,9 +33,9 @@ int16_t LR1110::beginGFSK(float freq, float br, float freqDev, float rxBw, int8_
return(state);
}
int16_t LR1110::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, int8_t power, float tcxoVoltage) {
int16_t LR1110::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, bool narrowGrid, int8_t power, float tcxoVoltage) {
// execute common part
int16_t state = LR11x0::beginLRFHSS(bw, cr, tcxoVoltage);
int16_t state = LR11x0::beginLRFHSS(bw, cr, narrowGrid, tcxoVoltage);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
@@ -45,20 +47,24 @@ int16_t LR1110::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, int8_t power, fl
}
int16_t LR1110::setFrequency(float freq) {
return(this->setFrequency(freq, true));
return(this->setFrequency(freq, false));
}
int16_t LR1110::setFrequency(float freq, bool calibrate, float band) {
int16_t LR1110::setFrequency(float freq, bool skipCalibration, float band) {
RADIOLIB_CHECK_RANGE(freq, 150.0, 960.0, RADIOLIB_ERR_INVALID_FREQUENCY);
// calibrate image rejection
if(calibrate) {
int16_t state = LR11x0::calibImage(freq - band, freq + band);
// check if we need to recalibrate image
int16_t state;
if(!skipCalibration && (fabsf(freq - this->freqMHz) >= RADIOLIB_LR11X0_CAL_IMG_FREQ_TRIG_MHZ)) {
state = LR11x0::calibrateImageRejection(freq - band, freq + band);
RADIOLIB_ASSERT(state);
}
// set frequency
return(LR11x0::setRfFrequency((uint32_t)(freq*1000000.0f)));
state = LR11x0::setRfFrequency((uint32_t)(freq*1000000.0f));
RADIOLIB_ASSERT(state);
this->freqMHz = freq;
return(state);
}
int16_t LR1110::setOutputPower(int8_t power) {
@@ -105,4 +111,19 @@ int16_t LR1110::checkOutputPower(int8_t power, int8_t* clipped, bool forceHighPo
return(RADIOLIB_ERR_NONE);
}
int16_t LR1110::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginGFSK());
} break;
case(ModemType_t::LRFHSS): {
return(this->beginLRFHSS());
} break;
}
return(RADIOLIB_ERR_WRONG_MODEM);
}
#endif
+16 -4
View File
@@ -58,19 +58,21 @@ class LR1110: public LR11x0 {
\param freq Carrier frequency in MHz. Defaults to 434.0 MHz.
\param bw LR-FHSS bandwidth, one of RADIOLIB_LR11X0_LR_FHSS_BW_* values. Defaults to 722.66 kHz.
\param cr LR-FHSS coding rate, one of RADIOLIB_LR11X0_LR_FHSS_CR_* values. Defaults to 2/3 coding rate.
\param narrowGrid Whether to use narrow (3.9 kHz) or wide (25.39 kHz) grid spacing. Defaults to true (narrow/non-FCC) grid.
\param power Output power in dBm. Defaults to 10 dBm.
\param tcxoVoltage TCXO reference voltage to be set. Defaults to 1.6 V.
If you are seeing -706/-707 error codes, it likely means you are using non-0 value for module with XTAL.
To use XTAL, either set this value to 0, or set LR11x0::XTAL to true.
\returns \ref status_codes
*/
int16_t beginLRFHSS(float freq = 434.0, uint8_t bw = RADIOLIB_LR11X0_LR_FHSS_BW_722_66, uint8_t cr = RADIOLIB_LR11X0_LR_FHSS_CR_2_3, int8_t power = 10, float tcxoVoltage = 1.6);
int16_t beginLRFHSS(float freq = 434.0, uint8_t bw = RADIOLIB_LR11X0_LR_FHSS_BW_722_66, uint8_t cr = RADIOLIB_LR11X0_LR_FHSS_CR_2_3, bool narrowGrid = true, int8_t power = 10, float tcxoVoltage = 1.6);
// configuration methods
/*!
\brief Sets carrier frequency. Allowed values are in range from 150.0 to 960.0 MHz.
Will also perform calibrations.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_LR11X0_CAL_IMG_FREQ_TRIG MHz.
\param freq Carrier frequency to be set in MHz.
\returns \ref status_codes
*/
@@ -78,14 +80,16 @@ class LR1110: public LR11x0 {
/*!
\brief Sets carrier frequency. Allowed values are in range from 150.0 to 960.0 MHz.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_LR11X0_CAL_IMG_FREQ_TRIG MHz.
\param freq Carrier frequency to be set in MHz.
\param calibrate Run image calibration.
\param skipCalibration Skip automated image calibration.
\param band Half bandwidth for image calibration. For example,
if carrier is 434 MHz and band is set to 4 MHz, then the image will be calibrate
for band 430 - 438 MHz. Unused if calibrate is set to false, defaults to 4 MHz
\returns \ref status_codes
*/
int16_t setFrequency(float freq, bool calibrate, float band = 4);
int16_t setFrequency(float freq, bool skipCalibration, float band = 4);
/*!
\brief Sets output power. Allowed values are in range from -9 to 22 dBm (high-power PA) or -17 to 14 dBm (low-power PA).
@@ -122,6 +126,14 @@ class LR1110: public LR11x0 {
*/
int16_t checkOutputPower(int8_t power, int8_t* clipped, bool forceHighPower);
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK, LoRa or LR-FHSS.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
#endif
+26 -8
View File
@@ -1,4 +1,6 @@
#include "LR1120.h"
#include <math.h>
#if !RADIOLIB_EXCLUDE_LR11X0
LR1120::LR1120(Module* mod) : LR11x0(mod) {
@@ -7,7 +9,7 @@ LR1120::LR1120(Module* mod) : LR11x0(mod) {
int16_t LR1120::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint16_t preambleLength, float tcxoVoltage) {
// execute common part
int16_t state = LR11x0::begin(bw, sf, cr, syncWord, preambleLength, tcxoVoltage);
int16_t state = LR11x0::begin(bw, sf, cr, syncWord, preambleLength, tcxoVoltage, freq > 1000.0);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
@@ -31,9 +33,9 @@ int16_t LR1120::beginGFSK(float freq, float br, float freqDev, float rxBw, int8_
return(state);
}
int16_t LR1120::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, int8_t power, float tcxoVoltage) {
int16_t LR1120::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, bool narrowGrid, int8_t power, float tcxoVoltage) {
// execute common part
int16_t state = LR11x0::beginLRFHSS(bw, cr, tcxoVoltage);
int16_t state = LR11x0::beginLRFHSS(bw, cr, narrowGrid, tcxoVoltage);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
@@ -45,26 +47,27 @@ int16_t LR1120::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, int8_t power, fl
}
int16_t LR1120::setFrequency(float freq) {
return(this->setFrequency(freq, true));
return(this->setFrequency(freq, false));
}
int16_t LR1120::setFrequency(float freq, bool calibrate, float band) {
int16_t LR1120::setFrequency(float freq, bool skipCalibration, float band) {
if(!(((freq >= 150.0) && (freq <= 960.0)) ||
((freq >= 1900.0) && (freq <= 2200.0)) ||
((freq >= 2400.0) && (freq <= 2500.0)))) {
return(RADIOLIB_ERR_INVALID_FREQUENCY);
}
// calibrate image rejection
// check if we need to recalibrate image
int16_t state;
if(calibrate) {
state = LR11x0::calibImage(freq - band, freq + band);
if(!skipCalibration && (fabsf(freq - this->freqMHz) >= RADIOLIB_LR11X0_CAL_IMG_FREQ_TRIG_MHZ)) {
state = LR11x0::calibrateImageRejection(freq - band, freq + band);
RADIOLIB_ASSERT(state);
}
// set frequency
state = LR11x0::setRfFrequency((uint32_t)(freq*1000000.0f));
RADIOLIB_ASSERT(state);
this->freqMHz = freq;
this->highFreq = (freq > 1000.0);
return(RADIOLIB_ERR_NONE);
}
@@ -128,4 +131,19 @@ int16_t LR1120::checkOutputPower(int8_t power, int8_t* clipped, bool forceHighPo
return(RADIOLIB_ERR_NONE);
}
int16_t LR1120::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginGFSK());
} break;
case(ModemType_t::LRFHSS): {
return(this->beginLRFHSS());
} break;
}
return(RADIOLIB_ERR_WRONG_MODEM);
}
#endif
+18 -5
View File
@@ -58,19 +58,22 @@ class LR1120: public LR11x0 {
\param freq Carrier frequency in MHz. Defaults to 434.0 MHz.
\param bw LR-FHSS bandwidth, one of RADIOLIB_LR11X0_LR_FHSS_BW_* values. Defaults to 722.66 kHz.
\param cr LR-FHSS coding rate, one of RADIOLIB_LR11X0_LR_FHSS_CR_* values. Defaults to 2/3 coding rate.
\param narrowGrid Whether to use narrow (3.9 kHz) or wide (25.39 kHz) grid spacing. Defaults to true (narrow/non-FCC) grid.
\param power Output power in dBm. Defaults to 10 dBm.
\param tcxoVoltage TCXO reference voltage to be set. Defaults to 1.6 V.
If you are seeing -706/-707 error codes, it likely means you are using non-0 value for module with XTAL.
To use XTAL, either set this value to 0, or set LR11x0::XTAL to true.
\returns \ref status_codes
*/
int16_t beginLRFHSS(float freq = 434.0, uint8_t bw = RADIOLIB_LR11X0_LR_FHSS_BW_722_66, uint8_t cr = RADIOLIB_LR11X0_LR_FHSS_CR_2_3, int8_t power = 10, float tcxoVoltage = 1.6);
int16_t beginLRFHSS(float freq = 434.0, uint8_t bw = RADIOLIB_LR11X0_LR_FHSS_BW_722_66, uint8_t cr = RADIOLIB_LR11X0_LR_FHSS_CR_2_3, bool narrowGrid = true, int8_t power = 10, float tcxoVoltage = 1.6);
// configuration methods
/*!
\brief Sets carrier frequency. Allowed values are in range from 150.0 to 960.0 MHz,
1900 - 2200 MHz and 2400 - 2500 MHz. Will also perform calibrations.
1900 - 2200 MHz and 2400 - 2500 MHz.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_LR11X0_CAL_IMG_FREQ_TRIG MHz.
NOTE: When switching between sub-GHz and high-frequency bands, after changing the frequency,
setOutputPower() must be called in order to set the correct power amplifier!
\param freq Carrier frequency to be set in MHz.
@@ -80,17 +83,19 @@ class LR1120: public LR11x0 {
/*!
\brief Sets carrier frequency. Allowed values are in range from 150.0 to 960.0 MHz,
1900 - 2200 MHz and 2400 - 2500 MHz. Will also perform calibrations.
1900 - 2200 MHz and 2400 - 2500 MHz.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_LR11X0_CAL_IMG_FREQ_TRIG MHz.
NOTE: When switching between sub-GHz and high-frequency bands, after changing the frequency,
setOutputPower() must be called in order to set the correct power amplifier!
\param freq Carrier frequency to be set in MHz.
\param calibrate Run image calibration.
\param skipCalibration Skip automated image calibration.
\param band Half bandwidth for image calibration. For example,
if carrier is 434 MHz and band is set to 4 MHz, then the image will be calibrate
for band 430 - 438 MHz. Unused if calibrate is set to false, defaults to 4 MHz
\returns \ref status_codes
*/
int16_t setFrequency(float freq, bool calibrate, float band = 4);
int16_t setFrequency(float freq, bool skipCalibration, float band = 4);
/*!
\brief Sets output power. Allowed values are in range from -9 to 22 dBm (high-power PA) or -17 to 14 dBm (low-power PA).
@@ -131,6 +136,14 @@ class LR1120: public LR11x0 {
*/
int16_t checkOutputPower(int8_t power, int8_t* clipped, bool forceHighPower);
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK, LoRa or LR-FHSS.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
#endif
-3
View File
@@ -21,9 +21,6 @@ class LR1121: public LR1120 {
*/
LR1121(Module* mod); // cppcheck-suppress noExplicitConstructor
// TODO this is where overrides to disable GNSS+WiFi scanning methods on LR1121
// will be put once those are implemented
#if !RADIOLIB_GODMODE
private:
#endif
+467 -90
View File
@@ -23,13 +23,13 @@ LR11x0::LR11x0(Module* mod) : PhysicalLayer(RADIOLIB_LR11X0_FREQUENCY_STEP_SIZE,
this->irqMap[RADIOLIB_IRQ_TIMEOUT] = RADIOLIB_LR11X0_IRQ_TIMEOUT;
}
int16_t LR11x0::begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage) {
int16_t LR11x0::begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage, bool high) {
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, RADIOLIB_LR11X0_PACKET_TYPE_LORA);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
state = setBandwidth(bw);
state = setBandwidth(bw, high);
RADIOLIB_ASSERT(state);
state = setSpreadingFactor(sf);
@@ -98,11 +98,14 @@ int16_t LR11x0::beginGFSK(float br, float freqDev, float rxBw, uint16_t preamble
return(RADIOLIB_ERR_NONE);
}
int16_t LR11x0::beginLRFHSS(uint8_t bw, uint8_t cr, float tcxoVoltage) {
int16_t LR11x0::beginLRFHSS(uint8_t bw, uint8_t cr, bool narrowGrid, float tcxoVoltage) {
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, RADIOLIB_LR11X0_PACKET_TYPE_LR_FHSS);
RADIOLIB_ASSERT(state);
// set grid spacing
this->lrFhssGrid = narrowGrid ? RADIOLIB_LR11X0_LR_FHSS_GRID_STEP_NON_FCC : RADIOLIB_LR11X0_LR_FHSS_GRID_STEP_FCC;
// configure publicly accessible settings
state = setLrFhssConfig(bw, cr);
RADIOLIB_ASSERT(state);
@@ -117,6 +120,34 @@ int16_t LR11x0::beginLRFHSS(uint8_t bw, uint8_t cr, float tcxoVoltage) {
return(setModulationParamsLrFhss(RADIOLIB_LR11X0_LR_FHSS_BIT_RATE_RAW, RADIOLIB_LR11X0_LR_FHSS_SHAPING_GAUSSIAN_BT_1_0));
}
int16_t LR11x0::beginGNSS(uint8_t constellations, float tcxoVoltage) {
// set module properties and perform initial setup - packet type does not matter
int16_t state = this->modSetup(tcxoVoltage, RADIOLIB_LR11X0_PACKET_TYPE_LORA);
RADIOLIB_ASSERT(state);
state = this->clearErrors();
RADIOLIB_ASSERT(state);
state = this->configLfClock(RADIOLIB_LR11X0_LF_BUSY_RELEASE_DISABLED | RADIOLIB_LR11X0_LF_CLK_XOSC);
RADIOLIB_ASSERT(state);
uint16_t errs = 0;
state = this->getErrors(&errs);
RADIOLIB_ASSERT(state);
if(errs & 0x40) {
RADIOLIB_DEBUG_BASIC_PRINTLN("LF_XOSC_START_ERR");
return(RADIOLIB_ERR_SPI_CMD_FAILED);
}
state = this->gnssSetConstellationToUse(constellations);
RADIOLIB_ASSERT(state);
state = setRegulatorLDO();
RADIOLIB_ASSERT(state);
return(RADIOLIB_ERR_NONE);
}
int16_t LR11x0::reset() {
// run the reset sequence
this->mod->hal->pinMode(this->mod->getRst(), this->mod->hal->GpioModeOutput);
@@ -216,11 +247,8 @@ int16_t LR11x0::receive(uint8_t* data, size_t len) {
timeout = (RadioLibTime_t)(((maxLen * 8.0) / brBps) * 1000.0 * 5.0);
} else if(modem == RADIOLIB_LR11X0_PACKET_TYPE_LR_FHSS) {
size_t maxLen = len;
if(len == 0) {
maxLen = 0xFF;
}
timeout = (RadioLibTime_t)(((maxLen * 8.0) / (RADIOLIB_LR11X0_LR_FHSS_BIT_RATE)) * 1000.0 * 5.0);
// this modem cannot receive
return(RADIOLIB_ERR_WRONG_MODEM);
} else {
return(RADIOLIB_ERR_UNKNOWN);
@@ -288,7 +316,7 @@ int16_t LR11x0::receiveDirect() {
}
int16_t LR11x0::scanChannel() {
ChannelScanConfig_t config = {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_LR11X0_CAD_PARAM_DEFAULT,
.detPeak = RADIOLIB_LR11X0_CAD_PARAM_DEFAULT,
@@ -299,7 +327,7 @@ int16_t LR11x0::scanChannel() {
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->scanChannel(config));
return(this->scanChannel(cfg));
}
int16_t LR11x0::scanChannel(const ChannelScanConfig_t &config) {
@@ -421,8 +449,8 @@ int16_t LR11x0::startTransmit(const uint8_t* data, size_t len, uint8_t addr) {
if(modem == RADIOLIB_LR11X0_PACKET_TYPE_LR_FHSS) {
// in LR-FHSS mode, the packet is built by the device
// TODO add configurable grid step and device offset
state = lrFhssBuildFrame(this->lrFhssHdrCount, this->lrFhssCr, RADIOLIB_LR11X0_LR_FHSS_GRID_STEP_FCC, true, this->lrFhssBw, this->lrFhssHopSeq, 0, const_cast<uint8_t*>(data), len);
// TODO add configurable device offset
state = lrFhssBuildFrame(this->lrFhssHdrCount, this->lrFhssCr, this->lrFhssGrid, true, this->lrFhssBw, this->lrFhssHopSeq, 0, const_cast<uint8_t*>(data), len);
RADIOLIB_ASSERT(state);
} else {
@@ -472,8 +500,7 @@ int16_t LR11x0::startReceive(uint32_t timeout, uint32_t irqFlags, uint32_t irqMa
state = getPacketType(&modem);
RADIOLIB_ASSERT(state);
if((modem != RADIOLIB_LR11X0_PACKET_TYPE_LORA) &&
(modem != RADIOLIB_LR11X0_PACKET_TYPE_GFSK) &&
(modem != RADIOLIB_LR11X0_PACKET_TYPE_LR_FHSS)) {
(modem != RADIOLIB_LR11X0_PACKET_TYPE_GFSK)) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
@@ -521,8 +548,7 @@ int16_t LR11x0::readData(uint8_t* data, size_t len) {
state = getPacketType(&modem);
RADIOLIB_ASSERT(state);
if((modem != RADIOLIB_LR11X0_PACKET_TYPE_LORA) &&
(modem != RADIOLIB_LR11X0_PACKET_TYPE_GFSK) &&
(modem != RADIOLIB_LR11X0_PACKET_TYPE_LR_FHSS)) {
(modem != RADIOLIB_LR11X0_PACKET_TYPE_GFSK)) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
@@ -561,7 +587,7 @@ int16_t LR11x0::readData(uint8_t* data, size_t len) {
}
int16_t LR11x0::startChannelScan() {
ChannelScanConfig_t config = {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_LR11X0_CAD_PARAM_DEFAULT,
.detPeak = RADIOLIB_LR11X0_CAD_PARAM_DEFAULT,
@@ -572,7 +598,7 @@ int16_t LR11x0::startChannelScan() {
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->startChannelScan(config));
return(this->startChannelScan(cfg));
}
int16_t LR11x0::startChannelScan(const ChannelScanConfig_t &config) {
@@ -594,7 +620,7 @@ int16_t LR11x0::startChannelScan(const ChannelScanConfig_t &config) {
// set DIO pin mapping
uint16_t irqFlags = (config.cad.irqFlags == RADIOLIB_IRQ_NOT_SUPPORTED) ? RADIOLIB_LR11X0_IRQ_CAD_DETECTED | RADIOLIB_LR11X0_IRQ_CAD_DONE : config.cad.irqFlags;
state = setDioIrqParams(irqFlags, irqFlags);
state = setDioIrqParams(getIrqMapped(irqFlags), getIrqMapped(irqFlags));
RADIOLIB_ASSERT(state);
// clear interrupt flags
@@ -628,7 +654,7 @@ int16_t LR11x0::getChannelScanResult() {
return(RADIOLIB_ERR_UNKNOWN);
}
int16_t LR11x0::setBandwidth(float bw) {
int16_t LR11x0::setBandwidth(float bw, bool high) {
// check active modem
uint8_t type = RADIOLIB_LR11X0_PACKET_TYPE_NONE;
int16_t state = getPacketType(&type);
@@ -638,25 +664,39 @@ int16_t LR11x0::setBandwidth(float bw) {
}
// ensure byte conversion doesn't overflow
RADIOLIB_CHECK_RANGE(bw, 0.0, 510.0, RADIOLIB_ERR_INVALID_BANDWIDTH);
if (high) {
RADIOLIB_CHECK_RANGE(bw, 203.125, 815.0, RADIOLIB_ERR_INVALID_BANDWIDTH);
// check allowed bandwidth values
uint8_t bw_div2 = bw / 2 + 0.01;
switch (bw_div2) {
case 31: // 62.5:
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_62_5;
break;
case 62: // 125.0:
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_125_0;
break;
case 125: // 250.0
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_250_0;
break;
case 250: // 500.0
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_500_0;
break;
default:
if(fabsf(bw - 203.125) <= 0.001) {
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_203_125;
} else if(fabsf(bw - 406.25) <= 0.001) {
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_406_25;
} else if(fabsf(bw - 812.5) <= 0.001) {
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_812_50;
} else {
return(RADIOLIB_ERR_INVALID_BANDWIDTH);
}
} else {
RADIOLIB_CHECK_RANGE(bw, 0.0, 510.0, RADIOLIB_ERR_INVALID_BANDWIDTH);
// check allowed bandwidth values
uint8_t bw_div2 = bw / 2 + 0.01;
switch (bw_div2) {
case 31: // 62.5:
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_62_5;
break;
case 62: // 125.0:
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_125_0;
break;
case 125: // 250.0
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_250_0;
break;
case 250: // 500.0
this->bandwidth = RADIOLIB_LR11X0_LORA_BW_500_0;
break;
default:
return(RADIOLIB_ERR_INVALID_BANDWIDTH);
}
}
// update modulation parameters
@@ -1038,7 +1078,12 @@ int16_t LR11x0::setDataRate(DataRate_t dr) {
state = this->setCodingRate(dr.lora.codingRate);
} else if(type == RADIOLIB_LR11X0_PACKET_TYPE_LR_FHSS) {
// set the basic config
state = this->setLrFhssConfig(dr.lrFhss.bw, dr.lrFhss.cr);
RADIOLIB_ASSERT(state);
// set hopping grid
this->lrFhssGrid = dr.lrFhss.narrowGrid ? RADIOLIB_LR11X0_LR_FHSS_GRID_STEP_NON_FCC : RADIOLIB_LR11X0_LR_FHSS_GRID_STEP_FCC;
}
@@ -1077,7 +1122,11 @@ int16_t LR11x0::setPreambleLength(size_t preambleLength) {
return(setPacketParamsLoRa(this->preambleLengthLoRa, this->headerType, this->implicitLen, this->crcTypeLoRa, (uint8_t)this->invertIQEnabled));
} else if(type == RADIOLIB_LR11X0_PACKET_TYPE_GFSK) {
this->preambleLengthGFSK = preambleLength;
this->preambleDetLength = RADIOLIB_LR11X0_GFSK_PREAMBLE_DETECT_16_BITS;
this->preambleDetLength = preambleLength >= 32 ? RADIOLIB_LR11X0_GFSK_PREAMBLE_DETECT_32_BITS :
preambleLength >= 24 ? RADIOLIB_LR11X0_GFSK_PREAMBLE_DETECT_24_BITS :
preambleLength >= 16 ? RADIOLIB_LR11X0_GFSK_PREAMBLE_DETECT_16_BITS :
preambleLength > 0 ? RADIOLIB_LR11X0_GFSK_PREAMBLE_DETECT_8_BITS :
RADIOLIB_LR11X0_GFSK_PREAMBLE_DETECT_DISABLED;
return(setPacketParamsGFSK(this->preambleLengthGFSK, this->preambleDetLength, this->syncWordLength, this->addrComp, this->packetType, RADIOLIB_LR11X0_MAX_PACKET_LENGTH, this->crcTypeGFSK, this->whitening));
}
@@ -1401,17 +1450,36 @@ void LR11x0::setRfSwitchTable(const uint32_t (&pins)[Module::RFSWITCH_MAX_PINS],
// find which pins are used
uint8_t enable = 0;
for(size_t i = 0; i < Module::RFSWITCH_MAX_PINS; i++) {
if((pins[i] == RADIOLIB_NC) || (pins[i] > RADIOLIB_LR11X0_DIO10)) {
// check if this pin is unused
if(pins[i] == RADIOLIB_NC) {
continue;
}
enable |= 1UL << pins[i];
// only keep DIO pins, there may be some GPIOs in the switch tabke
if(pins[i] & RFSWITCH_PIN_FLAG) {
enable |= 1UL << RADIOLIB_LR11X0_DIOx_VAL(pins[i]);
}
}
// now get the configuration
uint8_t modes[7] = { 0 };
for(size_t i = 0; i < 7; i++) {
// check end of table
if(table[i].mode == LR11x0::MODE_END_OF_TABLE) {
break;
}
// get the mode ID in case the modes are out-of-order
uint8_t index = table[i].mode - LR11x0::MODE_STBY;
// iterate over the pins
for(size_t j = 0; j < Module::RFSWITCH_MAX_PINS; j++) {
modes[i] |= (table[i].values[j] > 0) ? (1UL << j) : 0;
// only process modes for the DIOx pins, skip GPIO pins
if(!(pins[j] & RFSWITCH_PIN_FLAG)) {
continue;
}
modes[index] |= (table[i].values[j] == this->mod->hal->GpioLevelHigh) ? (1UL << j) : 0;
}
}
@@ -1419,6 +1487,33 @@ void LR11x0::setRfSwitchTable(const uint32_t (&pins)[Module::RFSWITCH_MAX_PINS],
this->setDioAsRfSwitch(enable, modes[0], modes[1], modes[2], modes[3], modes[4], modes[5], modes[6]);
}
int16_t LR11x0::forceLDRO(bool enable) {
// check packet type
uint8_t type = RADIOLIB_LR11X0_PACKET_TYPE_NONE;
int16_t state = getPacketType(&type);
RADIOLIB_ASSERT(state);
if(type != RADIOLIB_LR11X0_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
// update modulation parameters
this->ldroAuto = false;
this->ldrOptimize = (uint8_t)enable;
return(setModulationParamsLoRa(this->spreadingFactor, this->bandwidth, this->codingRate, this->ldrOptimize));
}
int16_t LR11x0::autoLDRO() {
uint8_t type = RADIOLIB_LR11X0_PACKET_TYPE_NONE;
int16_t state = getPacketType(&type);
RADIOLIB_ASSERT(state);
if(type != RADIOLIB_LR11X0_PACKET_TYPE_LORA) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
this->ldroAuto = true;
return(RADIOLIB_ERR_NONE);
}
int16_t LR11x0::setLrFhssConfig(uint8_t bw, uint8_t cr, uint8_t hdrCount, uint16_t hopSeed) {
// check active modem
uint8_t type = RADIOLIB_LR11X0_PACKET_TYPE_NONE;
@@ -1441,6 +1536,11 @@ int16_t LR11x0::setLrFhssConfig(uint8_t bw, uint8_t cr, uint8_t hdrCount, uint16
}
int16_t LR11x0::startWifiScan(char wifiType, uint8_t mode, uint16_t chanMask, uint8_t numScans, uint16_t timeout) {
// LR1121 cannot do WiFi scanning
if(this->chipType == RADIOLIB_LR11X0_DEVICE_LR1121) {
return(RADIOLIB_ERR_UNSUPPORTED);
}
uint8_t type;
switch(wifiType) {
case('b'):
@@ -1500,9 +1600,7 @@ int16_t LR11x0::getWifiScanResultsCount(uint8_t* count) {
}
int16_t LR11x0::getWifiScanResult(LR11x0WifiResult_t* result, uint8_t index, bool brief) {
if(!result) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(result);
// read a single result
uint8_t format = brief ? RADIOLIB_LR11X0_WIFI_RESULT_TYPE_BASIC : RADIOLIB_LR11X0_WIFI_RESULT_TYPE_COMPLETE;
@@ -1576,9 +1674,7 @@ int16_t LR11x0::getWifiScanResult(LR11x0WifiResult_t* result, uint8_t index, boo
}
int16_t LR11x0::wifiScan(uint8_t wifiType, uint8_t* count, uint8_t mode, uint16_t chanMask, uint8_t numScans, uint16_t timeout) {
if(!count) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(count);
// start scan
RADIOLIB_DEBUG_BASIC_PRINTLN("WiFi scan start");
@@ -1603,9 +1699,7 @@ int16_t LR11x0::wifiScan(uint8_t wifiType, uint8_t* count, uint8_t mode, uint16_
}
int16_t LR11x0::getVersionInfo(LR11x0VersionInfo_t* info) {
if(!info) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(info);
int16_t state = this->getVersion(&info->hardware, &info->device, &info->fwMajor, &info->fwMinor);
RADIOLIB_ASSERT(state);
@@ -1625,9 +1719,7 @@ int16_t LR11x0::getVersionInfo(LR11x0VersionInfo_t* info) {
}
int16_t LR11x0::updateFirmware(const uint32_t* image, size_t size, bool nonvolatile) {
if(!image) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(image);
// put the device to bootloader mode
int16_t state = this->reboot(true);
@@ -1684,6 +1776,275 @@ int16_t LR11x0::updateFirmware(const uint32_t* image, size_t size, bool nonvolat
return(state);
}
int16_t LR11x0::isGnssScanCapable() {
// get the version
LR11x0VersionInfo_t version;
int16_t state = this->getVersionInfo(&version);
RADIOLIB_ASSERT(state);
// check the device firmware version is sufficient
uint16_t versionFull = ((uint16_t)version.fwMajor << 8) | (uint16_t)version.fwMinor;
state = RADIOLIB_ERR_UNSUPPORTED;
if((version.device == RADIOLIB_LR11X0_DEVICE_LR1110) && (versionFull >= 0x0401)) {
state = RADIOLIB_ERR_NONE;
} else if((version.device == RADIOLIB_LR11X0_DEVICE_LR1120) && (versionFull >= 0x0201)) {
state = RADIOLIB_ERR_NONE;
}
RADIOLIB_ASSERT(state);
// in debug mode, dump the almanac
#if RADIOLIB_DEBUG_PROTOCOL
uint32_t addr = 0;
uint16_t sz = 0;
state = this->gnssAlmanacReadAddrSize(&addr, &sz);
RADIOLIB_ASSERT(state);
RADIOLIB_DEBUG_BASIC_PRINTLN("Almanac@%08x, %d bytes", addr, sz);
uint32_t buff[32] = { 0 };
while(sz > 0) {
size_t len = sz > 32 ? 32 : sz/sizeof(uint32_t);
state = this->readRegMem32(addr, buff, len);
RADIOLIB_ASSERT(state);
RADIOLIB_DEBUG_HEXDUMP(NULL, (uint8_t*)buff, len*sizeof(uint32_t), addr);
addr += len*sizeof(uint32_t);
sz -= len*sizeof(uint32_t);
}
uint8_t almanac[22] = { 0 };
for(uint8_t i = 0; i < 128; i++) {
RADIOLIB_DEBUG_BASIC_PRINTLN("Almanac[%d]:", i);
state = this->gnssAlmanacReadSV(i, almanac);
RADIOLIB_ASSERT(state);
RADIOLIB_DEBUG_HEXDUMP(NULL, almanac, 22);
}
#endif
return(state);
}
int16_t LR11x0::gnssScan(LR11x0GnssResult_t* res) {
RADIOLIB_ASSERT_PTR(res);
// go to standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
// set DIO mapping
state = setDioIrqParams(RADIOLIB_LR11X0_IRQ_GNSS_DONE | RADIOLIB_LR11X0_IRQ_GNSS_ABORT);
RADIOLIB_ASSERT(state);
// set scan mode (single vs multiple)
state = this->gnssSetMode(0x03);
RADIOLIB_ASSERT(state);
// set RF switch
this->mod->setRfSwitchState(LR11x0::MODE_GNSS);
// start scan with high effort
RADIOLIB_DEBUG_BASIC_PRINTLN("GNSS scan start");
state = this->gnssPerformScan(RADIOLIB_LR11X0_GNSS_EFFORT_MID, 0x3C, 16);
RADIOLIB_ASSERT(state);
// wait for scan finished or timeout
// this can take very long if both GPS and BeiDou are enabled
RadioLibTime_t softTimeout = 300UL * 1000UL;
RadioLibTime_t start = this->mod->hal->millis();
while(!this->mod->hal->digitalRead(this->mod->getIrq())) {
this->mod->hal->yield();
if(this->mod->hal->millis() - start > softTimeout) {
this->gnssAbort();
RADIOLIB_DEBUG_BASIC_PRINTLN("Timeout waiting for IRQ");
}
}
// restore the switch
this->mod->setRfSwitchState(Module::MODE_IDLE);
RADIOLIB_DEBUG_BASIC_PRINTLN("GNSS scan done in %lu ms", (long unsigned int)(this->mod->hal->millis() - start));
// distinguish between GNSS-done and GNSS-abort outcomes and clear the flags
uint32_t irq = this->getIrqStatus();
this->clearIrq(RADIOLIB_LR11X0_IRQ_ALL);
if(irq & RADIOLIB_LR11X0_IRQ_GNSS_ABORT) {
return(RADIOLIB_ERR_RX_TIMEOUT);
}
// retrieve the demodulator status
uint8_t info = 0;
state = this->gnssReadDemodStatus(&res->demodStat, &info);
RADIOLIB_ASSERT(state);
RADIOLIB_DEBUG_BASIC_PRINTLN("Demod status %d, info %02x", (int)res->demodStat, (unsigned int)info);
// retrieve the number of detected satellites
state = this->gnssGetNbSvDetected(&res->numSatsDet);
RADIOLIB_ASSERT(state);
// retrieve the result size
state = this->gnssGetResultSize(&res->resSize);
RADIOLIB_ASSERT(state);
// check and return demodulator status
if(res->demodStat < RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_TOW_FOUND) {
return(RADIOLIB_ERR_GNSS_DEMOD(res->demodStat));
}
return(state);
}
int16_t LR11x0::getGnssAlmanacStatus(LR11x0GnssAlmanacStatus_t *stat) {
RADIOLIB_ASSERT_PTR(stat);
// save the time the time until subframe is relative to
stat->start = this->mod->hal->millis();
// get the raw data
uint8_t raw[53] = { 0 };
int16_t state = this->gnssReadAlmanacStatus(raw);
RADIOLIB_ASSERT(state);
// parse the reply
stat->gps.status = (int8_t)raw[0];
stat->gps.timeUntilSubframe = ((uint32_t)(raw[1]) << 24) | ((uint32_t)(raw[2]) << 16) | ((uint32_t)(raw[3]) << 8) | (uint32_t)raw[4];
stat->gps.numSubframes = raw[5];
stat->gps.nextSubframe4SvId = raw[6];
stat->gps.nextSubframe5SvId = raw[7];
stat->gps.nextSubframeStart = raw[8];
stat->gps.numUpdateNeeded = raw[9];
stat->gps.flagsUpdateNeeded[0] = ((uint32_t)(raw[10]) << 24) | ((uint32_t)(raw[11]) << 16) | ((uint32_t)(raw[12]) << 8) | (uint32_t)raw[13];
stat->gps.flagsActive[0] = ((uint32_t)(raw[14]) << 24) | ((uint32_t)(raw[15]) << 16) | ((uint32_t)(raw[16]) << 8) | (uint32_t)raw[17];
stat->beidou.status = (int8_t)raw[18];
stat->beidou.timeUntilSubframe = ((uint32_t)(raw[19]) << 24) | ((uint32_t)(raw[20]) << 16) | ((uint32_t)(raw[21]) << 8) | (uint32_t)raw[22];
stat->beidou.numSubframes = raw[23];
stat->beidou.nextSubframe4SvId = raw[24];
stat->beidou.nextSubframe5SvId = raw[25];
stat->beidou.nextSubframeStart = raw[26];
stat->beidou.numUpdateNeeded = raw[27];
stat->beidou.flagsUpdateNeeded[0] = ((uint32_t)(raw[28]) << 24) | ((uint32_t)(raw[29]) << 16) | ((uint32_t)(raw[30]) << 8) | (uint32_t)raw[31];
stat->beidou.flagsUpdateNeeded[1] = ((uint32_t)(raw[32]) << 24) | ((uint32_t)(raw[33]) << 16) | ((uint32_t)(raw[34]) << 8) | (uint32_t)raw[35];
stat->beidou.flagsActive[0] = ((uint32_t)(raw[36]) << 24) | ((uint32_t)(raw[37]) << 16) | ((uint32_t)(raw[38]) << 8) | (uint32_t)raw[39];
stat->beidou.flagsActive[1] = ((uint32_t)(raw[40]) << 24) | ((uint32_t)(raw[41]) << 16) | ((uint32_t)(raw[42]) << 8) | (uint32_t)raw[43];
stat->beidouSvNoAlmanacFlags[0] = ((uint32_t)(raw[44]) << 24) | ((uint32_t)(raw[45]) << 16) | ((uint32_t)(raw[46]) << 8) | (uint32_t)raw[47];
stat->beidouSvNoAlmanacFlags[1] = ((uint32_t)(raw[18]) << 24) | ((uint32_t)(raw[49]) << 16) | ((uint32_t)(raw[50]) << 8) | (uint32_t)raw[51];
stat->nextAlmanacId = raw[52];
return(state);
}
int16_t LR11x0::gnssDelayUntilSubframe(LR11x0GnssAlmanacStatus_t *stat, uint8_t constellation) {
RADIOLIB_ASSERT_PTR(stat);
// almanac update has to be called at least 1.3 seconds before the subframe
// we use 2.3 seconds to be on the safe side
// calculate absolute times
RadioLibTime_t window = stat->start + stat->gps.timeUntilSubframe - 2300;
if(constellation == RADIOLIB_LR11X0_GNSS_CONSTELLATION_BEIDOU) {
window = stat->start + stat->beidou.timeUntilSubframe - 2300;
}
RadioLibTime_t now = this->mod->hal->millis();
if(now > window) {
// we missed the window
return(RADIOLIB_ERR_GNSS_SUBFRAME_NOT_AVAILABLE);
}
RadioLibTime_t delay = window - now;
RADIOLIB_DEBUG_BASIC_PRINTLN("Time until subframe %lu ms", delay);
this->mod->hal->delay(delay);
return(RADIOLIB_ERR_NONE);
}
// TODO fix last satellite always out of date
int16_t LR11x0::updateGnssAlmanac(uint8_t constellation) {
int16_t state = this->setDioIrqParams(RADIOLIB_LR11X0_IRQ_GNSS_DONE | RADIOLIB_LR11X0_IRQ_GNSS_ABORT);
RADIOLIB_ASSERT(state);
state = this->gnssAlmanacUpdateFromSat(RADIOLIB_LR11X0_GNSS_EFFORT_MID, constellation);
RADIOLIB_ASSERT(state);
// wait for scan finished or timeout, assumes 2 subframes and up to 2.3s pre-roll
uint32_t softTimeout = 16UL * 1000UL;
uint32_t start = this->mod->hal->millis();
while (!this->mod->hal->digitalRead(this->mod->getIrq())) {
this->mod->hal->yield();
if(this->mod->hal->millis() - start > softTimeout) {
this->gnssAbort();
RADIOLIB_DEBUG_BASIC_PRINTLN("Timeout waiting for almanac update");
}
}
RADIOLIB_DEBUG_BASIC_PRINTLN("GPS almanac update done in %lu ms", (long unsigned int)(this->mod->hal->millis() - start));
// distinguish between GNSS-done and GNSS-abort outcomes and clear the flags
uint32_t irq = this->getIrqStatus();
this->clearIrq(RADIOLIB_LR11X0_IRQ_ALL);
if(irq & RADIOLIB_LR11X0_IRQ_GNSS_ABORT) {
state = RADIOLIB_ERR_RX_TIMEOUT;
}
return(state);
}
int16_t LR11x0::getGnssPosition(LR11x0GnssPosition_t* pos, bool filtered) {
RADIOLIB_ASSERT_PTR(pos);
uint8_t error = 0;
int16_t state;
if(filtered) {
state = this->gnssReadDopplerSolverRes(&error, &pos->numSatsUsed, NULL, NULL, NULL, NULL, &pos->latitude, &pos->longitude, &pos->accuracy, NULL);
} else {
state = this->gnssReadDopplerSolverRes(&error, &pos->numSatsUsed, &pos->latitude, &pos->longitude, &pos->accuracy, NULL, NULL, NULL, NULL, NULL);
}
RADIOLIB_ASSERT(state);
// check the solver error
if(error != 0) {
return(RADIOLIB_ERR_GNSS_SOLVER(error));
}
return(state);
}
int16_t LR11x0::getGnssSatellites(LR11x0GnssSatellite_t* sats, uint8_t numSats) {
RADIOLIB_ASSERT_PTR(sats);
if(numSats >= 32) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
uint8_t svId[32] = { 0 };
uint8_t snr[32] = { 0 };
int16_t doppler[32] = { 0 };
int16_t state = this->gnssGetSvDetected(svId, snr, doppler, numSats);
RADIOLIB_ASSERT(state);
for(size_t i = 0; i < numSats; i++) {
sats[i].svId = svId[i];
sats[i].c_n0 = snr[i] + 31;
sats[i].doppler = doppler[i];
}
return(state);
}
int16_t LR11x0::getModem(ModemType_t* modem) {
RADIOLIB_ASSERT_PTR(modem);
uint8_t packetType = RADIOLIB_LR11X0_PACKET_TYPE_NONE;
int16_t state = getPacketType(&packetType);
RADIOLIB_ASSERT(state);
switch(packetType) {
case(RADIOLIB_LR11X0_PACKET_TYPE_LORA):
*modem = ModemType_t::LoRa;
return(RADIOLIB_ERR_NONE);
case(RADIOLIB_LR11X0_PACKET_TYPE_GFSK):
*modem = ModemType_t::FSK;
return(RADIOLIB_ERR_NONE);
case(RADIOLIB_LR11X0_PACKET_TYPE_LR_FHSS):
*modem = ModemType_t::LRFHSS;
return(RADIOLIB_ERR_NONE);
}
return(RADIOLIB_ERR_WRONG_MODEM);
}
int16_t LR11x0::modSetup(float tcxoVoltage, uint8_t modem) {
this->mod->init();
this->mod->hal->pinMode(this->mod->getIrq(), this->mod->hal->GpioModeInput);
@@ -1777,7 +2138,9 @@ bool LR11x0::findChip(uint8_t ver) {
// read the version
LR11x0VersionInfo_t info;
int16_t state = getVersionInfo(&info);
if((state == RADIOLIB_ERR_NONE) && (info.device == ver)) {
RADIOLIB_ASSERT(state);
if(info.device == ver) {
RADIOLIB_DEBUG_BASIC_PRINTLN("Found LR11x0: RADIOLIB_LR11X0_CMD_GET_VERSION = 0x%02x", info.device);
RADIOLIB_DEBUG_BASIC_PRINTLN("Base FW version: %d.%d", (int)info.fwMajor, (int)info.fwMinor);
if(this->chipType != RADIOLIB_LR11X0_DEVICE_LR1121) {
@@ -2061,10 +2424,10 @@ int16_t LR11x0::setRegMode(uint8_t mode) {
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_SET_REG_MODE, true, &mode, 1));
}
int16_t LR11x0::calibImage(float freq1, float freq2) {
int16_t LR11x0::calibrateImageRejection(float freqMin, float freqMax) {
uint8_t buff[2] = {
(uint8_t)floor((freq1 - 1.0f) / 4.0f),
(uint8_t)ceil((freq2 + 1.0f) / 4.0f)
(uint8_t)floor((freqMin - 1.0f) / 4.0f),
(uint8_t)ceil((freqMax + 1.0f) / 4.0f)
};
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_CALIB_IMAGE, true, buff, sizeof(buff)));
}
@@ -2083,7 +2446,7 @@ int16_t LR11x0::setDioIrqParams(uint32_t irq1, uint32_t irq2) {
}
int16_t LR11x0::setDioIrqParams(uint32_t irq) {
return(setDioIrqParams(irq, irq));
return(setDioIrqParams(irq, 0));
}
int16_t LR11x0::clearIrq(uint32_t irq) {
@@ -2126,7 +2489,8 @@ int16_t LR11x0::getTemp(float* temp) {
// pass the replies
if(temp) {
uint16_t raw = ((uint16_t)(buff[0]) << 8) | (uint16_t)buff[1];
*temp = 25.0f - (1000.0f/1.7f)*(((float)raw/2047.0f)*1350.0f - 0.7295f);
raw = raw & 0x07FF; //According LR1121 datasheet we need [0..10] bits
*temp = 25.0f - (1000.0f/1.7f)*(((float)raw/2047.0f)*1.35f - 0.7295f); //According LR1121 datasheet 1.35
}
return(state);
@@ -2225,23 +2589,17 @@ int16_t LR11x0::readInfoPage(uint16_t addr, uint32_t* data, size_t len) {
}
int16_t LR11x0::getChipEui(uint8_t* eui) {
if(!eui) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(eui);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_GET_CHIP_EUI, false, eui, RADIOLIB_LR11X0_EUI_LEN));
}
int16_t LR11x0::getSemtechJoinEui(uint8_t* eui) {
if(!eui) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(eui);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_GET_SEMTECH_JOIN_EUI, false, eui, RADIOLIB_LR11X0_EUI_LEN));
}
int16_t LR11x0::deriveRootKeysAndGetPin(uint8_t* pin) {
if(!pin) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(pin);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_DERIVE_ROOT_KEYS_AND_GET_PIN, false, pin, RADIOLIB_LR11X0_PIN_LEN));
}
@@ -2337,9 +2695,7 @@ int16_t LR11x0::getRssiInst(float* rssi) {
}
int16_t LR11x0::setGfskSyncWord(uint8_t* sync) {
if(!sync) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(sync);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_SET_GFSK_SYNC_WORD, true, sync, RADIOLIB_LR11X0_GFSK_SYNC_WORD_LEN));
}
@@ -2392,7 +2748,19 @@ int16_t LR11x0::setPacketType(uint8_t type) {
}
int16_t LR11x0::setModulationParamsLoRa(uint8_t sf, uint8_t bw, uint8_t cr, uint8_t ldro) {
uint8_t buff[4] = { sf, bw, cr, ldro };
// calculate symbol length and enable low data rate optimization, if auto-configuration is enabled
if(this->ldroAuto) {
float symbolLength = (float)(uint32_t(1) << this->spreadingFactor) / (float)this->bandwidthKhz;
if(symbolLength >= 16.0) {
this->ldrOptimize = RADIOLIB_LR11X0_LORA_LDRO_ENABLED;
} else {
this->ldrOptimize = RADIOLIB_LR11X0_LORA_LDRO_DISABLED;
}
} else {
this->ldrOptimize = ldro;
}
uint8_t buff[4] = { sf, bw, cr, this->ldrOptimize };
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_SET_MODULATION_PARAMS, true, buff, sizeof(buff)));
}
@@ -2976,9 +3344,7 @@ int16_t LR11x0::gnssGetResultSize(uint16_t* size) {
}
int16_t LR11x0::gnssReadResults(uint8_t* result, uint16_t size) {
if(!result) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(result);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_GNSS_READ_RESULTS, false, result, size));
}
@@ -3262,10 +3628,20 @@ int16_t LR11x0::gnssWriteBitMaskSatActivated(uint8_t bitMask, uint32_t* bitMaskA
return(state);
}
void LR11x0::gnssAbort() {
// send the abort signal (single NOP)
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_CMD] = Module::BITS_8;
// we need to call the most basic overload of the SPI write method otherwise the call will be ambiguous
uint8_t cmd[2] = { 0, 0 };
this->mod->SPIwriteStream(cmd, 2, NULL, 0, false, false);
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_CMD] = Module::BITS_16;
// wait for at least 2.9 seconds as specified by the user manual
this->mod->hal->delay(3000);
}
int16_t LR11x0::cryptoSetKey(uint8_t keyId, uint8_t* key) {
if(!key) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(key);
uint8_t buff[1 + RADIOLIB_AES128_KEY_SIZE] = { 0 };
buff[0] = keyId;
memcpy(&buff[1], key, RADIOLIB_AES128_KEY_SIZE);
@@ -3273,9 +3649,7 @@ int16_t LR11x0::cryptoSetKey(uint8_t keyId, uint8_t* key) {
}
int16_t LR11x0::cryptoDeriveKey(uint8_t srcKeyId, uint8_t dstKeyId, uint8_t* key) {
if(!key) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(key);
uint8_t buff[2 + RADIOLIB_AES128_KEY_SIZE] = { 0 };
buff[0] = srcKeyId;
buff[1] = dstKeyId;
@@ -3322,11 +3696,17 @@ int16_t LR11x0::cryptoProcessJoinAccept(uint8_t decKeyId, uint8_t verKeyId, uint
// check the crypto engine state
if(rplBuff[0] != RADIOLIB_LR11X0_CRYPTO_STATUS_SUCCESS) {
RADIOLIB_DEBUG_BASIC_PRINTLN("Crypto Engine error: %02x", rplBuff[0]);
#if !RADIOLIB_STATIC_ONLY
delete[] rplBuff;
#endif
return(RADIOLIB_ERR_SPI_CMD_FAILED);
}
// pass the data
memcpy(dataOut, &rplBuff[1], len);
#if !RADIOLIB_STATIC_ONLY
delete[] rplBuff;
#endif
return(state);
}
@@ -3467,23 +3847,17 @@ int16_t LR11x0::bootReboot(bool stay) {
}
int16_t LR11x0::bootGetPin(uint8_t* pin) {
if(!pin) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(pin);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_BOOT_GET_PIN, false, pin, RADIOLIB_LR11X0_PIN_LEN));
}
int16_t LR11x0::bootGetChipEui(uint8_t* eui) {
if(!eui) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(eui);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_BOOT_GET_CHIP_EUI, false, eui, RADIOLIB_LR11X0_EUI_LEN));
}
int16_t LR11x0::bootGetJoinEui(uint8_t* eui) {
if(!eui) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(eui);
return(this->SPIcommand(RADIOLIB_LR11X0_CMD_BOOT_GET_JOIN_EUI, false, eui, RADIOLIB_LR11X0_EUI_LEN));
}
@@ -3557,6 +3931,9 @@ int16_t LR11x0::cryptoCommon(uint16_t cmd, uint8_t keyId, uint8_t* dataIn, size_
// pass the data
memcpy(dataOut, &rplBuff[1], len);
#if !RADIOLIB_STATIC_ONLY
delete[] rplBuff;
#endif
return(state);
}
+261 -13
View File
@@ -233,6 +233,7 @@
#define RADIOLIB_LR11X0_CALIBRATE_HF_RC (0x01UL << 1) // 1 1 high frequency RC
#define RADIOLIB_LR11X0_CALIBRATE_LF_RC (0x01UL << 0) // 0 0 low frequency RC
#define RADIOLIB_LR11X0_CALIBRATE_ALL (0x3FUL << 0) // 5 0 everything
#define RADIOLIB_LR11X0_CAL_IMG_FREQ_TRIG_MHZ (20.0)
// RADIOLIB_LR11X0_CMD_SET_REG_MODE
#define RADIOLIB_LR11X0_REG_MODE_LDO (0x00UL << 0) // 0 0 regulator mode: LDO in all modes
@@ -249,11 +250,13 @@
#define RADIOLIB_LR11X0_RFSW_DIO8_DISABLED (0x00UL << 3) // 4 0 DIO8 disabled (default)
#define RADIOLIB_LR11X0_RFSW_DIO10_ENABLED (0x01UL << 4) // 4 0 RF switch: DIO10 enabled
#define RADIOLIB_LR11X0_RFSW_DIO10_DISABLED (0x00UL << 4) // 4 0 DIO10 disabled (default)
#define RADIOLIB_LR11X0_DIO5 (0)
#define RADIOLIB_LR11X0_DIO6 (1)
#define RADIOLIB_LR11X0_DIO7 (2)
#define RADIOLIB_LR11X0_DIO8 (3)
#define RADIOLIB_LR11X0_DIO10 (4)
#define RADIOLIB_LR11X0_DIOx(X) ((X) | RFSWITCH_PIN_FLAG)
#define RADIOLIB_LR11X0_DIOx_VAL(X) ((X) & ~RFSWITCH_PIN_FLAG)
#define RADIOLIB_LR11X0_DIO5 (RADIOLIB_LR11X0_DIOx(0))
#define RADIOLIB_LR11X0_DIO6 (RADIOLIB_LR11X0_DIOx(1))
#define RADIOLIB_LR11X0_DIO7 (RADIOLIB_LR11X0_DIOx(2))
#define RADIOLIB_LR11X0_DIO8 (RADIOLIB_LR11X0_DIOx(3))
#define RADIOLIB_LR11X0_DIO10 (RADIOLIB_LR11X0_DIOx(4))
// RADIOLIB_LR11X0_CMD_SET_DIO_IRQ_PARAMS
#define RADIOLIB_LR11X0_IRQ_TX_DONE (0x01UL << 2) // 31 0 interrupt: packet transmitted
@@ -274,7 +277,8 @@
#define RADIOLIB_LR11X0_IRQ_FSK_LEN_ERROR (0x01UL << 24) // 31 0 FSK packet received with length error
#define RADIOLIB_LR11X0_IRQ_FSK_ADDR_ERROR (0x01UL << 25) // 31 0 FSK packet received with address error
#define RADIOLIB_LR11X0_IRQ_LORA_RX_TIMESTAMP (0x01UL << 27) // 31 0 last LoRa symbol was received (timestamp source)
#define RADIOLIB_LR11X0_IRQ_ALL (0x0BF80FFCUL) // 31 0 all interrupts
#define RADIOLIB_LR11X0_IRQ_GNSS_ABORT (0x01UL << 28) // 31 0 GNSS scan aborted
#define RADIOLIB_LR11X0_IRQ_ALL (0x1BF80FFCUL) // 31 0 all interrupts
#define RADIOLIB_LR11X0_IRQ_NONE (0x00UL << 0) // 31 0 no interrupts
// RADIOLIB_LR11X0_CMD_CONFIG_LF_LOCK
@@ -364,6 +368,9 @@
#define RADIOLIB_LR11X0_LORA_BW_125_0 (0x04UL << 0) // 7 0 125.0 kHz
#define RADIOLIB_LR11X0_LORA_BW_250_0 (0x05UL << 0) // 7 0 250.0 kHz
#define RADIOLIB_LR11X0_LORA_BW_500_0 (0x06UL << 0) // 7 0 500.0 kHz
#define RADIOLIB_LR11X0_LORA_BW_203_125 (0x0DUL << 0) // 7 0 203.0 kHz (2.4GHz only)
#define RADIOLIB_LR11X0_LORA_BW_406_25 (0x0EUL << 0) // 7 0 406.0 kHz (2.4GHz only)
#define RADIOLIB_LR11X0_LORA_BW_812_50 (0x0FUL << 0) // 7 0 812.0 kHz (2.4GHz only)
#define RADIOLIB_LR11X0_LORA_CR_4_5_SHORT (0x01UL << 0) // 7 0 coding rate: 4/5 with short interleaver
#define RADIOLIB_LR11X0_LORA_CR_4_6_SHORT (0x02UL << 0) // 7 0 4/6 with short interleaver
#define RADIOLIB_LR11X0_LORA_CR_4_7_SHORT (0x03UL << 0) // 7 0 4/7 with short interleaver
@@ -549,7 +556,7 @@
#define RADIOLIB_LR11X0_GNSS_CONTEXT_ERR_FLASH (0x03UL << 0) // 7 4 flash integrity error
#define RADIOLIB_LR11X0_GNSS_CONTEXT_ERR_ALMANAC_UPD (0x04UL << 0) // 7 4 almanac update not allowed
#define RADIOLIB_LR11X0_GNSS_CONTEXT_FREQ_SPACE_250_HZ (0x00UL << 0) // 8 7 frequency search space: 250 Hz
#define RADIOLIB_LR11X0_GNSS_CONTEXT_FREQ_SPACE_500_HZ (0x01UL << 0) // 8 7 500 H
#define RADIOLIB_LR11X0_GNSS_CONTEXT_FREQ_SPACE_500_HZ (0x01UL << 0) // 8 7 500 Hz
#define RADIOLIB_LR11X0_GNSS_CONTEXT_FREQ_SPACE_1000_HZ (0x02UL << 0) // 8 7 1000 Hz
#define RADIOLIB_LR11X0_GNSS_CONTEXT_FREQ_SPACE_2000_HZ (0x03UL << 0) // 8 7 2000 Hz
@@ -561,6 +568,65 @@
#define RADIOLIB_LR11X0_GNSS_ALMANAC_HEADER_ID (0x80UL << 0) // 7 0 starting byte of GNSS almanac header
#define RADIOLIB_LR11X0_GNSS_ALMANAC_BLOCK_SIZE (20)
// RADIOLIB_LR11X0_CMD_GNSS_FETCH_TIME
#define RADIOLIB_LR11X0_GNSS_EFFORT_LOW (0x00UL << 0) // 7 0 GNSS effort mode: low sensitivity
#define RADIOLIB_LR11X0_GNSS_EFFORT_MID (0x01UL << 0) // 7 0 medium sensitivity
#define RADIOLIB_LR11X0_GNSS_FETCH_TIME_OPT_TOW (0x00UL << 0) // 7 0 time fetch options: ToW only, requires WN to demodulated beforehand
#define RADIOLIB_LR11X0_GNSS_FETCH_TIME_OPT_TOW_WN (0x01UL << 0) // 7 0 ToW and WN
#define RADIOLIB_LR11X0_GNSS_FETCH_TIME_OPT_TOW_WN_ROLL (0x02UL << 0) // 7 0 ToW, WN and rollover
// RADIOLIB_LR11X0_CMD_GNSS_READ_DEMOD_STATUS
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_NOT_POSSIBLE (-21) // 7 0 GNSS demodulation status: not possible to demodulate
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_SAT_LOST (-20) // 7 0 satellite lost
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_ALMANAC_DEMOD_ERROR (-19) // 7 0 almanac demodulation error
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_TOO_LATE (-18) // 7 0 woke up after preamble (demodulation started too late)
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_20_MS_FAIL (-17) // 7 0 20ms real-time clock failed
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_WAKE_UP_FAIL (-16) // 7 0 wake up sync failed
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_WN_INVALID (-15) // 7 0 week number not validated
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_NO_ACTIVE_SAT (-14) // 7 0 no active satellite selected in satellite list
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_SLEEP_TOO_LONG (-13) // 7 0 sleep time too long
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_TOW_INVALID (-12) // 7 0 wrong time-of-week demodulated
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_PREAMBLE_INVALID (-11) // 7 0 preamble not validated
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_DISABLED (-10) // 7 0 demodulator disabled
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_EXTR_FAILED (-9) // 7 0 demodulator extraction failed
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_NO_BIT_CHANGE (-8) // 7 0 no bit change found during demodulation start
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_NO_BIT_CHANGE_ADV (-7) // 7 0 no bit change found during advanced scan
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_NO_SAT_FOUND (-6) // 7 0 no satellites found
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_SYNC_LOST (-5) // 7 0 word sync lost
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_PARITY_NOT_ENOUGH (-3) // 7 0 parity check fail (not enough)
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_PARITY_TOO_MANY (-2) // 7 0 parity check fail (too many)
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_NO_PARITY (-1) // 7 0 parity check fail (no parity found)
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_WORD_SYNC_NONE (0) // 7 0 word sync search not started
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_WORD_SYNC_POT (1) // 7 0 potential word sync found
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_WORD_SYNC_OK (2) // 7 0 word sync found
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_TOW_FOUND (3) // 7 0 time-of-week found
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_WN_FOUND (4) // 7 0 week number and time-of-week found
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_ALM_FOUND_UNSAVED (5) // 7 0 almanac found but not saved
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_HALF_ALM_SAVED (6) // 7 0 half of almanac found and saved
#define RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_FULL_ALM_SAVED (7) // 7 0 full almanac found and saved
#define RADIOLIB_LR11X0_GNSS_DEMOD_INFO_WORD_SYNC_FOUND (0x01UL << 0) // 7 0 GNSS demodulation info: word synchronization found
#define RADIOLIB_LR11X0_GNSS_DEMOD_INFO_TOW_FOUND (0x01UL << 1) // 7 0 time-of-week found
#define RADIOLIB_LR11X0_GNSS_DEMOD_INFO_WN_DEMODED (0x01UL << 2) // 7 0 week number demodulated
#define RADIOLIB_LR11X0_GNSS_DEMOD_INFO_WN_FOUND (0x01UL << 3) // 7 0 week number found
#define RADIOLIB_LR11X0_GNSS_DEMOD_INFO_SUBFRAME_1_FOUND (0x01UL << 4) // 7 0 subframe 1 found
#define RADIOLIB_LR11X0_GNSS_DEMOD_INFO_SUBFRAME_4_FOUND (0x01UL << 5) // 7 0 subframe 4 found
#define RADIOLIB_LR11X0_GNSS_DEMOD_INFO_SUBFRAME_5_FOUND (0x01UL << 6) // 7 0 subframe 5 found
// RADIOLIB_LR11X0_CMD_GNSS_READ_ALMANAC_STATUS
#define RADIOLIB_LR11X0_GNSS_ALMANAC_STATUS_UP_TO_DATE (0) // 7 0 GPS/BeiDou almanac status: all satellites up-to-date
#define RADIOLIB_LR11X0_GNSS_ALMANAC_STATUS_OUTDATED (1) // 7 0 at least one satellite needs update
// RADIOLIB_LR11X0_CMD_GNSS_READ_DOPPLER_SOLVER_RES
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_NONE (0) // 7 0 internal 2D solver error: no error
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_RES_HIGH (1) // 7 0 residue too high
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_NOT_CONVERGED (2) // 7 0 not converged on solution
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_NOT_ENOUGH_SV (3) // 7 0 not enough satellites
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_ILL_MATRIX (4) // 7 0 matrix error (?)
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_TIME (5) // 7 0 time error
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_ALM_PART_OLD (6) // 7 0 part of almanac too old or not available
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_INCONSISTENT (7) // 7 0 not consistent with history (?)
#define RADIOLIB_LR11X0_GNSS_SOLVER_ERR_ALM_OLD (8) // 7 0 all of almanac too old
// RADIOLIB_LR11X0_CMD_CRYPTO_SET_KEY
#define RADIOLIB_LR11X0_CRYPTO_STATUS_SUCCESS (0x00UL << 0) // 7 0 crypto engine status: success
#define RADIOLIB_LR11X0_CRYPTO_STATUS_FAIL_CMAC (0x01UL << 0) // 7 0 MIC check failed
@@ -714,8 +780,90 @@ struct LR11x0VersionInfo_t {
uint8_t almanacGNSS;
};
/*!
\struct LR11x0GnssResult_t
\brief Structure to report information results of a GNSS scan.
*/
struct LR11x0GnssResult_t {
/*! \brief Demodulator status. One of RADIOLIB_LR11X0_GNSS_DEMOD_STATUS_* */
int8_t demodStat;
/*! \brief Number of satellites detected during the scan. */
uint8_t numSatsDet;
/*! \brief Result size, used when passing data to LoRa cloud. */
uint16_t resSize;
};
/*!
\struct LR11x0GnssPosition_t
\brief Structure to report position from LR11x0 internal solver.
*/
struct LR11x0GnssPosition_t {
/*! \brief Latitude in degrees. */
float latitude;
/*! \brief Longitude in degrees. */
float longitude;
/*! \brief Accuracy of this result. */
uint16_t accuracy;
/*! \brief Number of satellites used to solve this position. */
uint8_t numSatsUsed;
};
/*!
\struct LR11x0GnssSatellite_t
\brief Structure to save information about a satellite found during GNSS scan.
*/
struct LR11x0GnssSatellite_t {
/*! \brief Satellite vehicle (SV) identifier. */
uint8_t svId;
/*! \brief C/N0 in dB. */
uint8_t c_n0;
/*! \brief Doppler shift of the signal in Hz. */
int16_t doppler;
};
/*!
\struct LR11x0GnssAlmanacStatusPart_t
\brief Structure to save information about one constellation of the GNSS almanac.
*/
struct LR11x0GnssAlmanacStatusPart_t {
int8_t status;
uint32_t timeUntilSubframe;
uint8_t numSubframes;
uint8_t nextSubframe4SvId;
uint8_t nextSubframe5SvId;
uint8_t nextSubframeStart;
uint8_t numUpdateNeeded;
uint32_t flagsUpdateNeeded[2];
uint32_t flagsActive[2];
};
/*!
\struct LR11x0GnssAlmanacStatus_t
\brief Structure to save information about the GNSS almanac.
This is not the actual almanac, just some context information about it.
*/
struct LR11x0GnssAlmanacStatus_t {
/*! \brief GPS part of the almanac */
LR11x0GnssAlmanacStatusPart_t gps;
/*! \brief BeiDou part of the almanac */
LR11x0GnssAlmanacStatusPart_t beidou;
/*! \brief Extra flags present for BeiDou only */
uint32_t beidouSvNoAlmanacFlags[2];
/*! \brief Next almanac ID */
uint8_t nextAlmanacId;
/*! \brief Timestamp of when almanac status was retrieved - timeUntilSubframe is relative to this value. */
RadioLibTime_t start;
};
/*!
@@ -773,9 +921,10 @@ class LR11x0: public PhysicalLayer {
\param syncWord 1-byte LoRa sync word.
\param preambleLength LoRa preamble length in symbols
\param tcxoVoltage TCXO reference voltage to be set.
\param high defaults to false for Sub-GHz band, true for frequencies above 1GHz
\returns \ref status_codes
*/
int16_t begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage);
int16_t begin(float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage, bool high = false);
/*!
\brief Initialization method for FSK modem.
@@ -792,10 +941,19 @@ class LR11x0: public PhysicalLayer {
\brief Initialization method for LR-FHSS modem.
\param bw LR-FHSS bandwidth, one of RADIOLIB_LR11X0_LR_FHSS_BW_* values.
\param cr LR-FHSS coding rate, one of RADIOLIB_LR11X0_LR_FHSS_CR_* values.
\param narrowGrid Whether to use narrow (3.9 kHz) or wide (25.39 kHz) grid spacing.
\param tcxoVoltage TCXO reference voltage to be set.
\returns \ref status_codes
*/
int16_t beginLRFHSS(uint8_t bw, uint8_t cr, float tcxoVoltage);
int16_t beginLRFHSS(uint8_t bw, uint8_t cr, bool narrowGrid, float tcxoVoltage);
/*!
\brief Initialization method for GNSS scanning.
\param constellations GNSS constellations to use (GPS, BeiDou or both). Defaults to both.
\param tcxoVoltage TCXO reference voltage to be set.
\returns \ref status_codes
*/
int16_t beginGNSS(uint8_t constellations = RADIOLIB_LR11X0_GNSS_CONSTELLATION_GPS | RADIOLIB_LR11X0_GNSS_CONSTELLATION_BEIDOU, float tcxoVoltage = 1.6);
/*!
\brief Reset method. Will reset the chip to the default state using RST pin.
@@ -993,11 +1151,12 @@ class LR11x0: public PhysicalLayer {
// configuration methods
/*!
\brief Sets LoRa bandwidth. Allowed values are 62.5, 125.0, 250.0 and 500.0 kHz.
\brief Sets LoRa bandwidth. Allowed values are 62.5, 125.0, 250.0 and 500.0 kHz. (default, high = false)
\param bw LoRa bandwidth to be set in kHz.
\param high if set to true, allowed bandwidth is 203.125, 406.25 and 812.5 kHz, frequency must be above 1GHz
\returns \ref status_codes
*/
int16_t setBandwidth(float bw);
int16_t setBandwidth(float bw, bool high = false);
/*!
\brief Sets LoRa spreading factor. Allowed values range from 5 to 12.
@@ -1283,6 +1442,21 @@ class LR11x0: public PhysicalLayer {
/*! \copydoc Module::setRfSwitchTable */
void setRfSwitchTable(const uint32_t (&pins)[Module::RFSWITCH_MAX_PINS], const Module::RfSwitchMode_t table[]);
/*!
\brief Forces LoRa low data rate optimization. Only available in LoRa mode. After calling this method, LDRO will always be set to
the provided value, regardless of symbol length. To re-enable automatic LDRO configuration, call LR11x0::autoLDRO()
\param enable Force LDRO to be always enabled (true) or disabled (false).
\returns \ref status_codes
*/
int16_t forceLDRO(bool enable);
/*!
\brief Re-enables automatic LDRO configuration. Only available in LoRa mode. After calling this method, LDRO will be enabled automatically
when symbol length exceeds 16 ms.
\returns \ref status_codes
*/
int16_t autoLDRO();
/*!
\brief Sets LR-FHSS configuration.
\param bw LR-FHSS bandwidth, one of RADIOLIB_LR11X0_LR_FHSS_BW_* values.
@@ -1375,6 +1549,79 @@ class LR11x0: public PhysicalLayer {
*/
int16_t updateFirmware(const uint32_t* image, size_t size, bool nonvolatile = true);
/*!
\brief Method to check whether the device is capable of performing a GNSS scan.
\returns \ref status_codes
*/
int16_t isGnssScanCapable();
/*!
\brief Performs GNSS scan.
\param res Pointer to LR11x0GnssPosition_t structure to populate.
Will not be saved if set to NULL, defaults to NULL.
\returns \ref status_codes
*/
int16_t gnssScan(LR11x0GnssResult_t* res = NULL);
/*!
\brief Read information about the almanac.
\param stat Pointer to structure to save the almanac status into.
This is not the actual almanac, just a structure providing information about it.
\returns \ref status_codes
*/
int16_t getGnssAlmanacStatus(LR11x0GnssAlmanacStatus_t *stat);
/*!
\brief Blocking wait until the next subframe with almanac data is available.
Used to control timing during almanac update from satellite.
\param stat Pointer to structure containing the almanac status read by getGnssAlmanacStatus.
This is not the actual almanac, just a structure providing information about it.
\param constellation Constellation to wait for, one of RADIOLIB_LR11X0_GNSS_CONSTELLATION_*.
Constellations cannot be updated at the same time, but rather must be updated sequentially!
\returns \ref status_codes
*/
int16_t gnssDelayUntilSubframe(LR11x0GnssAlmanacStatus_t *stat, uint8_t constellation);
/*!
\brief Perform almanac update. Must be called immediately after gnssDelayUntilSubframe.
\param constellation Constellation to update, one of RADIOLIB_LR11X0_GNSS_CONSTELLATION_*.
Constellations cannot be updated at the same time, but rather must be updated sequentially!
\returns \ref status_codes
*/
int16_t updateGnssAlmanac(uint8_t constellation);
/*!
\brief Get GNSS position. Called after gnssScan to retrieve the position calculated by the internal solver.
\param pos Pointer to LR11x0GnssPosition_t structure to populate.
\param filtered Whether to save the filtered, or unfiltered values. Defaults to true (filtered).
\returns \ref status_codes
*/
int16_t getGnssPosition(LR11x0GnssPosition_t* pos, bool filtered = true);
/*!
\brief Get GNSS satellites found during the last scan.
\param sats Pointer to array of LR11x0GnssSatellite_t structures to populate.
\param numSats Number of satellites to read. Can be retrieved from LR11x0GnssResult_t passed to gnssScan.
\returns \ref status_codes
*/
int16_t getGnssSatellites(LR11x0GnssSatellite_t* sats, uint8_t numSats);
/*!
\brief Get modem currently in use by the radio.
\param modem Pointer to a variable to save the retrieved configuration into.
\returns \ref status_codes
*/
int16_t getModem(ModemType_t* modem) override;
/*!
\brief Perform image rejection calibration for the specified frequency band.
WARNING: Use at your own risk! Setting incorrect values may lead to decreased performance
\param freqMin Frequency band lower bound.
\param freqMax Frequency band upper bound.
\returns \ref status_codes
*/
int16_t calibrateImageRejection(float freqMin, float freqMax);
#if !RADIOLIB_GODMODE && !RADIOLIB_LOW_LEVEL
protected:
#endif
@@ -1394,7 +1641,6 @@ class LR11x0: public PhysicalLayer {
int16_t clearErrors(void);
int16_t calibrate(uint8_t params);
int16_t setRegMode(uint8_t mode);
int16_t calibImage(float freq1, float freq2);
int16_t setDioAsRfSwitch(uint8_t en, uint8_t stbyCfg, uint8_t rxCfg, uint8_t txCfg, uint8_t txHpCfg, uint8_t txHfCfg, uint8_t gnssCfg, uint8_t wifiCfg);
int16_t setDioIrqParams(uint32_t irq1, uint32_t irq2);
int16_t setDioIrqParams(uint32_t irq);
@@ -1525,6 +1771,7 @@ class LR11x0: public PhysicalLayer {
int16_t gnssReadWarmStartStatus(uint8_t bitMask, uint8_t* nbVisSat, uint32_t* timeElapsed);
int16_t gnssGetSvSync(uint8_t mask, uint8_t nbSv, uint8_t* syncList);
int16_t gnssWriteBitMaskSatActivated(uint8_t bitMask, uint32_t* bitMaskActivated0, uint32_t* bitMaskActivated1);
void gnssAbort();
int16_t cryptoSetKey(uint8_t keyId, uint8_t* key);
int16_t cryptoDeriveKey(uint8_t srcKeyId, uint8_t dstKeyId, uint8_t* key);
@@ -1554,6 +1801,7 @@ class LR11x0: public PhysicalLayer {
protected:
#endif
uint8_t chipType = 0;
float freqMHz = 0;
#if !RADIOLIB_GODMODE
private:
@@ -1574,7 +1822,7 @@ class LR11x0: public PhysicalLayer {
uint16_t preambleLengthGFSK = 0;
// cached LR-FHSS parameters
uint8_t lrFhssCr = 0, lrFhssBw = 0, lrFhssHdrCount = 0;
uint8_t lrFhssCr = 0, lrFhssBw = 0, lrFhssHdrCount = 0, lrFhssGrid = 0;
uint16_t lrFhssHopSeq = 0;
float dataRateMeasured = 0;
@@ -9,7 +9,7 @@ This file is licensed under the MIT License: https://opensource.org/licenses/MIT
#if !RADIOLIB_EXCLUDE_STM32WLX
#include "../../ArduinoHal.h"
#include "hal/Arduino/ArduinoHal.h"
// This defines some dummy pin numbers (starting at NUM_DIGITAL_PINS to
// guarantee these are not valid regular pin numbers) that can be passed
+42 -39
View File
@@ -1,4 +1,6 @@
#include "SX1262.h"
#include <math.h>
#if !RADIOLIB_EXCLUDE_SX126X
SX1262::SX1262(Module* mod) : SX126x(mod) {
@@ -47,50 +49,35 @@ int16_t SX1262::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t
return(state);
}
int16_t SX1262::setFrequency(float freq) {
return(setFrequency(freq, true));
int16_t SX1262::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, bool narrowGrid, int8_t power, float tcxoVoltage, bool useRegulatorLDO) {
// execute common part
int16_t state = SX126x::beginLRFHSS(bw, cr, narrowGrid, tcxoVoltage, useRegulatorLDO);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
state = setFrequency(freq);
RADIOLIB_ASSERT(state);
state = SX126x::fixPaClamping();
RADIOLIB_ASSERT(state);
state = setOutputPower(power);
RADIOLIB_ASSERT(state);
return(state);
}
int16_t SX1262::setFrequency(float freq, bool calibrate) {
int16_t SX1262::setFrequency(float freq) {
return(setFrequency(freq, false));
}
int16_t SX1262::setFrequency(float freq, bool skipCalibration) {
RADIOLIB_CHECK_RANGE(freq, 150.0, 960.0, RADIOLIB_ERR_INVALID_FREQUENCY);
// calibrate image rejection
if(calibrate) {
uint8_t data[2] = { 0, 0 };
// try to match the frequency ranges
int freqBand = (int)freq;
if((freqBand >= 902) && (freqBand <= 928)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_902_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_902_MHZ_2;
} else if((freqBand >= 863) && (freqBand <= 870)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_863_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_863_MHZ_2;
} else if((freqBand >= 779) && (freqBand <= 787)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_779_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_779_MHZ_2;
} else if((freqBand >= 470) && (freqBand <= 510)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_470_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_470_MHZ_2;
} else if((freqBand >= 430) && (freqBand <= 440)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_430_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_430_MHZ_2;
}
int16_t state;
if(data[0]) {
// matched with predefined ranges, do the calibration
state = SX126x::calibrateImage(data);
} else {
// if nothing matched, try custom calibration - the may or may not work
RADIOLIB_DEBUG_BASIC_PRINTLN("Failed to match predefined frequency range, trying custom");
state = SX126x::calibrateImageRejection(freq - 4.0f, freq + 4.0f);
}
// check if we need to recalibrate image
if(!skipCalibration && (fabsf(freq - this->freqMHz) >= RADIOLIB_SX126X_CAL_IMG_FREQ_TRIG_MHZ)) {
int16_t state = this->calibrateImage(freq);
RADIOLIB_ASSERT(state);
}
// set frequency
@@ -127,4 +114,20 @@ int16_t SX1262::checkOutputPower(int8_t power, int8_t* clipped) {
return(RADIOLIB_ERR_NONE);
}
int16_t SX1262::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
case(ModemType_t::LRFHSS): {
return(this->beginLRFHSS());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+29 -2
View File
@@ -62,10 +62,27 @@ class SX1262: public SX126x {
*/
int16_t beginFSK(float freq = 434.0, float br = 4.8, float freqDev = 5.0, float rxBw = 156.2, int8_t power = 10, uint16_t preambleLength = 16, float tcxoVoltage = 1.6, bool useRegulatorLDO = false);
/*!
\brief Initialization method for LR-FHSS modem. This modem only supports transmission!
\param freq Carrier frequency in MHz. Defaults to 434.0 MHz.
\param bw LR-FHSS bandwidth, one of RADIOLIB_SX126X_LR_FHSS_BW_* values. Defaults to 722.66 kHz.
\param cr LR-FHSS coding rate, one of RADIOLIB_SX126X_LR_FHSS_CR_* values. Defaults to 2/3 coding rate.
\param narrowGrid Whether to use narrow (3.9 kHz) or wide (25.39 kHz) grid spacing. Defaults to true (narrow/non-FCC) grid.
\param power Output power in dBm. Defaults to 10 dBm.
\param tcxoVoltage TCXO reference voltage to be set. Defaults to 1.6 V.
If you are seeing -706/-707 error codes, it likely means you are using non-0 value for module with XTAL.
To use XTAL, either set this value to 0, or set SX126x::XTAL to true.
\param useRegulatorLDO Whether to use only LDO regulator (true) or DC-DC regulator (false). Defaults to false.
\returns \ref status_codes
*/
int16_t beginLRFHSS(float freq = 434.0, uint8_t bw = RADIOLIB_SX126X_LR_FHSS_BW_722_66, uint8_t cr = RADIOLIB_SX126X_LR_FHSS_CR_2_3, bool narrowGrid = true, int8_t power = 10, float tcxoVoltage = 1.6, bool useRegulatorLDO = false);
// configuration methods
/*!
\brief Sets carrier frequency. Allowed values are in range from 150.0 to 960.0 MHz.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_SX126X_CAL_IMG_FREQ_TRIG MHz.
\param freq Carrier frequency to be set in MHz.
\returns \ref status_codes
*/
@@ -73,11 +90,13 @@ class SX1262: public SX126x {
/*!
\brief Sets carrier frequency. Allowed values are in range from 150.0 to 960.0 MHz.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_SX126X_CAL_IMG_FREQ_TRIG_MHZ.
\param freq Carrier frequency to be set in MHz.
\param calibrate Run image calibration.
\param skipCalibration Skip automated image calibration.
\returns \ref status_codes
*/
int16_t setFrequency(float freq, bool calibrate);
int16_t setFrequency(float freq, bool skipCalibration);
/*!
\brief Sets output power. Allowed values are in range from -9 to 22 dBm.
@@ -94,6 +113,14 @@ class SX1262: public SX126x {
\returns \ref status_codes
*/
int16_t checkOutputPower(int8_t power, int8_t* clipped) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK, LoRa or LR-FHSS.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
+41 -32
View File
@@ -1,4 +1,6 @@
#include "SX1268.h"
#include <math.h>
#if !RADIOLIB_EXCLUDE_SX126X
SX1268::SX1268(Module* mod) : SX126x(mod) {
@@ -47,45 +49,36 @@ int16_t SX1268::beginFSK(float freq, float br, float freqDev, float rxBw, int8_t
return(state);
}
int16_t SX1268::beginLRFHSS(float freq, uint8_t bw, uint8_t cr, bool narrowGrid, int8_t power, float tcxoVoltage, bool useRegulatorLDO) {
// execute common part
int16_t state = SX126x::beginLRFHSS(bw, cr, narrowGrid, tcxoVoltage, useRegulatorLDO);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
state = setFrequency(freq);
RADIOLIB_ASSERT(state);
state = SX126x::fixPaClamping();
RADIOLIB_ASSERT(state);
state = setOutputPower(power);
RADIOLIB_ASSERT(state);
return(state);
}
int16_t SX1268::setFrequency(float freq) {
return(setFrequency(freq, true));
return(setFrequency(freq, false));
}
/// \todo integers only (all modules - frequency, data rate, bandwidth etc.)
int16_t SX1268::setFrequency(float freq, bool calibrate) {
int16_t SX1268::setFrequency(float freq, bool skipCalibration) {
RADIOLIB_CHECK_RANGE(freq, 410.0, 810.0, RADIOLIB_ERR_INVALID_FREQUENCY);
// calibrate image rejection
if(calibrate) {
uint8_t data[2] = { 0, 0 };
// try to match the frequency ranges
int freqBand = (int)freq;
if((freqBand >= 779) && (freqBand <= 787)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_779_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_779_MHZ_2;
} else if((freqBand >= 470) && (freqBand <= 510)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_470_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_470_MHZ_2;
} else if((freqBand >= 430) && (freqBand <= 440)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_430_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_430_MHZ_2;
}
int16_t state;
if(data[0]) {
// matched with predefined ranges, do the calibration
state = SX126x::calibrateImage(data);
} else {
// if nothing matched, try custom calibration - the may or may not work
RADIOLIB_DEBUG_BASIC_PRINTLN("Failed to match predefined frequency range, trying custom");
state = SX126x::calibrateImageRejection(freq - 4.0f, freq + 4.0f);
}
// check if we need to recalibrate image
if(!skipCalibration && (fabsf(freq - this->freqMHz) >= RADIOLIB_SX126X_CAL_IMG_FREQ_TRIG_MHZ)) {
int16_t state = this->calibrateImage(freq);
RADIOLIB_ASSERT(state);
}
// set frequency
@@ -122,4 +115,20 @@ int16_t SX1268::checkOutputPower(int8_t power, int8_t* clipped) {
return(RADIOLIB_ERR_NONE);
}
int16_t SX1268::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
case(ModemType_t::LRFHSS): {
return(this->beginLRFHSS());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+29 -2
View File
@@ -61,10 +61,27 @@ class SX1268: public SX126x {
*/
int16_t beginFSK(float freq = 434.0, float br = 4.8, float freqDev = 5.0, float rxBw = 156.2, int8_t power = 10, uint16_t preambleLength = 16, float tcxoVoltage = 1.6, bool useRegulatorLDO = false);
/*!
\brief Initialization method for LR-FHSS modem. This modem only supports transmission!
\param freq Carrier frequency in MHz. Defaults to 434.0 MHz.
\param bw LR-FHSS bandwidth, one of RADIOLIB_SX126X_LR_FHSS_BW_* values. Defaults to 722.66 kHz.
\param cr LR-FHSS coding rate, one of RADIOLIB_SX126X_LR_FHSS_CR_* values. Defaults to 2/3 coding rate.
\param narrowGrid Whether to use narrow (3.9 kHz) or wide (25.39 kHz) grid spacing. Defaults to true (narrow/non-FCC) grid.
\param power Output power in dBm. Defaults to 10 dBm.
\param tcxoVoltage TCXO reference voltage to be set. Defaults to 1.6 V.
If you are seeing -706/-707 error codes, it likely means you are using non-0 value for module with XTAL.
To use XTAL, either set this value to 0, or set SX126x::XTAL to true.
\param useRegulatorLDO Whether to use only LDO regulator (true) or DC-DC regulator (false). Defaults to false.
\returns \ref status_codes
*/
int16_t beginLRFHSS(float freq = 434.0, uint8_t bw = RADIOLIB_SX126X_LR_FHSS_BW_722_66, uint8_t cr = RADIOLIB_SX126X_LR_FHSS_CR_2_3, bool narrowGrid = true, int8_t power = 10, float tcxoVoltage = 1.6, bool useRegulatorLDO = false);
// configuration methods
/*!
\brief Sets carrier frequency. Allowed values are in range from 410.0 to 810.0 MHz.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_SX126X_CAL_IMG_FREQ_TRIG MHz.
\param freq Carrier frequency to be set in MHz.
\returns \ref status_codes
*/
@@ -72,11 +89,13 @@ class SX1268: public SX126x {
/*!
\brief Sets carrier frequency. Allowed values are in range from 150.0 to 960.0 MHz.
Will automatically perform image calibration if the frequency changes by
more than RADIOLIB_SX126X_CAL_IMG_FREQ_TRIG_MHZ.
\param freq Carrier frequency to be set in MHz.
\param calibrate Run image calibration.
\param skipCalibration Skip automated image calibration.
\returns \ref status_codes
*/
int16_t setFrequency(float freq, bool calibrate);
int16_t setFrequency(float freq, bool skipCalibration);
/*!
\brief Sets output power. Allowed values are in range from -9 to 22 dBm.
@@ -92,6 +111,14 @@ class SX1268: public SX126x {
\returns \ref status_codes
*/
int16_t checkOutputPower(int8_t power, int8_t* clipped) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK, LoRa or LR-FHSS.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
+334 -150
View File
@@ -20,35 +20,13 @@ SX126x::SX126x(Module* mod) : PhysicalLayer(RADIOLIB_SX126X_FREQUENCY_STEP_SIZE,
}
int16_t SX126x::begin(uint8_t cr, uint8_t syncWord, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) {
// set module properties
this->mod->init();
this->mod->hal->pinMode(this->mod->getIrq(), this->mod->hal->GpioModeInput);
this->mod->hal->pinMode(this->mod->getGpio(), this->mod->hal->GpioModeInput);
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_ADDR] = Module::BITS_16;
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_CMD] = Module::BITS_8;
this->mod->spiConfig.statusPos = 1;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_READ] = RADIOLIB_SX126X_CMD_READ_REGISTER;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_WRITE] = RADIOLIB_SX126X_CMD_WRITE_REGISTER;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_NOP] = RADIOLIB_SX126X_CMD_NOP;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_STATUS] = RADIOLIB_SX126X_CMD_GET_STATUS;
this->mod->spiConfig.stream = true;
this->mod->spiConfig.parseStatusCb = SPIparseStatus;
// try to find the SX126x chip
if(!SX126x::findChip(this->chipType)) {
RADIOLIB_DEBUG_BASIC_PRINTLN("No SX126x found!");
this->mod->term();
return(RADIOLIB_ERR_CHIP_NOT_FOUND);
}
RADIOLIB_DEBUG_BASIC_PRINTLN("M\tSX126x");
// BW in kHz and SF are required in order to calculate LDRO for setModulationParams
// set the defaults, this will get overwritten later anyway
this->bandwidthKhz = 500.0;
this->spreadingFactor = 9;
// initialize configuration variables (will be overwritten during public settings configuration)
this->bandwidth = RADIOLIB_SX126X_LORA_BW_500_0; // initialized to 500 kHz, since lower valeus will interfere with LLCC68
this->bandwidth = RADIOLIB_SX126X_LORA_BW_500_0; // initialized to 500 kHz, since lower values will interfere with LLCC68
this->codingRate = RADIOLIB_SX126X_LORA_CR_4_7;
this->ldrOptimize = 0x00;
this->crcTypeLoRa = RADIOLIB_SX126X_LORA_CRC_ON;
@@ -57,22 +35,8 @@ int16_t SX126x::begin(uint8_t cr, uint8_t syncWord, uint16_t preambleLength, flo
this->headerType = RADIOLIB_SX126X_LORA_HEADER_EXPLICIT;
this->implicitLen = 0xFF;
// reset the module and verify startup
int16_t state = reset();
RADIOLIB_ASSERT(state);
// set mode to standby
state = standby();
RADIOLIB_ASSERT(state);
// set TCXO control, if requested
if(!this->XTAL && tcxoVoltage > 0.0) {
state = setTCXO(tcxoVoltage);
RADIOLIB_ASSERT(state);
}
// configure settings not accessible by API
state = config(RADIOLIB_SX126X_PACKET_TYPE_LORA);
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, useRegulatorLDO, RADIOLIB_SX126X_PACKET_TYPE_LORA);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
@@ -85,13 +49,6 @@ int16_t SX126x::begin(uint8_t cr, uint8_t syncWord, uint16_t preambleLength, flo
state = setPreambleLength(preambleLength);
RADIOLIB_ASSERT(state);
if (useRegulatorLDO) {
state = setRegulatorLDO();
} else {
state = setRegulatorDCDC();
}
RADIOLIB_ASSERT(state);
// set publicly accessible settings that are not a part of begin method
state = setCurrentLimit(60.0);
RADIOLIB_ASSERT(state);
@@ -109,54 +66,18 @@ int16_t SX126x::begin(uint8_t cr, uint8_t syncWord, uint16_t preambleLength, flo
}
int16_t SX126x::beginFSK(float br, float freqDev, float rxBw, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO) {
// set module properties
this->mod->init();
this->mod->hal->pinMode(this->mod->getIrq(), this->mod->hal->GpioModeInput);
this->mod->hal->pinMode(this->mod->getGpio(), this->mod->hal->GpioModeInput);
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_ADDR] = Module::BITS_16;
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_CMD] = Module::BITS_8;
this->mod->spiConfig.statusPos = 1;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_READ] = RADIOLIB_SX126X_CMD_READ_REGISTER;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_WRITE] = RADIOLIB_SX126X_CMD_WRITE_REGISTER;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_NOP] = RADIOLIB_SX126X_CMD_NOP;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_STATUS] = RADIOLIB_SX126X_CMD_GET_STATUS;
this->mod->spiConfig.stream = true;
this->mod->spiConfig.parseStatusCb = SPIparseStatus;
// try to find the SX126x chip
if(!SX126x::findChip(this->chipType)) {
RADIOLIB_DEBUG_BASIC_PRINTLN("No SX126x found!");
this->mod->term();
return(RADIOLIB_ERR_CHIP_NOT_FOUND);
}
RADIOLIB_DEBUG_BASIC_PRINTLN("M\tSX126x");
// initialize configuration variables (will be overwritten during public settings configuration)
this->bitRate = 21333; // 48.0 kbps
this->frequencyDev = 52428; // 50.0 kHz
this->rxBandwidth = RADIOLIB_SX126X_GFSK_RX_BW_156_2;
this->rxBandwidthKhz = 156.2;
this->pulseShape = RADIOLIB_SX126X_GFSK_FILTER_GAUSS_0_5;
this->crcTypeFSK = RADIOLIB_SX126X_GFSK_CRC_2_BYTE_INV; // CCIT CRC configuration
this->crcTypeFSK = RADIOLIB_SX126X_GFSK_CRC_2_BYTE_INV; // CCITT CRC configuration
this->preambleLengthFSK = preambleLength;
this->addrComp = RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF;
// reset the module and verify startup
int16_t state = reset();
RADIOLIB_ASSERT(state);
// set mode to standby
state = standby();
RADIOLIB_ASSERT(state);
// set TCXO control, if requested
if(!this->XTAL && tcxoVoltage > 0.0) {
state = setTCXO(tcxoVoltage);
RADIOLIB_ASSERT(state);
}
// configure settings not accessible by API
state = config(RADIOLIB_SX126X_PACKET_TYPE_GFSK);
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, useRegulatorLDO, RADIOLIB_SX126X_PACKET_TYPE_GFSK);
RADIOLIB_ASSERT(state);
// configure publicly accessible settings
@@ -175,13 +96,6 @@ int16_t SX126x::beginFSK(float br, float freqDev, float rxBw, uint16_t preambleL
state = setPreambleLength(preambleLength);
RADIOLIB_ASSERT(state);
if(useRegulatorLDO) {
state = setRegulatorLDO();
} else {
state = setRegulatorDCDC();
}
RADIOLIB_ASSERT(state);
// set publicly accessible settings that are not a part of begin method
uint8_t sync[] = {0x12, 0xAD};
state = setSyncWord(sync, 2);
@@ -205,6 +119,47 @@ int16_t SX126x::beginFSK(float br, float freqDev, float rxBw, uint16_t preambleL
return(state);
}
int16_t SX126x::beginLRFHSS(uint8_t bw, uint8_t cr, bool narrowGrid, float tcxoVoltage, bool useRegulatorLDO) {
this->lrFhssGridNonFcc = narrowGrid;
// set module properties and perform initial setup
int16_t state = this->modSetup(tcxoVoltage, useRegulatorLDO, RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS);
RADIOLIB_ASSERT(state);
// set publicly accessible settings that are not a part of begin method
state = setCurrentLimit(60.0);
RADIOLIB_ASSERT(state);
state = setDio2AsRfSwitch(true);
RADIOLIB_ASSERT(state);
// set all packet params to 0 (packet engine is disabled in LR-FHSS mode)
state = setPacketParamsFSK(0, 0, 0, 0, 0, 0, 0, 0);
RADIOLIB_ASSERT(state);
// set bit rate
this->rxBandwidth = 0;
this->frequencyDev = 0;
this->pulseShape = RADIOLIB_SX126X_GFSK_FILTER_GAUSS_1;
state = setBitRate(0.48828125f);
RADIOLIB_ASSERT(state);
return(setLrFhssConfig(bw, cr));
}
int16_t SX126x::setLrFhssConfig(uint8_t bw, uint8_t cr, uint8_t hdrCount, uint16_t hopSeqId) {
// check and cache all parameters
RADIOLIB_CHECK_RANGE((int8_t)cr, (int8_t)RADIOLIB_SX126X_LR_FHSS_CR_5_6, (int8_t)RADIOLIB_SX126X_LR_FHSS_CR_1_3, RADIOLIB_ERR_INVALID_CODING_RATE);
this->lrFhssCr = cr;
RADIOLIB_CHECK_RANGE((int8_t)bw, (int8_t)RADIOLIB_SX126X_LR_FHSS_BW_39_06, (int8_t)RADIOLIB_SX126X_LR_FHSS_BW_1574_2, RADIOLIB_ERR_INVALID_BANDWIDTH);
this->lrFhssBw = bw;
RADIOLIB_CHECK_RANGE(hdrCount, 1, 4, RADIOLIB_ERR_INVALID_BIT_RANGE);
this->lrFhssHdrCount = hdrCount;
RADIOLIB_CHECK_RANGE((int16_t)hopSeqId, (int16_t)0x000, (int16_t)0x1FF, RADIOLIB_ERR_INVALID_DATA_SHAPING);
this->lrFhssHopSeqId = hopSeqId;
return(RADIOLIB_ERR_NONE);
}
int16_t SX126x::reset(bool verify) {
// run the reset sequence
this->mod->hal->pinMode(this->mod->getRst(), this->mod->hal->GpioModeOutput);
@@ -257,13 +212,34 @@ int16_t SX126x::transmit(const uint8_t* data, size_t len, uint8_t addr) {
RADIOLIB_ASSERT(state);
// wait for packet transmission or timeout
uint8_t modem = getPacketType();
RadioLibTime_t start = this->mod->hal->millis();
while(!this->mod->hal->digitalRead(this->mod->getIrq())) {
while(true) {
// yield for multi-threaded platforms
this->mod->hal->yield();
// check timeout
if(this->mod->hal->millis() - start > timeout) {
finishTransmit();
return(RADIOLIB_ERR_TX_TIMEOUT);
}
// poll the interrupt pin
if(this->mod->hal->digitalRead(this->mod->getIrq())) {
// in LoRa or GFSK, only Tx done interrupt is enabled
if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
break;
}
// in LR-FHSS, IRQ signals both Tx done as frequency hop request
if(this->getIrqFlags() & RADIOLIB_SX126X_IRQ_TX_DONE) {
break;
} else {
// handle frequency hop
this->setLRFHSSHop(this->lrFhssHopNum % 16);
clearIrqStatus();
}
}
}
// update data rate
@@ -435,7 +411,7 @@ int16_t SX126x::packetMode() {
}
int16_t SX126x::scanChannel() {
ChannelScanConfig_t config = {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.detPeak = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
@@ -446,7 +422,7 @@ int16_t SX126x::scanChannel() {
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->scanChannel(config));
return(this->scanChannel(cfg));
}
int16_t SX126x::scanChannel(const ChannelScanConfig_t &config) {
@@ -533,9 +509,6 @@ void SX126x::clearChannelScanAction() {
}
int16_t SX126x::startTransmit(const uint8_t* data, size_t len, uint8_t addr) {
// suppress unused variable warning
(void)addr;
// check packet length
if(len > RADIOLIB_SX126X_MAX_PACKET_LENGTH) {
return(RADIOLIB_ERR_PACKET_TOO_LONG);
@@ -551,15 +524,28 @@ int16_t SX126x::startTransmit(const uint8_t* data, size_t len, uint8_t addr) {
uint8_t modem = getPacketType();
if(modem == RADIOLIB_SX126X_PACKET_TYPE_LORA) {
state = setPacketParams(this->preambleLengthLoRa, this->crcTypeLoRa, len, this->headerType, this->invertIQEnabled);
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType, len);
} else {
// address is taken from the register
if(this->addrComp != RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF) {
RADIOLIB_ASSERT(state);
state = writeRegister(RADIOLIB_SX126X_REG_NODE_ADDRESS, &addr, 1);
}
} else if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
return(RADIOLIB_ERR_UNKNOWN);
}
RADIOLIB_ASSERT(state);
// set DIO mapping
state = setDioIrqParams(RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_TIMEOUT, RADIOLIB_SX126X_IRQ_TX_DONE);
if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
state = setDioIrqParams(RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_TIMEOUT, RADIOLIB_SX126X_IRQ_TX_DONE);
} else {
state = setDioIrqParams(RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_LR_FHSS_HOP, RADIOLIB_SX126X_IRQ_TX_DONE | RADIOLIB_SX126X_IRQ_LR_FHSS_HOP);
}
RADIOLIB_ASSERT(state);
// set buffer pointers
@@ -567,7 +553,49 @@ int16_t SX126x::startTransmit(const uint8_t* data, size_t len, uint8_t addr) {
RADIOLIB_ASSERT(state);
// write packet to buffer
if(modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
state = writeBuffer(const_cast<uint8_t*>(data), len);
} else {
// first, reset the LR-FHSS state machine
state = resetLRFHSS();
RADIOLIB_ASSERT(state);
// skip hopping for the first 4 - lrFhssHdrCount blocks
for(int i = 0; i < 4 - this->lrFhssHdrCount; ++i ) {
stepLRFHSS();
}
// in LR-FHSS mode, we need to build the entire packet manually
uint8_t frame[RADIOLIB_SX126X_MAX_PACKET_LENGTH] = { 0 };
size_t frameLen = 0;
this->lrFhssFrameBitsRem = 0;
this->lrFhssFrameHopsRem = 0;
this->lrFhssHopNum = 0;
state = buildLRFHSSPacket(const_cast<uint8_t*>(data), len, frame, &frameLen, &this->lrFhssFrameBitsRem, &this->lrFhssFrameHopsRem);
RADIOLIB_ASSERT(state);
// FIXME check max len for FHSS
state = writeBuffer(frame, frameLen);
RADIOLIB_ASSERT(state);
// activate hopping
uint8_t hopCfg[] = { RADIOLIB_SX126X_HOPPING_ENABLED, (uint8_t)frameLen, (uint8_t)this->lrFhssFrameHopsRem };
state = writeRegister(RADIOLIB_SX126X_REG_HOPPING_ENABLE, hopCfg, 3);
RADIOLIB_ASSERT(state);
// write the initial hopping table
uint8_t initHops = this->lrFhssFrameHopsRem;
if(initHops > 16) {
initHops = 16;
};
for(size_t i = 0; i < initHops; i++) {
// set the hop frequency and symbols
state = this->setLRFHSSHop(i);
RADIOLIB_ASSERT(state);
}
}
RADIOLIB_ASSERT(state);
// clear interrupt flags
@@ -595,7 +623,14 @@ int16_t SX126x::startTransmit(const uint8_t* data, size_t len, uint8_t addr) {
int16_t SX126x::finishTransmit() {
// clear interrupt flags
clearIrqStatus();
int16_t state = clearIrqStatus();
RADIOLIB_ASSERT(state);
// restore the original node address
if(getPacketType() == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
state = writeRegister(RADIOLIB_SX126X_REG_NODE_ADDRESS, &this->nodeAddr, 1);
RADIOLIB_ASSERT(state);
}
// set mode to standby to disable transmitter/RF switch
return(standby());
@@ -685,11 +720,15 @@ int16_t SX126x::startReceiveDutyCycleAuto(uint16_t senderPreambleLength, uint16_
}
int16_t SX126x::startReceiveCommon(uint32_t timeout, RadioLibIrqFlags_t irqFlags, RadioLibIrqFlags_t irqMask) {
// ensure we are in standby
int16_t state = standby();
RADIOLIB_ASSERT(state);
// set DIO mapping
if(timeout != RADIOLIB_SX126X_RX_TIMEOUT_INF) {
irqMask |= (1UL << RADIOLIB_IRQ_TIMEOUT);
}
int16_t state = setDioIrqParams(getIrqMapped(irqFlags), getIrqMapped(irqMask));
state = setDioIrqParams(getIrqMapped(irqFlags), getIrqMapped(irqMask));
RADIOLIB_ASSERT(state);
// set buffer pointers
@@ -717,14 +756,14 @@ int16_t SX126x::readData(uint8_t* data, size_t len) {
// if that's the case, the first call will return "SPI command timeout error"
// check the IRQ to be sure this really originated from timeout event
int16_t state = this->mod->SPIcheckStream();
if((state == RADIOLIB_ERR_SPI_CMD_TIMEOUT) && (getIrqFlags() & RADIOLIB_SX126X_IRQ_TIMEOUT)) {
uint16_t irq = getIrqFlags();
if((state == RADIOLIB_ERR_SPI_CMD_TIMEOUT) && (irq & RADIOLIB_SX126X_IRQ_TIMEOUT)) {
// this is definitely Rx timeout
return(RADIOLIB_ERR_RX_TIMEOUT);
}
RADIOLIB_ASSERT(state);
// check integrity CRC
uint16_t irq = getIrqFlags();
int16_t crcState = RADIOLIB_ERR_NONE;
// Report CRC mismatch when there's a payload CRC error, or a header error and no valid header (to avoid false alarm from previous packet)
if((irq & RADIOLIB_SX126X_IRQ_CRC_ERR) || ((irq & RADIOLIB_SX126X_IRQ_HEADER_ERR) && !(irq & RADIOLIB_SX126X_IRQ_HEADER_VALID))) {
@@ -753,7 +792,7 @@ int16_t SX126x::readData(uint8_t* data, size_t len) {
}
int16_t SX126x::startChannelScan() {
ChannelScanConfig_t config = {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
.detPeak = RADIOLIB_SX126X_CAD_PARAM_DEFAULT,
@@ -764,7 +803,7 @@ int16_t SX126x::startChannelScan() {
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->startChannelScan(config));
return(this->startChannelScan(cfg));
}
int16_t SX126x::startChannelScan(const ChannelScanConfig_t &config) {
@@ -929,7 +968,12 @@ int16_t SX126x::setPreambleLength(size_t preambleLength) {
return(setPacketParams(this->preambleLengthLoRa, this->crcTypeLoRa, this->implicitLen, this->headerType, this->invertIQEnabled));
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
this->preambleLengthFSK = preambleLength;
return(setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType));
this->preambleDetLength = preambleLength >= 32 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_32 :
preambleLength >= 24 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_24 :
preambleLength >= 16 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_16 :
preambleLength > 0 ? RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_8 :
RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_OFF;
return(setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType));
}
return(RADIOLIB_ERR_UNKNOWN);
@@ -1004,6 +1048,15 @@ int16_t SX126x::setDataRate(DataRate_t dr) {
// set the coding rate
state = this->setCodingRate(dr.lora.codingRate);
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
// set the basic config
state = this->setLrFhssConfig(dr.lrFhss.bw, dr.lrFhss.cr);
RADIOLIB_ASSERT(state);
// set hopping grid
this->lrFhssGridNonFcc = dr.lrFhss.narrowGrid ? RADIOLIB_SX126X_LR_FHSS_GRID_STEP_NON_FCC : RADIOLIB_SX126X_LR_FHSS_GRID_STEP_FCC;
}
return(state);
@@ -1094,37 +1147,16 @@ int16_t SX126x::setRxBandwidth(float rxBw) {
}
int16_t SX126x::setRxBoostedGainMode(bool rxbgm, bool persist) {
// read the current register value
uint8_t rxGain = 0;
int16_t state = readRegister(RADIOLIB_SX126X_REG_RX_GAIN, &rxGain, 1);
RADIOLIB_ASSERT(state);
// gain mode register value (SX1261/2 datasheet v2.1 section 9.6)
if(rxbgm) {
rxGain = RADIOLIB_SX126X_RX_GAIN_BOOSTED;
} else {
rxGain = RADIOLIB_SX126X_RX_GAIN_POWER_SAVING;
}
// update RX gain setting register
state = writeRegister(RADIOLIB_SX126X_REG_RX_GAIN, &rxGain, 1);
uint8_t rxGain = rxbgm ? RADIOLIB_SX126X_RX_GAIN_BOOSTED : RADIOLIB_SX126X_RX_GAIN_POWER_SAVING;
int16_t state = writeRegister(RADIOLIB_SX126X_REG_RX_GAIN, &rxGain, 1);
RADIOLIB_ASSERT(state);
// add Rx Gain register to retention memory if requested
if(persist) {
// values and registers below are specified in SX126x datasheet v2.1 section 9.6, just below table 9-3
uint8_t value0 = 0x01;
uint8_t value1 = 0x08;
uint8_t value2 = 0xAC;
state = writeRegister(RADIOLIB_SX126X_REG_RX_GAIN_RETENTION_0, &value0, 1);
RADIOLIB_ASSERT(state);
state = writeRegister(RADIOLIB_SX126X_REG_RX_GAIN_RETENTION_1, &value1, 1);
RADIOLIB_ASSERT(state);
state = writeRegister(RADIOLIB_SX126X_REG_RX_GAIN_RETENTION_2, &value2, 1);
RADIOLIB_ASSERT(state);
uint8_t data[] = { 0x01, (uint8_t)((RADIOLIB_SX126X_REG_RX_GAIN >> 8) & 0xFF), (uint8_t)(RADIOLIB_SX126X_REG_RX_GAIN & 0xFF) };
state = writeRegister(RADIOLIB_SX126X_REG_RX_GAIN_RETENTION_0, data, 3);
}
return(state);
@@ -1132,7 +1164,8 @@ int16_t SX126x::setRxBoostedGainMode(bool rxbgm, bool persist) {
int16_t SX126x::setDataShaping(uint8_t sh) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
uint8_t modem = getPacketType();
if((modem != RADIOLIB_SX126X_PACKET_TYPE_GFSK) && (modem != RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS)) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
@@ -1176,7 +1209,7 @@ int16_t SX126x::setSyncWord(uint8_t* syncWord, size_t len) {
// update packet parameters
this->syncWordLength = len * 8;
state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
return(state);
@@ -1186,6 +1219,14 @@ int16_t SX126x::setSyncWord(uint8_t* syncWord, size_t len) {
return(RADIOLIB_ERR_INVALID_SYNC_WORD);
}
return(setSyncWord(syncWord[0]));
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
// with length set to 4 and LR-FHSS modem active, assume it is the LR-FHSS sync word
if(len != sizeof(uint32_t)) {
return(RADIOLIB_ERR_INVALID_SYNC_WORD);
}
memcpy(this->lrFhssSyncWord, syncWord, sizeof(uint32_t));
}
return(RADIOLIB_ERR_WRONG_MODEM);
@@ -1210,7 +1251,7 @@ int16_t SX126x::setSyncBits(uint8_t *syncWord, uint8_t bitsLen) {
return(setSyncWord(syncWord, bytesLen));
}
int16_t SX126x::setNodeAddress(uint8_t nodeAddr) {
int16_t SX126x::setNodeAddress(uint8_t addr) {
// check active modem
if(getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
return(RADIOLIB_ERR_WRONG_MODEM);
@@ -1218,11 +1259,12 @@ int16_t SX126x::setNodeAddress(uint8_t nodeAddr) {
// enable address filtering (node only)
this->addrComp = RADIOLIB_SX126X_GFSK_ADDRESS_FILT_NODE;
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
RADIOLIB_ASSERT(state);
// set node address
state = writeRegister(RADIOLIB_SX126X_REG_NODE_ADDRESS, &nodeAddr, 1);
this->nodeAddr = addr;
state = writeRegister(RADIOLIB_SX126X_REG_NODE_ADDRESS, &addr, 1);
return(state);
}
@@ -1235,7 +1277,7 @@ int16_t SX126x::setBroadcastAddress(uint8_t broadAddr) {
// enable address filtering (node and broadcast)
this->addrComp = RADIOLIB_SX126X_GFSK_ADDRESS_FILT_NODE_BROADCAST;
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
RADIOLIB_ASSERT(state);
// set broadcast address
@@ -1252,7 +1294,7 @@ int16_t SX126x::disableAddressFiltering() {
// disable address filtering
this->addrComp = RADIOLIB_SX126X_GFSK_ADDRESS_FILT_OFF;
return(setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening));
return(setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening));
}
int16_t SX126x::setCRC(uint8_t len, uint16_t initial, uint16_t polynomial, bool inverted) {
@@ -1283,7 +1325,7 @@ int16_t SX126x::setCRC(uint8_t len, uint16_t initial, uint16_t polynomial, bool
return(RADIOLIB_ERR_INVALID_CRC_CONFIGURATION);
}
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
RADIOLIB_ASSERT(state);
// write initial CRC value
@@ -1325,7 +1367,7 @@ int16_t SX126x::setWhitening(bool enabled, uint16_t initial) {
// disable whitening
this->whitening = RADIOLIB_SX126X_GFSK_WHITENING_OFF;
state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
RADIOLIB_ASSERT(state);
} else {
@@ -1345,7 +1387,7 @@ int16_t SX126x::setWhitening(bool enabled, uint16_t initial) {
state = writeRegister(RADIOLIB_SX126X_REG_WHITENING_INITIAL_MSB, data, 2);
RADIOLIB_ASSERT(state);
state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, this->packetType);
RADIOLIB_ASSERT(state);
}
return(state);
@@ -1367,9 +1409,9 @@ float SX126x::getRSSI(bool packet) {
return(-1.0 * rssiPkt/2.0);
} else {
// get instantaneous RSSI value
uint8_t data[3] = {0, 0, 0}; // RssiInst, Status, RFU
this->mod->SPIreadStream(RADIOLIB_SX126X_CMD_GET_RSSI_INST, data, 3);
return((float)data[0] / (-2.0));
uint8_t rssiRaw = 0;
this->mod->SPIreadStream(RADIOLIB_SX126X_CMD_GET_RSSI_INST, &rssiRaw, 1);
return((float)rssiRaw / (-2.0));
}
}
@@ -1453,7 +1495,8 @@ int16_t SX126x::variablePacketLengthMode(uint8_t maxLen) {
RadioLibTime_t SX126x::getTimeOnAir(size_t len) {
// everything is in microseconds to allow integer arithmetic
// some constants have .25, these are multiplied by 4, and have _x4 postfix to indicate that fact
if(getPacketType() == RADIOLIB_SX126X_PACKET_TYPE_LORA) {
uint8_t modem = getPacketType();
if(modem == RADIOLIB_SX126X_PACKET_TYPE_LORA) {
uint32_t symbolLength_us = ((uint32_t)(1000 * 10) << this->spreadingFactor) / (this->bandwidthKhz * 10) ;
uint8_t sfCoeff1_x4 = 17; // (4.25 * 4)
uint8_t sfCoeff2 = 8;
@@ -1480,9 +1523,44 @@ RadioLibTime_t SX126x::getTimeOnAir(size_t len) {
uint32_t nSymbol_x4 = (this->preambleLengthLoRa + 8) * 4 + sfCoeff1_x4 + nPreCodedSymbols * (this->codingRate + 4) * 4;
return((symbolLength_us * nSymbol_x4) / 4);
} else {
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_GFSK) {
return(((uint32_t)len * 8 * this->bitRate) / (RADIOLIB_SX126X_CRYSTAL_FREQ * 32));
} else if(modem == RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS) {
// calculate the number of bits based on coding rate
uint16_t N_bits;
switch(this->lrFhssCr) {
case RADIOLIB_SX126X_LR_FHSS_CR_5_6:
N_bits = ((len * 6) + 4) / 5; // this is from the official LR11xx driver, but why the extra +4?
break;
case RADIOLIB_SX126X_LR_FHSS_CR_2_3:
N_bits = (len * 3) / 2;
break;
case RADIOLIB_SX126X_LR_FHSS_CR_1_2:
N_bits = len * 2;
break;
case RADIOLIB_SX126X_LR_FHSS_CR_1_3:
N_bits = len * 3;
break;
default:
return(RADIOLIB_ERR_INVALID_CODING_RATE);
}
// calculate number of bits when accounting for unaligned last block
uint16_t N_payBits = (N_bits / RADIOLIB_SX126X_LR_FHSS_FRAG_BITS) * RADIOLIB_SX126X_LR_FHSS_BLOCK_BITS;
uint16_t N_lastBlockBits = N_bits % RADIOLIB_SX126X_LR_FHSS_FRAG_BITS;
if(N_lastBlockBits) {
N_payBits += N_lastBlockBits + 2;
}
// add header bits
uint16_t N_totalBits = (RADIOLIB_SX126X_LR_FHSS_HEADER_BITS * this->lrFhssHdrCount) + N_payBits;
return(((uint32_t)N_totalBits * 8 * 1000000UL) / 488.28215f);
}
return(RADIOLIB_ERR_UNKNOWN);
}
RadioLibTime_t SX126x::calculateRxTimeout(RadioLibTime_t timeoutUs) {
@@ -1598,6 +1676,25 @@ int16_t SX126x::invertIQ(bool enable) {
return(setPacketParams(this->preambleLengthLoRa, this->crcTypeLoRa, this->implicitLen, this->headerType, this->invertIQEnabled));
}
int16_t SX126x::getModem(ModemType_t* modem) {
RADIOLIB_ASSERT_PTR(modem);
uint8_t packetType = getPacketType();
switch(packetType) {
case(RADIOLIB_SX126X_PACKET_TYPE_LORA):
*modem = ModemType_t::LoRa;
return(RADIOLIB_ERR_NONE);
case(RADIOLIB_SX126X_PACKET_TYPE_GFSK):
*modem = ModemType_t::FSK;
return(RADIOLIB_ERR_NONE);
case(RADIOLIB_SX126X_PACKET_TYPE_LR_FHSS):
*modem = ModemType_t::LRFHSS;
return(RADIOLIB_ERR_NONE);
}
return(RADIOLIB_ERR_WRONG_MODEM);
}
#if !RADIOLIB_EXCLUDE_DIRECT_RECEIVE
void SX126x::setDirectAction(void (*func)(void)) {
setDio1Action(func);
@@ -1866,6 +1963,43 @@ int16_t SX126x::setRfFrequency(uint32_t frf) {
return(this->mod->SPIwriteStream(RADIOLIB_SX126X_CMD_SET_RF_FREQUENCY, data, 4));
}
int16_t SX126x::calibrateImage(float freq) {
uint8_t data[2] = { 0, 0 };
// try to match the frequency ranges
int freqBand = (int)freq;
if((freqBand >= 902) && (freqBand <= 928)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_902_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_902_MHZ_2;
} else if((freqBand >= 863) && (freqBand <= 870)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_863_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_863_MHZ_2;
} else if((freqBand >= 779) && (freqBand <= 787)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_779_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_779_MHZ_2;
} else if((freqBand >= 470) && (freqBand <= 510)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_470_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_470_MHZ_2;
} else if((freqBand >= 430) && (freqBand <= 440)) {
data[0] = RADIOLIB_SX126X_CAL_IMG_430_MHZ_1;
data[1] = RADIOLIB_SX126X_CAL_IMG_430_MHZ_2;
}
int16_t state;
if(data[0]) {
// matched with predefined ranges, do the calibration
state = SX126x::calibrateImage(data);
} else {
// if nothing matched, try custom calibration - the may or may not work
RADIOLIB_DEBUG_BASIC_PRINTLN("Failed to match predefined frequency range, trying custom");
state = SX126x::calibrateImageRejection(freq - 4.0f, freq + 4.0f);
}
return(state);
}
int16_t SX126x::calibrateImageRejection(float freqMin, float freqMax) {
// calculate the calibration coefficients and calibrate image
uint8_t data[] = { (uint8_t)floor((freqMin - 1.0f) / 4.0f), (uint8_t)ceil((freqMax + 1.0f) / 4.0f) };
@@ -1915,7 +2049,7 @@ int16_t SX126x::setPacketMode(uint8_t mode, uint8_t len) {
}
// set requested packet mode
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, mode, len);
int16_t state = setPacketParamsFSK(this->preambleLengthFSK, this->preambleDetLength, this->crcTypeFSK, this->syncWordLength, this->addrComp, this->whitening, mode, len);
RADIOLIB_ASSERT(state);
// update cached value
@@ -1972,7 +2106,7 @@ int16_t SX126x::setPacketParams(uint16_t preambleLen, uint8_t crcType, uint8_t p
return(this->mod->SPIwriteStream(RADIOLIB_SX126X_CMD_SET_PACKET_PARAMS, data, 6));
}
int16_t SX126x::setPacketParamsFSK(uint16_t preambleLen, uint8_t crcType, uint8_t syncWordLen, uint8_t addrCmp, uint8_t whiten, uint8_t packType, uint8_t payloadLen, uint8_t preambleDetectorLen) {
int16_t SX126x::setPacketParamsFSK(uint16_t preambleLen, uint8_t preambleDetectorLen, uint8_t crcType, uint8_t syncWordLen, uint8_t addrCmp, uint8_t whiten, uint8_t packType, uint8_t payloadLen) {
uint8_t data[9] = {(uint8_t)((preambleLen >> 8) & 0xFF), (uint8_t)(preambleLen & 0xFF),
preambleDetectorLen, syncWordLen, addrCmp,
packType, payloadLen, crcType, whiten};
@@ -2015,7 +2149,8 @@ int16_t SX126x::clearDeviceErrors() {
int16_t SX126x::setFrequencyRaw(float freq) {
// calculate raw value
uint32_t frf = (freq * (uint32_t(1) << RADIOLIB_SX126X_DIV_EXPONENT)) / RADIOLIB_SX126X_CRYSTAL_FREQ;
this->freqMHz = freq;
uint32_t frf = (this->freqMHz * (uint32_t(1) << RADIOLIB_SX126X_DIV_EXPONENT)) / RADIOLIB_SX126X_CRYSTAL_FREQ;
return(setRfFrequency(frf));
}
@@ -2103,6 +2238,55 @@ Module* SX126x::getMod() {
return(this->mod);
}
int16_t SX126x::modSetup(float tcxoVoltage, bool useRegulatorLDO, uint8_t modem) {
// set module properties
this->mod->init();
this->mod->hal->pinMode(this->mod->getIrq(), this->mod->hal->GpioModeInput);
this->mod->hal->pinMode(this->mod->getGpio(), this->mod->hal->GpioModeInput);
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_ADDR] = Module::BITS_16;
this->mod->spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_CMD] = Module::BITS_8;
this->mod->spiConfig.statusPos = 1;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_READ] = RADIOLIB_SX126X_CMD_READ_REGISTER;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_WRITE] = RADIOLIB_SX126X_CMD_WRITE_REGISTER;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_NOP] = RADIOLIB_SX126X_CMD_NOP;
this->mod->spiConfig.cmds[RADIOLIB_MODULE_SPI_COMMAND_STATUS] = RADIOLIB_SX126X_CMD_GET_STATUS;
this->mod->spiConfig.stream = true;
this->mod->spiConfig.parseStatusCb = SPIparseStatus;
// try to find the SX126x chip
if(!SX126x::findChip(this->chipType)) {
RADIOLIB_DEBUG_BASIC_PRINTLN("No SX126x found!");
this->mod->term();
return(RADIOLIB_ERR_CHIP_NOT_FOUND);
}
RADIOLIB_DEBUG_BASIC_PRINTLN("M\tSX126x");
// reset the module and verify startup
int16_t state = reset();
RADIOLIB_ASSERT(state);
// set mode to standby
state = standby();
RADIOLIB_ASSERT(state);
// set TCXO control, if requested
if(!this->XTAL && tcxoVoltage > 0.0) {
state = setTCXO(tcxoVoltage);
RADIOLIB_ASSERT(state);
}
// configure settings not accessible by API
state = config(modem);
RADIOLIB_ASSERT(state);
if (useRegulatorLDO) {
state = setRegulatorLDO();
} else {
state = setRegulatorDCDC();
}
return(state);
}
int16_t SX126x::config(uint8_t modem) {
// reset buffer base address
int16_t state = setBufferBaseAddress();
+98 -4
View File
@@ -8,6 +8,8 @@
#include "../../Module.h"
#include "../../protocols/PhysicalLayer/PhysicalLayer.h"
#include "../../utils/FEC.h"
#include "../../utils/CRC.h"
// SX126X physical layer properties
#define RADIOLIB_SX126X_FREQUENCY_STEP_SIZE 0.9536743164
@@ -199,6 +201,7 @@
#define RADIOLIB_SX126X_CAL_IMG_863_MHZ_2 0xDB
#define RADIOLIB_SX126X_CAL_IMG_902_MHZ_1 0xE1
#define RADIOLIB_SX126X_CAL_IMG_902_MHZ_2 0xE9
#define RADIOLIB_SX126X_CAL_IMG_FREQ_TRIG_MHZ (20.0)
//RADIOLIB_SX126X_CMD_SET_PA_CONFIG
#define RADIOLIB_SX126X_PA_CONFIG_HP_MAX 0x07
@@ -434,6 +437,36 @@
// size of the spectral scan result
#define RADIOLIB_SX126X_SPECTRAL_SCAN_RES_SIZE (33)
// LR-FHSS configuration
#define RADIOLIB_SX126X_LR_FHSS_CR_5_6 (0x00UL << 0) // 7 0 LR FHSS coding rate: 5/6
#define RADIOLIB_SX126X_LR_FHSS_CR_2_3 (0x01UL << 0) // 7 0 2/3
#define RADIOLIB_SX126X_LR_FHSS_CR_1_2 (0x02UL << 0) // 7 0 1/2
#define RADIOLIB_SX126X_LR_FHSS_CR_1_3 (0x03UL << 0) // 7 0 1/3
#define RADIOLIB_SX126X_LR_FHSS_MOD_TYPE_GMSK (0x00UL << 0) // 7 0 LR FHSS modulation: GMSK
#define RADIOLIB_SX126X_LR_FHSS_GRID_STEP_FCC (0x00UL << 0) // 7 0 LR FHSS step size: 25.390625 kHz (FCC)
#define RADIOLIB_SX126X_LR_FHSS_GRID_STEP_NON_FCC (0x01UL << 0) // 7 0 3.90625 kHz (non-FCC)
#define RADIOLIB_SX126X_LR_FHSS_HOPPING_DISABLED (0x00UL << 0) // 7 0 LR FHSS hopping: disabled
#define RADIOLIB_SX126X_LR_FHSS_HOPPING_ENABLED (0x01UL << 0) // 7 0 enabled
#define RADIOLIB_SX126X_LR_FHSS_BW_39_06 (0x00UL << 0) // 7 0 LR FHSS bandwidth: 39.06 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_85_94 (0x01UL << 0) // 7 0 85.94 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_136_72 (0x02UL << 0) // 7 0 136.72 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_183_59 (0x03UL << 0) // 7 0 183.59 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_335_94 (0x04UL << 0) // 7 0 335.94 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_386_72 (0x05UL << 0) // 7 0 386.72 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_722_66 (0x06UL << 0) // 7 0 722.66 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_773_44 (0x07UL << 0) // 7 0 773.44 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_1523_4 (0x08UL << 0) // 7 0 1523.4 kHz
#define RADIOLIB_SX126X_LR_FHSS_BW_1574_2 (0x09UL << 0) // 7 0 1574.2 kHz
// LR-FHSS packet lengths
#define RADIOLIB_SX126X_LR_FHSS_MAX_ENC_SIZE (608)
#define RADIOLIB_SX126X_LR_FHSS_HEADER_BITS (114)
#define RADIOLIB_SX126X_LR_FHSS_HDR_BYTES (10)
#define RADIOLIB_SX126X_LR_FHSS_SYNC_WORD_BYTES (4)
#define RADIOLIB_SX126X_LR_FHSS_FRAG_BITS (48)
#define RADIOLIB_SX126X_LR_FHSS_BLOCK_PREAMBLE_BITS (2)
#define RADIOLIB_SX126X_LR_FHSS_BLOCK_BITS (RADIOLIB_SX126X_LR_FHSS_FRAG_BITS + RADIOLIB_SX126X_LR_FHSS_BLOCK_PREAMBLE_BITS)
/*!
\class SX126x
\brief Base class for %SX126x series. All derived classes for %SX126x (e.g. SX1262 or SX1268) inherit from this base class.
@@ -489,6 +522,27 @@ class SX126x: public PhysicalLayer {
*/
int16_t beginFSK(float br, float freqDev, float rxBw, uint16_t preambleLength, float tcxoVoltage, bool useRegulatorLDO = false);
/*!
\brief Initialization method for LR-FHSS modem. This modem only supports transmission!
\param bw LR-FHSS bandwidth, one of RADIOLIB_SX126X_LR_FHSS_BW_* values.
\param cr LR-FHSS coding rate, one of RADIOLIB_SX126X_LR_FHSS_CR_* values.
\param narrowGrid Whether to use narrow (3.9 kHz) or wide (25.39 kHz) grid spacing.
\param tcxoVoltage TCXO reference voltage to be set on DIO3. Defaults to 1.6 V, set to 0 to skip.
\param useRegulatorLDO Whether to use only LDO regulator (true) or DC-DC regulator (false). Defaults to false.
\returns \ref status_codes
*/
int16_t beginLRFHSS(uint8_t bw, uint8_t cr, bool narrowGrid, float tcxoVoltage, bool useRegulatorLDO = false);
/*!
\brief Sets LR-FHSS configuration.
\param bw LR-FHSS bandwidth, one of RADIOLIB_SX126X_LR_FHSS_BW_* values.
\param cr LR-FHSS coding rate, one of RADIOLIB_SX126X_LR_FHSS_CR_* values.
\param hdrCount Header packet count, 1 - 4. Defaults to 3.
\param hopSeqId 9-bit seed number for PRNG generation of the hopping sequence. Defaults to 0x13A.
\returns \ref status_codes
*/
int16_t setLrFhssConfig(uint8_t bw, uint8_t cr, uint8_t hdrCount = 3, uint16_t hopSeqId = 0x100);
/*!
\brief Reset method. Will reset the chip to the default state using RST pin.
\param verify Whether correct module startup should be verified. When set to true, RadioLib will attempt to verify the module has started correctly
@@ -830,6 +884,7 @@ class SX126x: public PhysicalLayer {
/*!
\brief Sets FSK sync word in the form of array of up to 8 bytes.
Can also set LR-FHSS sync word, but its length must be 4 bytes.
\param syncWord FSK sync word to be set.
\param len FSK sync word length in bytes.
\returns \ref status_codes
@@ -847,10 +902,10 @@ class SX126x: public PhysicalLayer {
/*!
\brief Sets node address. Calling this method will also enable address filtering for node address only.
\param nodeAddr Node address to be set.
\param addr Node address to be set.
\returns \ref status_codes
*/
int16_t setNodeAddress(uint8_t nodeAddr);
int16_t setNodeAddress(uint8_t addr);
/*!
\brief Sets broadcast address. Calling this method will also enable address
@@ -1069,6 +1124,13 @@ class SX126x: public PhysicalLayer {
*/
int16_t invertIQ(bool enable) override;
/*!
\brief Get modem currently in use by the radio.
\param modem Pointer to a variable to save the retrieved configuration into.
\returns \ref status_codes
*/
int16_t getModem(ModemType_t* modem) override;
#if !RADIOLIB_EXCLUDE_DIRECT_RECEIVE
/*!
\brief Set interrupt service routine function to call when data bit is received in direct mode.
@@ -1134,6 +1196,15 @@ class SX126x: public PhysicalLayer {
*/
int16_t setPaConfig(uint8_t paDutyCycle, uint8_t deviceSel, uint8_t hpMax = RADIOLIB_SX126X_PA_CONFIG_HP_MAX, uint8_t paLut = RADIOLIB_SX126X_PA_CONFIG_PA_LUT);
/*!
\brief Perform image rejection calibration for the specified frequency.
Will try to use Semtech-defined presets first, and if none of them matches,
custom iamge calibration will be attempted using calibrateImageRejection.
\param freq Frequency to perform the calibration for.
\returns \ref status_codes
*/
int16_t calibrateImage(float freq);
/*!
\brief Perform image rejection calibration for the specified frequency band.
WARNING: Use at your own risk! Setting incorrect values may lead to decreased performance
@@ -1172,7 +1243,7 @@ class SX126x: public PhysicalLayer {
int16_t setModulationParams(uint8_t sf, uint8_t bw, uint8_t cr, uint8_t ldro);
int16_t setModulationParamsFSK(uint32_t br, uint8_t sh, uint8_t rxBw, uint32_t freqDev);
int16_t setPacketParams(uint16_t preambleLen, uint8_t crcType, uint8_t payloadLen, uint8_t hdrType, uint8_t invertIQ);
int16_t setPacketParamsFSK(uint16_t preambleLen, uint8_t crcType, uint8_t syncWordLen, uint8_t addrCmp, uint8_t whiten, uint8_t packType = RADIOLIB_SX126X_GFSK_PACKET_VARIABLE, uint8_t payloadLen = 0xFF, uint8_t preambleDetectorLen = RADIOLIB_SX126X_GFSK_PREAMBLE_DETECT_16);
int16_t setPacketParamsFSK(uint16_t preambleLen, uint8_t preambleDetectorLen, uint8_t crcType, uint8_t syncWordLen, uint8_t addrCmp, uint8_t whiten, uint8_t packType = RADIOLIB_SX126X_GFSK_PACKET_VARIABLE, uint8_t payloadLen = 0xFF);
int16_t setBufferBaseAddress(uint8_t txBaseAddress = 0x00, uint8_t rxBaseAddress = 0x00);
int16_t setRegulatorMode(uint8_t mode);
uint8_t getStatus();
@@ -1185,6 +1256,7 @@ class SX126x: public PhysicalLayer {
#endif
const char* chipType = NULL;
uint8_t bandwidth = 0;
float freqMHz = 0;
// Allow subclasses to define different TX modes
uint8_t txMode = Module::MODE_TX;
@@ -1206,9 +1278,10 @@ class SX126x: public PhysicalLayer {
bool ldroAuto = true;
uint32_t bitRate = 0, frequencyDev = 0;
uint8_t rxBandwidth = 0, pulseShape = 0, crcTypeFSK = 0, syncWordLength = 0, addrComp = 0, whitening = 0, packetType = 0;
uint8_t preambleDetLength = 0, rxBandwidth = 0, pulseShape = 0, crcTypeFSK = 0, syncWordLength = 0, addrComp = 0, whitening = 0, packetType = 0;
uint16_t preambleLengthFSK = 0;
float rxBandwidthKhz = 0;
uint8_t nodeAddr = 0;
float dataRateMeasured = 0;
@@ -1218,6 +1291,22 @@ class SX126x: public PhysicalLayer {
size_t implicitLen = 0;
uint8_t invertIQEnabled = RADIOLIB_SX126X_LORA_IQ_STANDARD;
// LR-FHSS stuff - there's a lot of it because all the encoding happens in software
uint8_t lrFhssCr = RADIOLIB_SX126X_LR_FHSS_CR_2_3;
uint8_t lrFhssBw = RADIOLIB_SX126X_LR_FHSS_BW_722_66;
uint8_t lrFhssHdrCount = 3;
uint8_t lrFhssSyncWord[RADIOLIB_SX126X_LR_FHSS_SYNC_WORD_BYTES] = { 0x12, 0xAD, 0x10, 0x1B };
bool lrFhssGridNonFcc = false;
uint16_t lrFhssNgrid = 0;
uint16_t lrFhssLfsrState = 0;
uint16_t lrFhssPoly = 0;
uint16_t lrFhssSeed = 0;
uint16_t lrFhssHopSeqId = 0;
size_t lrFhssFrameBitsRem = 0;
size_t lrFhssFrameHopsRem = 0;
size_t lrFhssHopNum = 0;
int16_t modSetup(float tcxoVoltage, bool useRegulatorLDO, uint8_t modem);
int16_t config(uint8_t modem);
bool findChip(const char* verStr);
int16_t startReceiveCommon(uint32_t timeout = RADIOLIB_SX126X_RX_TIMEOUT_INF, RadioLibIrqFlags_t irqFlags = RADIOLIB_IRQ_RX_DEFAULT_FLAGS, RadioLibIrqFlags_t irqMask = RADIOLIB_IRQ_RX_DEFAULT_MASK);
@@ -1231,6 +1320,11 @@ class SX126x: public PhysicalLayer {
int16_t fixImplicitTimeout();
int16_t fixInvertedIQ(uint8_t iqConfig);
// LR-FHSS utilities
int16_t buildLRFHSSPacket(const uint8_t* in, size_t in_len, uint8_t* out, size_t* out_len, size_t* out_bits, size_t* out_hops);
int16_t resetLRFHSS();
uint16_t stepLRFHSS();
int16_t setLRFHSSHop(uint8_t index);
void regdump();
void effectEvalPre(uint8_t* buff, uint32_t start);
@@ -0,0 +1,393 @@
#include "SX126x.h"
#include <string.h>
#include <math.h>
#if !RADIOLIB_EXCLUDE_SX126X
/*
LR-FHSS implementation in this file is adapted from Setmech's LR-FHSS demo:
https://github.com/Lora-net/SWDM001/tree/master/lib/sx126x_driver
Its SX126x driver is distributed under the Clear BSD License,
and to comply with its terms, it is reproduced below.
The Clear BSD License
Copyright Semtech Corporation 2021. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the disclaimer
below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Semtech corporation nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// header interleaver
static const uint8_t LrFhssHeaderInterleaver[80] = {
0, 18, 36, 54, 72, 4, 22, 40,
58, 76, 8, 26, 44, 62, 12, 30,
48, 66, 16, 34, 52, 70, 1, 19,
37, 55, 73, 5, 23, 41, 59, 77,
9, 27, 45, 63, 13, 31, 49, 67,
17, 35, 53, 71, 2, 20, 38, 56,
74, 6, 24, 42, 60, 78, 10, 28,
46, 64, 14, 32, 50, 68, 3, 21,
39, 57, 75, 7, 25, 43, 61, 79,
11, 29, 47, 65, 15, 33, 51, 69,
};
int16_t SX126x::buildLRFHSSPacket(const uint8_t* in, size_t in_len, uint8_t* out, size_t* out_len, size_t* out_bits, size_t* out_hops) {
// perform payload whitening
uint8_t lfsr = 0xFF;
for(size_t i = 0; i < in_len; i++) {
uint8_t u = in[i] ^ lfsr;
// we really shouldn't reuse the caller's memory in this way ...
// but since this is a private method it should be at least controlled, if not safe
out[i] = ((u & 0x0F) << 4 ) | ((u & 0xF0) >> 4);
lfsr = (lfsr << 1) | (((lfsr & 0x80) >> 7) ^ (((lfsr & 0x20) >> 5) ^ (((lfsr & 0x10) >> 4) ^ ((lfsr & 0x08) >> 3))));
}
// calculate the CRC-16 over the whitened data, looks like something custom
RadioLibCRCInstance.size = 16;
RadioLibCRCInstance.poly = 0x755B;
RadioLibCRCInstance.init = 0xFFFF;
RadioLibCRCInstance.out = 0x0000;
uint16_t crc16 = RadioLibCRCInstance.checksum(out, in_len);
// add payload CRC
out[in_len] = (crc16 >> 8) & 0xFF;
out[in_len + 1] = crc16 & 0xFF;
out[in_len + 2] = 0;
// encode the payload with CRC using convolutional coding with 1/3 rate into a temporary buffer
uint8_t tmp[RADIOLIB_SX126X_LR_FHSS_MAX_ENC_SIZE] = { 0 };
size_t nb_bits = 0;
RadioLibConvCodeInstance.begin(3);
RadioLibConvCodeInstance.encode(out, 8 * (in_len + 2) + 6, tmp, &nb_bits);
memset(out, 0, RADIOLIB_SX126X_MAX_PACKET_LENGTH);
// for rates other than the 1/3 base, puncture the code
if(this->lrFhssCr != RADIOLIB_SX126X_LR_FHSS_CR_1_3) {
uint32_t matrix_index = 0;
uint8_t matrix[15] = { 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0 };
uint8_t matrix_len = 0;
switch(this->lrFhssCr) {
case RADIOLIB_SX126X_LR_FHSS_CR_5_6:
matrix_len = 15;
break;
case RADIOLIB_SX126X_LR_FHSS_CR_2_3:
matrix_len = 6;
break;
case RADIOLIB_SX126X_LR_FHSS_CR_1_2:
matrix_len = 3;
break;
}
uint32_t j = 0;
for(uint32_t i = 0; i < nb_bits; i++) {
if(matrix[matrix_index]) {
if(TEST_BIT_IN_ARRAY_LSB(tmp, i)) {
SET_BIT_IN_ARRAY_LSB(out, j);
} else {
CLEAR_BIT_IN_ARRAY_LSB(out, j);
}
j++;
}
if(++matrix_index == matrix_len) {
matrix_index = 0;
}
}
nb_bits = j;
memcpy(tmp, out, (nb_bits + 7) / 8);
}
// interleave the payload into output buffer
uint16_t step = 0;
while((size_t)(step * step) < nb_bits) {
// probably the silliest sqrt() I ever saw
step++;
}
const uint16_t step_v = step >> 1;
step <<= 1;
uint16_t pos = 0;
uint16_t st_idx = 0;
uint16_t st_idx_init = 0;
int16_t bits_left = nb_bits;
uint16_t out_row_index = RADIOLIB_SX126X_LR_FHSS_HEADER_BITS * this->lrFhssHdrCount;
while(bits_left > 0) {
int16_t in_row_width = bits_left;
if(in_row_width > RADIOLIB_SX126X_LR_FHSS_FRAG_BITS) {
in_row_width = RADIOLIB_SX126X_LR_FHSS_FRAG_BITS;
}
// guard bits
CLEAR_BIT_IN_ARRAY_LSB(out, out_row_index);
CLEAR_BIT_IN_ARRAY_LSB(out, out_row_index + 1);
for(int16_t j = 0; j < in_row_width; j++) {
// guard bit
if(TEST_BIT_IN_ARRAY_LSB(tmp, pos)) {
SET_BIT_IN_ARRAY_LSB(out, j + 2 + out_row_index);
} else {
CLEAR_BIT_IN_ARRAY_LSB(out, j + 2 + out_row_index);
}
pos += step;
if(pos >= nb_bits) {
st_idx += step_v;
if(st_idx >= step) {
st_idx_init++;
st_idx = st_idx_init;
}
pos = st_idx;
}
}
bits_left -= RADIOLIB_SX126X_LR_FHSS_FRAG_BITS;
out_row_index += 2 + in_row_width;
}
nb_bits = out_row_index - RADIOLIB_SX126X_LR_FHSS_HEADER_BITS * this->lrFhssHdrCount;
// build the header
uint8_t raw_header[RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2];
raw_header[0] = in_len;
raw_header[1] = (this->lrFhssCr << 3) | ((uint8_t)this->lrFhssGridNonFcc << 2) |
(RADIOLIB_SX126X_LR_FHSS_HOPPING_ENABLED << 1) | (this->lrFhssBw >> 3);
raw_header[2] = ((this->lrFhssBw & 0x07) << 5) | (this->lrFhssHopSeqId >> 4);
raw_header[3] = ((this->lrFhssHopSeqId & 0x000F) << 4);
// CRC-8 used seems to based on 8H2F, but without final XOR
RadioLibCRCInstance.size = 8;
RadioLibCRCInstance.poly = 0x2F;
RadioLibCRCInstance.init = 0xFF;
RadioLibCRCInstance.out = 0x00;
uint16_t header_offset = 0;
for(size_t i = 0; i < this->lrFhssHdrCount; i++) {
// insert index and calculate the header CRC
raw_header[3] = (raw_header[3] & ~0x0C) | ((this->lrFhssHdrCount - i - 1) << 2);
raw_header[4] = RadioLibCRCInstance.checksum(raw_header, (RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2 - 1));
// convolutional encode
uint8_t coded_header[RADIOLIB_SX126X_LR_FHSS_HDR_BYTES] = { 0 };
RadioLibConvCodeInstance.begin(2);
RadioLibConvCodeInstance.encode(raw_header, 8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2, coded_header);
// tail-biting seems to just do this twice ...?
RadioLibConvCodeInstance.encode(raw_header, 8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2, coded_header);
// clear guard bits
CLEAR_BIT_IN_ARRAY_LSB(out, header_offset);
CLEAR_BIT_IN_ARRAY_LSB(out, header_offset + 1);
// interleave the header directly to the physical payload buffer
for(size_t j = 0; j < (8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2); j++) {
if(TEST_BIT_IN_ARRAY_LSB(coded_header, LrFhssHeaderInterleaver[j])) {
SET_BIT_IN_ARRAY_LSB(out, header_offset + 2 + j);
} else {
CLEAR_BIT_IN_ARRAY_LSB(out, header_offset + 2 + j);
}
}
for(size_t j = 0; j < (8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2); j++) {
if(TEST_BIT_IN_ARRAY_LSB(coded_header, LrFhssHeaderInterleaver[(8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2) + j])) {
SET_BIT_IN_ARRAY_LSB(out, header_offset + 2 + (8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2) + (8*RADIOLIB_SX126X_LR_FHSS_SYNC_WORD_BYTES) + j);
} else {
CLEAR_BIT_IN_ARRAY_LSB(out, header_offset + 2 + (8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2) + (8*RADIOLIB_SX126X_LR_FHSS_SYNC_WORD_BYTES) + j);
}
}
// copy the sync word to the physical payload buffer
for(size_t j = 0; j < (8*RADIOLIB_SX126X_LR_FHSS_SYNC_WORD_BYTES); j++) {
if(TEST_BIT_IN_ARRAY_LSB(this->lrFhssSyncWord, j)) {
SET_BIT_IN_ARRAY_LSB(out, header_offset + 2 + (8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2) + j);
} else {
CLEAR_BIT_IN_ARRAY_LSB(out, header_offset + 2 + (8*RADIOLIB_SX126X_LR_FHSS_HDR_BYTES/2) + j);
}
}
header_offset += RADIOLIB_SX126X_LR_FHSS_HEADER_BITS;
}
// calculate the number of hops and total number of bits
uint16_t length_bits = (in_len + 2) * 8 + 6;
switch(this->lrFhssCr) {
case RADIOLIB_SX126X_LR_FHSS_CR_5_6:
length_bits = ( ( length_bits * 6 ) + 4 ) / 5;
break;
case RADIOLIB_SX126X_LR_FHSS_CR_2_3:
length_bits = length_bits * 3 / 2;
break;
case RADIOLIB_SX126X_LR_FHSS_CR_1_2:
length_bits = length_bits * 2;
break;
case RADIOLIB_SX126X_LR_FHSS_CR_1_3:
length_bits = length_bits * 3;
break;
}
*out_hops = (length_bits + 47) / 48 + this->lrFhssHdrCount;
// calculate total number of payload bits, after breaking into blocks
uint16_t payload_bits = length_bits / RADIOLIB_SX126X_LR_FHSS_FRAG_BITS * RADIOLIB_SX126X_LR_FHSS_BLOCK_BITS;
uint16_t last_block_bits = length_bits % RADIOLIB_SX126X_LR_FHSS_FRAG_BITS;
if(last_block_bits > 0) {
// add the 2 guard bits for the last block + the actual remaining payload bits
payload_bits += last_block_bits + 2;
}
*out_bits = (RADIOLIB_SX126X_LR_FHSS_HEADER_BITS * this->lrFhssHdrCount) + payload_bits;
*out_len = (*out_bits + 7) / 8;
return(RADIOLIB_ERR_NONE);
}
int16_t SX126x::resetLRFHSS() {
// initialize hopping configuration
const uint16_t numChan[] = { 80, 176, 280, 376, 688, 792, 1480, 1584, 3120, 3224 };
// LFSR polynomials for different ranges of lrFhssNgrid
const uint8_t lfsrPoly1[] = { 33, 45, 48, 51, 54, 57 };
const uint8_t lfsrPoly2[] = { 65, 68, 71, 72 };
const uint8_t lfsrPoly3[] = { 142, 149 };
uint32_t nb_channel_in_grid = this->lrFhssGridNonFcc ? 8 : 52;
this->lrFhssNgrid = numChan[this->lrFhssBw] / nb_channel_in_grid;
this->lrFhssLfsrState = 6;
switch(this->lrFhssNgrid) {
case 10:
case 22:
case 28:
case 30:
case 35:
case 47:
this->lrFhssPoly = lfsrPoly1[this->lrFhssHopSeqId >> 6];
this->lrFhssSeed = this->lrFhssHopSeqId & 0x3F;
if(this->lrFhssHopSeqId >= 384) {
return(RADIOLIB_ERR_INVALID_DATA_SHAPING);
}
break;
case 60:
case 62:
this->lrFhssLfsrState = 56;
this->lrFhssPoly = lfsrPoly1[this->lrFhssHopSeqId >> 6];
this->lrFhssSeed = this->lrFhssHopSeqId & 0x3F;
if(this->lrFhssHopSeqId >= 384) {
return(RADIOLIB_ERR_INVALID_DATA_SHAPING);
}
break;
case 86:
case 99:
this->lrFhssPoly = lfsrPoly2[this->lrFhssHopSeqId >> 7];
this->lrFhssSeed = this->lrFhssHopSeqId & 0x7F;
break;
case 185:
case 198:
this->lrFhssPoly = lfsrPoly3[this->lrFhssHopSeqId >> 8];
this->lrFhssSeed = this->lrFhssHopSeqId & 0xFF;
break;
case 390:
case 403:
this->lrFhssPoly = 264;
this->lrFhssSeed = this->lrFhssHopSeqId;
break;
default:
return(RADIOLIB_ERR_INVALID_DATA_SHAPING);
}
return(RADIOLIB_ERR_NONE);
}
uint16_t SX126x::stepLRFHSS() {
uint16_t hop;
do {
uint16_t lsb = this->lrFhssLfsrState & 1;
this->lrFhssLfsrState >>= 1;
if(lsb) {
this->lrFhssLfsrState ^= this->lrFhssPoly;
}
hop = this->lrFhssSeed;
if(hop != this->lrFhssLfsrState) {
hop ^= this->lrFhssLfsrState;
}
} while(hop > this->lrFhssNgrid);
return(hop);
}
int16_t SX126x::setLRFHSSHop(uint8_t index) {
if(!this->lrFhssFrameHopsRem) {
return(RADIOLIB_ERR_NONE);
}
uint16_t hop = stepLRFHSS();
int16_t freq_table = hop - 1;
if(freq_table >= (int16_t)(this->lrFhssNgrid >> 1)) {
freq_table -= this->lrFhssNgrid;
}
uint32_t nb_channel_in_grid = this->lrFhssGridNonFcc ? 8 : 52;
uint32_t grid_offset = (1 + (this->lrFhssNgrid % 2)) * (nb_channel_in_grid / 2);
uint32_t grid_in_pll_steps = this->lrFhssGridNonFcc ? 4096 : 26624;
uint32_t frf = (this->freqMHz * (uint32_t(1) << RADIOLIB_SX126X_DIV_EXPONENT)) / RADIOLIB_SX126X_CRYSTAL_FREQ;
uint32_t freq_raw = frf - freq_table * grid_in_pll_steps - grid_offset * 512;
if((this->lrFhssHopNum < this->lrFhssHdrCount)) {
if((((this->lrFhssHdrCount - this->lrFhssHopNum) % 2) == 0)) {
freq_raw += 256;
}
}
uint8_t frq[4] = { (uint8_t)((freq_raw >> 24) & 0xFF), (uint8_t)((freq_raw >> 16) & 0xFF), (uint8_t)((freq_raw >> 8) & 0xFF), (uint8_t)(freq_raw & 0xFF) };
int16_t state = writeRegister(RADIOLIB_SX126X_REG_LR_FHSS_FREQX_0(index), frq, sizeof(freq_raw));
RADIOLIB_ASSERT(state);
// (LR_FHSS_HEADER_BITS + pulse_shape_compensation) symbols on first sync_word, LR_FHSS_HEADER_BITS on
// next sync_words, LR_FHSS_BLOCK_BITS on payload
uint16_t numSymbols = RADIOLIB_SX126X_LR_FHSS_BLOCK_BITS;
if(index == 0) {
numSymbols = RADIOLIB_SX126X_LR_FHSS_HEADER_BITS + 1; // the +1 is "pulse_shape_compensation", but it's constant in the demo
} else if(index < this->lrFhssHdrCount) {
numSymbols = RADIOLIB_SX126X_LR_FHSS_HEADER_BITS;
} else if(this->lrFhssFrameBitsRem < RADIOLIB_SX126X_LR_FHSS_BLOCK_BITS) {
numSymbols = this->lrFhssFrameBitsRem;
}
// write hop length in symbols
uint8_t sym[2] = { (uint8_t)((numSymbols >> 8) & 0xFF), (uint8_t)(numSymbols & 0xFF) };
state = writeRegister(RADIOLIB_SX126X_REG_LR_FHSS_NUM_SYMBOLS_FREQX_MSB(index), sym, sizeof(uint16_t));
RADIOLIB_ASSERT(state);
this->lrFhssFrameBitsRem -= numSymbols;
this->lrFhssFrameHopsRem--;
this->lrFhssHopNum++;
return(RADIOLIB_ERR_NONE);
}
#endif
@@ -585,4 +585,17 @@ void SX1272::errataFix(bool rx) {
mod->SPIsetRegValue(0x31, 0b10000000, 7, 7);
}
int16_t SX1272::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+8
View File
@@ -301,6 +301,14 @@ class SX1272: public SX127x {
\returns \ref status_codes
*/
int16_t explicitHeader();
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK or LoRa.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
protected:
@@ -115,4 +115,17 @@ int16_t SX1273::checkDataRate(DataRate_t dr) {
return(state);
}
int16_t SX1273::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+8
View File
@@ -62,6 +62,14 @@ class SX1273: public SX1272 {
\returns \ref status_codes
*/
int16_t checkDataRate(DataRate_t dr) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK or LoRa.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
@@ -79,4 +79,17 @@ int16_t SX1276::setFrequency(float freq) {
return(state);
}
int16_t SX1276::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+8
View File
@@ -62,6 +62,14 @@ class SX1276: public SX1278 {
\returns \ref status_codes
*/
int16_t setFrequency(float freq) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK or LoRa.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
@@ -157,4 +157,17 @@ int16_t SX1277::checkDataRate(DataRate_t dr) {
return(state);
}
int16_t SX1277::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+8
View File
@@ -83,6 +83,14 @@ class SX1277: public SX1278 {
\returns \ref status_codes
*/
int16_t checkDataRate(DataRate_t dr) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK or LoRa.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
@@ -705,4 +705,17 @@ void SX1278::errataFix(bool rx) {
mod->SPIsetRegValue(0x30, fixedRegs[2]);
}
int16_t SX1278::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+8
View File
@@ -313,6 +313,14 @@ class SX1278: public SX127x {
\returns \ref status_codes
*/
int16_t explicitHeader();
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK or LoRa.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
protected:
@@ -79,4 +79,17 @@ int16_t SX1279::setFrequency(float freq) {
return(state);
}
int16_t SX1279::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginFSK());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
#endif
+8
View File
@@ -62,6 +62,14 @@ class SX1279: public SX1278 {
\returns \ref status_codes
*/
int16_t setFrequency(float freq) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK or LoRa.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
#if !RADIOLIB_GODMODE
private:
+124 -46
View File
@@ -605,16 +605,18 @@ int16_t SX127x::startTransmit(const uint8_t* data, size_t len, uint8_t addr) {
this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO0_PACK_PACKET_SENT, 7, 6);
}
// set packet length
if (this->packetLengthConfig == RADIOLIB_SX127X_PACKET_VARIABLE) {
this->mod->SPIwriteRegister(RADIOLIB_SX127X_REG_FIFO, len);
}
// check address filtering
// set packet length - increased by 1 when address filter is enabled
uint8_t filter = this->mod->SPIgetRegValue(RADIOLIB_SX127X_REG_PACKET_CONFIG_1, 2, 1);
if((filter == RADIOLIB_SX127X_ADDRESS_FILTERING_NODE) || (filter == RADIOLIB_SX127X_ADDRESS_FILTERING_NODE_BROADCAST)) {
this->mod->SPIwriteRegister(RADIOLIB_SX127X_REG_FIFO, addr);
if(this->packetLengthConfig == RADIOLIB_SX127X_PACKET_VARIABLE) {
if((filter == RADIOLIB_SX127X_ADDRESS_FILTERING_NODE) || (filter == RADIOLIB_SX127X_ADDRESS_FILTERING_NODE_BROADCAST)) {
this->mod->SPIwriteRegister(RADIOLIB_SX127X_REG_FIFO, len + 1);
this->mod->SPIwriteRegister(RADIOLIB_SX127X_REG_FIFO, addr);
} else {
this->mod->SPIwriteRegister(RADIOLIB_SX127X_REG_FIFO, len);
}
}
}
// write packet to FIFO
@@ -672,12 +674,11 @@ int16_t SX127x::readData(uint8_t* data, size_t len) {
// CRC is disabled according to packet header and enabled according to user
// most likely damaged packet header
state = RADIOLIB_ERR_LORA_HEADER_DAMAGED;
} else {
// set FIFO read pointer to the start of the current packet
state = this->mod->SPIgetRegValue(RADIOLIB_SX127X_REG_FIFO_RX_CURRENT_ADDR);
if (state >= 0) {
state = this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_FIFO_ADDR_PTR, state);
}
}
// set FIFO read pointer to the start of the current packet
int16_t addr = this->mod->SPIgetRegValue(RADIOLIB_SX127X_REG_FIFO_RX_CURRENT_ADDR);
if (addr >= 0) {
this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_FIFO_ADDR_PTR, addr);
}
} else if(modem == RADIOLIB_SX127X_FSK_OOK) {
@@ -1315,43 +1316,104 @@ uint32_t SX127x::getIrqFlags() {
int16_t SX127x::setIrqFlags(uint32_t irq) {
// this is a bit convoluted, but unfortunately SX127x IRQ flags are not used to enable/disable that IRQ ...
// in addition, the configuration is often mutually exclusive, so we iterate over the set bits in a loop
uint8_t usedPinFlags = 0;
bool conflict = false;
int16_t modem = getActiveModem();
if(modem == RADIOLIB_SX127X_LORA) {
switch(irq) {
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_TX_DONE):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO0_PACK_PACKET_SENT, 7, 6));
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_RX_DONE):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO0_LORA_RX_DONE, 7, 6));
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_VALID_HEADER):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO3_LORA_VALID_HEADER, 1, 0));
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_PAYLOAD_CRC_ERROR):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO3_LORA_PAYLOAD_CRC_ERROR, 1, 0));
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_CAD_DONE):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO0_LORA_CAD_DONE, 7, 6));
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_CAD_DETECTED):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO1_LORA_CAD_DETECTED, 5, 4));
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_RX_TIMEOUT):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO1_LORA_RX_TIMEOUT, 5, 4));
int16_t state;
for(uint8_t i = 0; i <= 31; i++) {
// check if the bit is set
uint32_t irqBit = irq & (1UL << i);
if(!irqBit) {
continue;
}
return(RADIOLIB_ERR_UNSUPPORTED);
} else if(modem == RADIOLIB_SX127X_FSK_OOK) {
switch(irq) {
case(RADIOLIB_SX127X_FLAG_PACKET_SENT << 8):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO0_PACK_PACKET_SENT, 7, 6));
case(RADIOLIB_SX127X_FLAG_PAYLOAD_READY << 8):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO0_PACK_PAYLOAD_READY, 7, 6));
case(RADIOLIB_SX127X_FLAG_PREAMBLE_DETECT << 0):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_2, RADIOLIB_SX127X_DIO4_PACK_RSSI_PREAMBLE_DETECT, 7, 6));
case(RADIOLIB_SX127X_FLAG_SYNC_ADDRESS_MATCH << 0):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO2_PACK_SYNC_ADDRESS, 3, 2));
case(RADIOLIB_SX127X_FLAG_TIMEOUT << 0):
return(this->mod->SPIsetRegValue(RADIOLIB_SX127X_REG_DIO_MAPPING_1, RADIOLIB_SX127X_DIO2_PACK_TIMEOUT, 3, 2));
// if not, decode it
uint8_t dioNum = 0; // DIO pin number and register value to set (address and MSB/LSB can be inferred)
uint8_t regVal = 0;
if(modem == RADIOLIB_SX127X_LORA) {
switch(irqBit) {
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_TX_DONE):
dioNum = 0;
regVal = RADIOLIB_SX127X_DIO0_PACK_PACKET_SENT;
break;
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_RX_DONE):
dioNum = 0;
regVal = RADIOLIB_SX127X_DIO0_LORA_RX_DONE;
break;
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_VALID_HEADER):
dioNum = 3;
regVal = RADIOLIB_SX127X_DIO3_LORA_VALID_HEADER;
break;
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_PAYLOAD_CRC_ERROR):
dioNum = 3;
regVal = RADIOLIB_SX127X_DIO3_LORA_PAYLOAD_CRC_ERROR;
break;
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_CAD_DONE):
dioNum = 0;
regVal = RADIOLIB_SX127X_DIO0_LORA_CAD_DONE;
break;
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_CAD_DETECTED):
dioNum = 1;
regVal = RADIOLIB_SX127X_DIO1_LORA_CAD_DETECTED;
break;
case(RADIOLIB_SX127X_CLEAR_IRQ_FLAG_RX_TIMEOUT):
dioNum = 1;
regVal = RADIOLIB_SX127X_DIO1_LORA_RX_TIMEOUT;
break;
default:
return(RADIOLIB_ERR_UNSUPPORTED);
}
} else if(modem == RADIOLIB_SX127X_FSK_OOK) {
switch(irqBit) {
case(RADIOLIB_SX127X_FLAG_PACKET_SENT << 8):
dioNum = 0;
regVal = RADIOLIB_SX127X_DIO0_PACK_PACKET_SENT;
break;
case(RADIOLIB_SX127X_FLAG_PAYLOAD_READY << 8):
dioNum = 0;
regVal = RADIOLIB_SX127X_DIO0_PACK_PAYLOAD_READY;
break;
case(RADIOLIB_SX127X_FLAG_PREAMBLE_DETECT << 0):
dioNum = 4;
regVal = RADIOLIB_SX127X_DIO4_PACK_RSSI_PREAMBLE_DETECT;
break;
case(RADIOLIB_SX127X_FLAG_SYNC_ADDRESS_MATCH << 0):
dioNum = 2;
regVal = RADIOLIB_SX127X_DIO2_PACK_SYNC_ADDRESS;
break;
case(RADIOLIB_SX127X_FLAG_TIMEOUT << 0):
dioNum = 2;
regVal = RADIOLIB_SX127X_DIO2_PACK_TIMEOUT;
break;
default:
return(RADIOLIB_ERR_UNSUPPORTED);
}
}
return(RADIOLIB_ERR_UNSUPPORTED);
// check if this DIO pin has been set already
if(usedPinFlags & (1UL << dioNum)) {
// uh oh, this pin is used!
RADIOLIB_DEBUG_PRINTLN("Unable to set IRQ %04x on DIO%d due to conflict!", irqBit, (int)dioNum);
conflict = true;
continue;
}
// DIO pin is unused, set the flag and configure it
usedPinFlags |= (1UL << dioNum);
uint8_t addr = (dioNum > 3) ? RADIOLIB_SX127X_REG_DIO_MAPPING_2 : RADIOLIB_SX127X_REG_DIO_MAPPING_1;
uint8_t msb = 7 - 2*(dioNum % 4);
state = this->mod->SPIsetRegValue(addr, regVal, msb, msb - 1);
RADIOLIB_ASSERT(state);
}
return(RADIOLIB_ERR_UNSUPPORTED);
// if there was at least one conflict, this flag is set
if(conflict) {
return(RADIOLIB_ERR_INVALID_IRQ);
}
return(state);
}
int16_t SX127x::clearIrqFlags(uint32_t irq) {
@@ -1692,6 +1754,22 @@ int16_t SX127x::invertIQ(bool enable) {
return(state);
}
int16_t SX127x::getModem(ModemType_t* modem) {
RADIOLIB_ASSERT_PTR(modem);
int16_t packetType = getActiveModem();
switch(packetType) {
case(RADIOLIB_SX127X_LORA):
*modem = ModemType_t::LoRa;
return(RADIOLIB_ERR_NONE);
case(RADIOLIB_SX127X_FSK_OOK):
*modem = ModemType_t::FSK;
return(RADIOLIB_ERR_NONE);
}
return(RADIOLIB_ERR_WRONG_MODEM);
}
#if !RADIOLIB_EXCLUDE_DIRECT_RECEIVE
void SX127x::setDirectAction(void (*func)(void)) {
setDio1Action(func, this->mod->hal->GpioInterruptRising);
+11
View File
@@ -1063,6 +1063,10 @@ class SX127x: public PhysicalLayer {
/*!
\brief Set interrupt on DIO1 to be sent on a specific IRQ bit (e.g. RxTimeout, CadDone).
NOTE: Unlike other modules that support IRQ abstraction (SX126x, LR11x0, etc.),
SX127x cannot configure multiple IRQs to signal using the same DIOx pin.
This method tries to configure IRQs in a "best effort" approach, and will skip conflicting flags.
RADIOLIB_ERR_INVALID_IRQ will be returned in this case.
\param irq Module-specific IRQ flags.
\returns \ref status_codes
*/
@@ -1145,6 +1149,13 @@ class SX127x: public PhysicalLayer {
*/
int16_t invertIQ(bool enable) override;
/*!
\brief Get modem currently in use by the radio.
\param modem Pointer to a variable to save the retrieved configuration into.
\returns \ref status_codes
*/
int16_t getModem(ModemType_t* modem) override;
#if !RADIOLIB_EXCLUDE_DIRECT_RECEIVE
/*!
\brief Set interrupt service routine function to call when data bit is received in direct mode.
+64 -6
View File
@@ -421,7 +421,7 @@ int16_t SX128x::receiveDirect() {
}
int16_t SX128x::scanChannel() {
ChannelScanConfig_t config = {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_SX128X_CAD_PARAM_DEFAULT,
.detPeak = 0,
@@ -432,7 +432,7 @@ int16_t SX128x::scanChannel() {
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->scanChannel(config));
return(this->scanChannel(cfg));
}
int16_t SX128x::scanChannel(const ChannelScanConfig_t &config) {
@@ -461,7 +461,9 @@ int16_t SX128x::sleep(bool retainConfig) {
if(!retainConfig) {
sleepConfig = RADIOLIB_SX128X_SLEEP_DATA_BUFFER_FLUSH | RADIOLIB_SX128X_SLEEP_DATA_RAM_FLUSH;
}
int16_t state = this->mod->SPIwriteStream(RADIOLIB_SX128X_CMD_SET_SLEEP, &sleepConfig, 1, false, false);
int16_t state = this->mod->SPIwriteStream(RADIOLIB_SX128X_CMD_SAVE_CONTEXT, 0, 1, false, false);
RADIOLIB_ASSERT(state);
state = this->mod->SPIwriteStream(RADIOLIB_SX128X_CMD_SET_SLEEP, &sleepConfig, 1, false, false);
// wait for SX128x to safely enter sleep mode
this->mod->hal->delay(1);
@@ -677,7 +679,7 @@ int16_t SX128x::clearIrqFlags(uint32_t irq) {
}
int16_t SX128x::startChannelScan() {
ChannelScanConfig_t config = {
ChannelScanConfig_t cfg = {
.cad = {
.symNum = RADIOLIB_SX128X_CAD_PARAM_DEFAULT,
.detPeak = 0,
@@ -688,7 +690,7 @@ int16_t SX128x::startChannelScan() {
.irqMask = RADIOLIB_IRQ_CAD_DEFAULT_MASK,
},
};
return(this->startChannelScan(config));
return(this->startChannelScan(cfg));
}
int16_t SX128x::startChannelScan(const ChannelScanConfig_t &config) {
@@ -854,6 +856,35 @@ int16_t SX128x::checkOutputPower(int8_t pwr, int8_t* clipped) {
return(RADIOLIB_ERR_NONE);
}
int16_t SX128x::setModem(ModemType_t modem) {
switch(modem) {
case(ModemType_t::LoRa): {
return(this->begin());
} break;
case(ModemType_t::FSK): {
return(this->beginGFSK());
} break;
default:
return(RADIOLIB_ERR_WRONG_MODEM);
}
}
int16_t SX128x::getModem(ModemType_t* modem) {
RADIOLIB_ASSERT_PTR(modem);
uint8_t packetType = getPacketType();
switch(packetType) {
case(RADIOLIB_SX128X_PACKET_TYPE_LORA):
*modem = ModemType_t::LoRa;
return(RADIOLIB_ERR_NONE);
case(RADIOLIB_SX128X_PACKET_TYPE_GFSK):
*modem = ModemType_t::FSK;
return(RADIOLIB_ERR_NONE);
}
return(RADIOLIB_ERR_WRONG_MODEM);
}
int16_t SX128x::setPreambleLength(uint32_t preambleLength) {
uint8_t modem = getPacketType();
if((modem == RADIOLIB_SX128X_PACKET_TYPE_LORA) || (modem == RADIOLIB_SX128X_PACKET_TYPE_RANGING)) {
@@ -870,7 +901,7 @@ int16_t SX128x::setPreambleLength(uint32_t preambleLength) {
uint8_t m = 1;
uint32_t len = 0;
for(; e <= 15; e++) {
for(; m <= 15; m++) {
for(m = 1; m <= 15; m++) {
len = m * (uint32_t(1) << e);
if(len >= preambleLength) {
break;
@@ -902,6 +933,22 @@ int16_t SX128x::setPreambleLength(uint32_t preambleLength) {
return(RADIOLIB_ERR_WRONG_MODEM);
}
int16_t SX128x::setDataRate(DataRate_t dr) {
// check active modem
uint8_t modem = getPacketType();
int16_t state = RADIOLIB_ERR_NONE;
if (modem == RADIOLIB_SX128X_PACKET_TYPE_LORA) {
state = this->setBandwidth(dr.lora.bandwidth);
RADIOLIB_ASSERT(state);
state = this->setSpreadingFactor(dr.lora.spreadingFactor);
RADIOLIB_ASSERT(state);
state = this->setCodingRate(dr.lora.codingRate);
} else {
return(RADIOLIB_ERR_WRONG_MODEM);
}
return(state);
}
int16_t SX128x::setBitRate(float br) {
// check active modem
uint8_t modem = getPacketType();
@@ -1253,6 +1300,17 @@ float SX128x::getRSSI() {
}
}
float SX128x::getRSSI(bool packet) {
if (!packet) {
// get instantaneous RSSI value
uint8_t data[3] = {0, 0, 0}; // RssiInst, Status, RFU
this->mod->SPIreadStream(RADIOLIB_SX128X_CMD_GET_RSSI_INST, data, 3);
return ((float)data[0] / (-2.0));
} else {
return this->getRSSI();
}
}
float SX128x::getSNR() {
// check active modem
uint8_t modem = getPacketType();
+30
View File
@@ -22,6 +22,7 @@
#define RADIOLIB_SX128X_CMD_READ_REGISTER 0x19
#define RADIOLIB_SX128X_CMD_WRITE_BUFFER 0x1A
#define RADIOLIB_SX128X_CMD_READ_BUFFER 0x1B
#define RADIOLIB_SX128X_CMD_SAVE_CONTEXT 0xD5
#define RADIOLIB_SX128X_CMD_SET_SLEEP 0x84
#define RADIOLIB_SX128X_CMD_SET_STANDBY 0x80
#define RADIOLIB_SX128X_CMD_SET_FS 0xC1
@@ -670,6 +671,21 @@ class SX128x: public PhysicalLayer {
\returns \ref status_codes
*/
int16_t checkOutputPower(int8_t pwr, int8_t* clipped) override;
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set - FSK, LoRa or LR-FHSS.
\returns \ref status_codes
*/
int16_t setModem(ModemType_t modem) override;
/*!
\brief Get modem currently in use by the radio.
\param modem Pointer to a variable to save the retrieved configuration into.
\returns \ref status_codes
*/
int16_t getModem(ModemType_t* modem) override;
/*!
\brief Sets preamble length for currently active modem. Allowed values range from 1 to 65535.
@@ -678,6 +694,13 @@ class SX128x: public PhysicalLayer {
*/
int16_t setPreambleLength(uint32_t preambleLength);
/*!
\brief Set data rate.
\param dr Data rate struct. Interpretation depends on currently active modem (FSK or LoRa).
\returns \ref status_codes
*/
int16_t setDataRate(DataRate_t dr) override;
/*!
\brief Sets FSK or FLRC bit rate. Allowed values are 125, 250, 400, 500, 800, 1000,
1600 and 2000 kbps (for FSK modem) or 260, 325, 520, 650, 1000 and 1300 (for FLRC modem).
@@ -761,6 +784,13 @@ class SX128x: public PhysicalLayer {
*/
float getRSSI() override;
/*!
\brief Gets RSSI (Recorded Signal Strength Indicator).
\param packet Whether to read last packet RSSI, or the current value.
\returns RSSI value in dBm.
*/
float getRSSI(bool packet);
/*!
\brief Gets SNR (Signal to Noise Ratio) of the last received packet. Only available for LoRa or ranging modem.
\returns SNR of the last received packet in dB.
+18
View File
@@ -260,6 +260,12 @@ int16_t APRSClient::sendFrame(char* destCallsign, uint8_t destSSID, char* info)
RADIOLIB_AX25_CONTROL_UNNUMBERED_FRAME,
RADIOLIB_AX25_PID_NO_LAYER_3, const_cast<char*>(info));
// optionally set repeaters
if(this->repCalls && this->repSSIDs && this->numReps) {
int16_t state = frameUI.setRepeaters(this->repCalls, this->repSSIDs, this->numReps);
RADIOLIB_ASSERT(state);
}
return(axClient->sendFrame(&frameUI));
} else if(this->phyLayer != nullptr) {
@@ -276,4 +282,16 @@ int16_t APRSClient::sendFrame(char* destCallsign, uint8_t destSSID, char* info)
return(RADIOLIB_ERR_WRONG_MODEM);
}
void APRSClient::useRepeaters(char** repeaterCallsigns, uint8_t* repeaterSSIDs, uint8_t numRepeaters) {
this->repCalls = repeaterCallsigns;
this->repSSIDs = repeaterSSIDs;
this->numReps = numRepeaters;
}
void APRSClient::dropRepeaters() {
this->repCalls = NULL;
this->repSSIDs = NULL;
this->numReps = 0;
}
#endif
+20
View File
@@ -144,6 +144,21 @@ class APRSClient {
*/
int16_t sendFrame(char* destCallsign, uint8_t destSSID, char* info);
/*!
\brief Set the repeater callsigns and SSIDs to be used by the frames sent by sendPosition, sendMicE or sendFrame.
\param repeaterCallsigns Array of repeater callsigns in the form of null-terminated C-strings.
\param repeaterSSIDs Array of repeater SSIDs.
\param numRepeaters Number of repeaters, maximum is 8.
\returns \ref status_codes
*/
void useRepeaters(char** repeaterCallsigns, uint8_t* repeaterSSIDs, uint8_t numRepeaters);
/*!
\brief Stop using repeaters.
\returns \ref status_codes
*/
void dropRepeaters();
#if !RADIOLIB_GODMODE
private:
#endif
@@ -153,6 +168,11 @@ class APRSClient {
// default APRS symbol (car)
char symbol = '>';
char table = '/';
// repeaters
char** repCalls = NULL;
uint8_t* repSSIDs = NULL;
uint8_t numReps = 0;
// source callsign when using APRS over LoRa
char src[RADIOLIB_AX25_MAX_CALLSIGN_LEN + 1] = { 0 };
+13 -11
View File
@@ -1,5 +1,7 @@
#include "AX25.h"
#include <string.h>
#if !RADIOLIB_EXCLUDE_AX25
AX25Frame::AX25Frame(const char* destCallsign, uint8_t destSSID, const char* srcCallsign, uint8_t srcSSID, uint8_t control)
@@ -369,7 +371,7 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) {
// flip bit order
for(size_t i = 0; i < frameBuffLen; i++) {
frameBuff[i] = Module::reflect(frameBuff[i], 8);
frameBuff[i] = rlb_reflect(frameBuff[i], 8);
}
// calculate
@@ -402,7 +404,7 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) {
uint16_t stuffedFrameBuffPos = stuffedFrameBuffLenBits + 7 - 2*(stuffedFrameBuffLenBits%8);
if((frameBuff[i] >> shift) & 0x01) {
// copy 1 and increment counter
SET_BIT_IN_ARRAY(stuffedFrameBuff, stuffedFrameBuffPos);
SET_BIT_IN_ARRAY_MSB(stuffedFrameBuff, stuffedFrameBuffPos);
stuffedFrameBuffLenBits++;
count++;
@@ -412,14 +414,14 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) {
stuffedFrameBuffPos = stuffedFrameBuffLenBits + 7 - 2*(stuffedFrameBuffLenBits%8);
// insert 0 and reset counter
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, stuffedFrameBuffPos);
CLEAR_BIT_IN_ARRAY_MSB(stuffedFrameBuff, stuffedFrameBuffPos);
stuffedFrameBuffLenBits++;
count = 0;
}
} else {
// copy 0 and reset counter
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, stuffedFrameBuffPos);
CLEAR_BIT_IN_ARRAY_MSB(stuffedFrameBuff, stuffedFrameBuffPos);
stuffedFrameBuffLenBits++;
count = 0;
}
@@ -454,20 +456,20 @@ int16_t AX25Client::sendFrame(AX25Frame* frame) {
for(size_t i = preambleLen + 1; i < stuffedFrameBuffLen*8; i++) {
size_t currBitPos = i + 7 - 2*(i%8);
size_t prevBitPos = (i - 1) + 7 - 2*((i - 1)%8);
if(TEST_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos)) {
if(TEST_BIT_IN_ARRAY_MSB(stuffedFrameBuff, currBitPos)) {
// bit is 1, no change, copy previous bit
if(TEST_BIT_IN_ARRAY(stuffedFrameBuff, prevBitPos)) {
SET_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
if(TEST_BIT_IN_ARRAY_MSB(stuffedFrameBuff, prevBitPos)) {
SET_BIT_IN_ARRAY_MSB(stuffedFrameBuff, currBitPos);
} else {
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
CLEAR_BIT_IN_ARRAY_MSB(stuffedFrameBuff, currBitPos);
}
} else {
// bit is 0, transition, copy inversion of the previous bit
if(TEST_BIT_IN_ARRAY(stuffedFrameBuff, prevBitPos)) {
CLEAR_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
if(TEST_BIT_IN_ARRAY_MSB(stuffedFrameBuff, prevBitPos)) {
CLEAR_BIT_IN_ARRAY_MSB(stuffedFrameBuff, currBitPos);
} else {
SET_BIT_IN_ARRAY(stuffedFrameBuff, currBitPos);
SET_BIT_IN_ARRAY_MSB(stuffedFrameBuff, currBitPos);
}
}
}
@@ -3,9 +3,6 @@
#include "../../TypeDef.h"
#include "../../Module.h"
#if defined(RADIOLIB_BUILD_ARDUINO)
#include "../../ArduinoHal.h"
#endif
#if !RADIOLIB_EXCLUDE_BELL
@@ -3,9 +3,6 @@
#include "../../TypeDef.h"
#include "../../Module.h"
#if defined(RADIOLIB_BUILD_ARDUINO)
#include "../../ArduinoHal.h"
#endif
#include "../PhysicalLayer/PhysicalLayer.h"
+123 -72
View File
@@ -183,11 +183,12 @@ int16_t LoRaWANNode::sendReceive(uint8_t* dataUp, size_t lenUp, uint8_t fPort, u
eventUp->nbTrans = trans;
}
#if !RADIOLIB_STATIC_ONLY
delete[] uplinkMsg;
#endif
// if a hardware error occurred, return
if(state < RADIOLIB_ERR_NONE) {
#if !RADIOLIB_STATIC_ONLY
delete[] uplinkMsg;
#endif
return(state);
}
@@ -440,11 +441,19 @@ uint8_t* LoRaWANNode::getBufferSession() {
LoRaWANNode::hton<uint32_t>(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_ADR_FCNT], this->adrFCnt);
LoRaWANNode::hton<uint32_t>(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_FCNT_UP], this->fCntUp);
// store the enabled channels
uint64_t chMaskGrp0123 = 0;
uint32_t chMaskGrp45 = 0;
this->getChannelPlanMask(&chMaskGrp0123, &chMaskGrp45);
LoRaWANNode::hton<uint64_t>(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_LINK_ADR] + 1, chMaskGrp0123);
LoRaWANNode::hton<uint32_t>(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_LINK_ADR] + 9, chMaskGrp45);
// store the available/unused channels
uint16_t chMask = 0x0000;
(void)this->getAvailableChannels(&chMask);
LoRaWANNode::hton<uint16_t>(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_AVAILABLE_CHANNELS], chMask);
// save the current uplink MAC command queue
// store the current uplink MAC command queue
memcpy(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_MAC_QUEUE], this->fOptsUp, RADIOLIB_LORAWAN_FHDR_FOPTS_MAX_LEN);
memcpy(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_MAC_QUEUE_LEN], &this->fOptsUpLen, 1);
@@ -679,6 +688,8 @@ int16_t LoRaWANNode::processJoinAccept(LoRaWANJoinEvent_t *joinEvent) {
// we can ignore that error
if(state != RADIOLIB_ERR_LORA_HEADER_DAMAGED) {
RADIOLIB_ASSERT(state);
} else {
state = RADIOLIB_ERR_NONE;
}
// check reply message type
@@ -930,6 +941,9 @@ int16_t LoRaWANNode::activateOTAA(uint8_t joinDr, LoRaWANJoinEvent_t *joinEvent)
this->devNonce += 1;
LoRaWANNode::hton<uint16_t>(&this->bufferNonces[RADIOLIB_LORAWAN_NONCES_DEV_NONCE], this->devNonce);
// set the Time on Air of the JoinRequest
this->lastToA = this->phyLayer->getTimeOnAir(RADIOLIB_LORAWAN_JOIN_REQUEST_LEN) / 1000;
// configure Rx1 and Rx2 delay for JoinAccept message - these are re-configured once a valid JoinAccept is received
this->rxDelays[1] = RADIOLIB_LORAWAN_JOIN_ACCEPT_DELAY_1_MS;
this->rxDelays[2] = RADIOLIB_LORAWAN_JOIN_ACCEPT_DELAY_2_MS;
@@ -1384,11 +1398,11 @@ int16_t LoRaWANNode::receiveCommon(uint8_t dir, const LoRaWANChannel_t* dlChanne
}
// get the maximum allowed Time-on-Air of a packet given the current datarate
uint8_t maxPayLen = this->band->payloadLenMax[this->channels[RADIOLIB_LORAWAN_UPLINK].dr];
uint8_t maxPayLen = this->band->payloadLenMax[dlChannels[window].dr];
if(this->TS011) {
maxPayLen = RADIOLIB_MIN(maxPayLen, 230); // payload length is limited to 230 if under repeater
maxPayLen = RADIOLIB_MIN(maxPayLen, 222); // payload length is limited to 222 if under repeater
}
RadioLibTime_t tMax = this->phyLayer->getTimeOnAir(maxPayLen + 13); // mandatory FHDR is 12/13 bytes
RadioLibTime_t tMax = this->phyLayer->getTimeOnAir(maxPayLen + 13) / 1000; // mandatory FHDR is 12/13 bytes
bool downlinkComplete = true;
// wait for the DIO to fire indicating a downlink is received
@@ -1473,7 +1487,8 @@ int16_t LoRaWANNode::parseDownlink(uint8_t* data, size_t* len, LoRaWANEvent_t* e
// check the address
uint32_t addr = LoRaWANNode::ntoh<uint32_t>(&downlinkMsg[RADIOLIB_LORAWAN_FHDR_DEV_ADDR_POS]);
if(addr != this->devAddr) {
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("Device address mismatch, expected 0x%08X, got 0x%08X", this->devAddr, addr);
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("Device address mismatch, expected 0x%08lX, got 0x%08lX",
(unsigned long)this->devAddr, (unsigned long)addr);
#if !RADIOLIB_STATIC_ONLY
delete[] downlinkMsg;
#endif
@@ -1792,6 +1807,7 @@ int16_t LoRaWANNode::parseDownlink(uint8_t* data, size_t* len, LoRaWANEvent_t* e
event->dir = RADIOLIB_LORAWAN_DOWNLINK;
event->confirmed = isConfirmedDown;
event->confirming = isConfirmingUp;
event->frmPending = (downlinkMsg[RADIOLIB_LORAWAN_FHDR_FCTRL_POS] & RADIOLIB_LORAWAN_FCTRL_FRAME_PENDING) != 0;
event->datarate = this->channels[RADIOLIB_LORAWAN_DOWNLINK].dr;
event->freq = channels[event->dir].freq / 10000.0;
event->power = this->txPowerMax - this->txPowerSteps * 2;
@@ -1962,7 +1978,7 @@ bool LoRaWANNode::execMacCommand(uint8_t cid, uint8_t* optIn, uint8_t lenIn, uin
optIn[13] = this->nbTrans;
}
memcpy(&this->bufferSession[RADIOLIB_LORAWAN_SESSION_LINK_ADR], optIn, lenIn);
return(true);
} break;
@@ -2340,11 +2356,11 @@ void LoRaWANNode::preprocessMacLinkAdr(uint8_t* mPtr, uint8_t cLen, uint8_t* mAd
}
break;
case 6:
// for dynamic bands: all channels ON (currently defined)
// for dynamic bands: all channels ON (that are currently defined)
// for fixed bands: all 125kHz channels ON, channel mask similar to ChMask = 4
// except for CN500: all 125kHz channels ON
// for dynamic bands: retrieve all defined channels
// for dynamic bands: retrieve all currently defined channels
// for fixed bands: cannot store all defined channels, so select a random one from each bank
this->getChannelPlanMask(&chMaskGrp0123, &chMaskGrp45);
if(this->band->bandType == RADIOLIB_LORAWAN_BAND_FIXED && this->band->bandNum != BandCN500) {
@@ -2752,11 +2768,19 @@ int16_t LoRaWANNode::setPhyProperties(const LoRaWANChannel_t* chnl, uint8_t dir,
return(state);
}
// TODO implement PhysicalLayer::setModem()
// get the currently configured modem from the radio
ModemType_t modem;
state = this->phyLayer->getModem(&modem);
RADIOLIB_ASSERT(state);
// set modem-dependent functions
switch(this->band->dataRates[chnl->dr] & RADIOLIB_LORAWAN_DATA_RATE_MODEM) {
case(RADIOLIB_LORAWAN_DATA_RATE_LORA):
this->modulation = RADIOLIB_LORAWAN_MODULATION_LORA;
if(modem != ModemType_t::LoRa) {
state = this->phyLayer->setModem(ModemType_t::LoRa);
RADIOLIB_ASSERT(state);
}
modem = ModemType_t::LoRa;
// downlink messages are sent with inverted IQ
if(dir == RADIOLIB_LORAWAN_DOWNLINK) {
state = this->phyLayer->invertIQ(true);
@@ -2765,22 +2789,33 @@ int16_t LoRaWANNode::setPhyProperties(const LoRaWANChannel_t* chnl, uint8_t dir,
}
RADIOLIB_ASSERT(state);
break;
case(RADIOLIB_LORAWAN_DATA_RATE_FSK):
this->modulation = RADIOLIB_LORAWAN_MODULATION_GFSK;
if(modem != ModemType_t::FSK) {
state = this->phyLayer->setModem(ModemType_t::FSK);
RADIOLIB_ASSERT(state);
}
modem = ModemType_t::FSK;
state = this->phyLayer->setDataShaping(RADIOLIB_SHAPING_1_0);
RADIOLIB_ASSERT(state);
state = this->phyLayer->setEncoding(RADIOLIB_ENCODING_WHITENING);
RADIOLIB_ASSERT(state);
break;
case(RADIOLIB_LORAWAN_DATA_RATE_LR_FHSS):
this->modulation = RADIOLIB_LORAWAN_MODULATION_LR_FHSS;
if(modem != ModemType_t::LRFHSS) {
state = this->phyLayer->setModem(ModemType_t::LRFHSS);
RADIOLIB_ASSERT(state);
}
modem = ModemType_t::LRFHSS;
break;
default:
return(RADIOLIB_ERR_UNSUPPORTED);
}
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("");
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("PHY: Frequency %cL = %7.3f MHz", dir ? 'D' : 'U', chnl->freq / 10000.0);
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("PHY: Frequency = %7.3f MHz, TX = %d dBm", chnl->freq / 10000.0, pwr);
state = this->phyLayer->setFrequency(chnl->freq / 10000.0);
RADIOLIB_ASSERT(state);
@@ -2796,40 +2831,37 @@ int16_t LoRaWANNode::setPhyProperties(const LoRaWANChannel_t* chnl, uint8_t dir,
state = this->phyLayer->setDataRate(dr);
RADIOLIB_ASSERT(state);
if(this->modulation == RADIOLIB_LORAWAN_MODULATION_GFSK) {
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("FSK: BR = %4.1f, TX = %d dBm, FD = %4.1f kHz",
dr.fsk.bitRate, pwr, dr.fsk.freqDev);
}
if(this->modulation == RADIOLIB_LORAWAN_MODULATION_LORA) {
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("LoRa: SF = %d, TX = %d dBm, BW = %5.1f kHz, CR = 4/%d",
dr.lora.spreadingFactor, pwr, dr.lora.bandwidth, dr.lora.codingRate);
}
// this only needs to be done once-ish
uint8_t syncWord[4] = { 0 };
uint8_t syncWordLen = 0;
size_t preLen = 0;
switch(this->modulation) {
case(RADIOLIB_LORAWAN_MODULATION_GFSK): {
switch(modem) {
case(ModemType_t::FSK): {
preLen = 8*RADIOLIB_LORAWAN_GFSK_PREAMBLE_LEN;
syncWord[0] = (uint8_t)(RADIOLIB_LORAWAN_GFSK_SYNC_WORD >> 16);
syncWord[1] = (uint8_t)(RADIOLIB_LORAWAN_GFSK_SYNC_WORD >> 8);
syncWord[2] = (uint8_t)RADIOLIB_LORAWAN_GFSK_SYNC_WORD;
syncWordLen = 3;
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("FSK: BR = %4.1f, FD = %4.1f kHz",
dr.fsk.bitRate, dr.fsk.freqDev);
} break;
case(RADIOLIB_LORAWAN_MODULATION_LORA): {
case(ModemType_t::LoRa): {
preLen = RADIOLIB_LORAWAN_LORA_PREAMBLE_LEN;
syncWord[0] = RADIOLIB_LORAWAN_LORA_SYNC_WORD;
syncWordLen = 1;
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("LoRa: SF = %d, BW = %5.1f kHz, CR = 4/%d, IQ: %c",
dr.lora.spreadingFactor, dr.lora.bandwidth, dr.lora.codingRate, dir ? 'D' : 'U');
} break;
case(RADIOLIB_LORAWAN_MODULATION_LR_FHSS): {
case(ModemType_t::LRFHSS): {
syncWord[0] = (uint8_t)(RADIOLIB_LORAWAN_LR_FHSS_SYNC_WORD >> 24);
syncWord[1] = (uint8_t)(RADIOLIB_LORAWAN_LR_FHSS_SYNC_WORD >> 16);
syncWord[2] = (uint8_t)(RADIOLIB_LORAWAN_LR_FHSS_SYNC_WORD >> 8);
syncWord[3] = (uint8_t)RADIOLIB_LORAWAN_LR_FHSS_SYNC_WORD;
syncWordLen = 4;
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("LR-FHSS: BW = 0x%02x, CR = 0x%02x kHz, grid = %c",
dr.lrFhss.bw, dr.lrFhss.cr, dr.lrFhss.narrowGrid ? 'N' : 'W');
} break;
default:
@@ -2843,7 +2875,7 @@ int16_t LoRaWANNode::setPhyProperties(const LoRaWANChannel_t* chnl, uint8_t dir,
if(pre) {
preLen = pre;
}
if(this->modulation != RADIOLIB_LORAWAN_MODULATION_LR_FHSS) {
if(modem != ModemType_t::LRFHSS) {
state = this->phyLayer->setPreambleLength(preLen);
}
return(state);
@@ -2885,7 +2917,9 @@ void LoRaWANNode::getChannelPlanMask(uint64_t* chMaskGrp0123, uint32_t* chMaskGr
*chMaskGrp0123 = 0;
*chMaskGrp45 = 0;
if(this->band->bandType == RADIOLIB_LORAWAN_BAND_DYNAMIC) {
// if there are any channels selected, create the mask from those channels
// channels are always selected for dynamic bands and/or when a device is active
if(this->band->bandType == RADIOLIB_LORAWAN_BAND_DYNAMIC || this->isActivated()) {
for(int i = 0; i < RADIOLIB_LORAWAN_NUM_AVAILABLE_CHANNELS; i++) {
uint8_t idx = this->channelPlan[RADIOLIB_LORAWAN_UPLINK][i].idx;
if(idx != RADIOLIB_LORAWAN_CHANNEL_INDEX_NONE) {
@@ -2896,6 +2930,8 @@ void LoRaWANNode::getChannelPlanMask(uint64_t* chMaskGrp0123, uint32_t* chMaskGr
}
}
}
return;
} else { // bandType == RADIOLIB_LORAWAN_BAND_FIXED
// if a subband is set, we can set the channel indices straight from subband
if(this->subBand > 0 && this->subBand <= 8) {
@@ -2906,9 +2942,9 @@ void LoRaWANNode::getChannelPlanMask(uint64_t* chMaskGrp0123, uint32_t* chMaskGr
// CN500 only: for sub band 9-12, set bank of 8 125kHz channels
*chMaskGrp45 |= 0xFF << ((this->subBand - 9) * 8);
} else {
// if subband is set to 0, all 125kHz channels are enabled
// however, we can 'only' store 16 channels, so we do not actually store these
// therefore, we select a random channel from each bank of 8 channels
// if subband is set to 0, all 125kHz channels are enabled.
// however, we can 'only' store 16 channels, so we don't use all channels at once.
// instead, we select a random channel from each bank of 8 channels + 1 from second plan.
uint8_t num125kHz = this->band->txSpans[0].numChannels;
uint8_t numBanks = num125kHz / 8;
for(uint8_t bank = 0; bank < numBanks; bank++) {
@@ -2992,10 +3028,6 @@ void LoRaWANNode::selectChannelPlanFix() {
// make all enabled channels available for uplink selection
this->setAvailableChannels(0xFFFF);
#if RADIOLIB_DEBUG_PROTOCOL
this->printChannels();
#endif
}
uint8_t LoRaWANNode::getAvailableChannels(uint16_t* chMask) {
@@ -3092,7 +3124,6 @@ int16_t LoRaWANNode::selectChannels() {
}
bool LoRaWANNode::applyChannelMask(uint64_t chMaskGrp0123, uint32_t chMaskGrp45) {
int num = 0;
if(this->band->bandType == RADIOLIB_LORAWAN_BAND_DYNAMIC) {
for(int i = 0; i < RADIOLIB_LORAWAN_NUM_AVAILABLE_CHANNELS; i++) {
if(chMaskGrp0123 & ((uint64_t)1 << i)) {
@@ -3106,7 +3137,12 @@ bool LoRaWANNode::applyChannelMask(uint64_t chMaskGrp0123, uint32_t chMaskGrp45)
}
}
} else { // bandType == RADIOLIB_LORAWAN_BAND_FIXED
// full channel mask received, so clear all existing channels
LoRaWANChannel_t chnl = RADIOLIB_LORAWAN_CHANNEL_NONE;
for(size_t i = 0; i < RADIOLIB_LORAWAN_NUM_AVAILABLE_CHANNELS; i++) {
this->channelPlan[RADIOLIB_LORAWAN_UPLINK][i] = chnl;
}
int num = 0;
uint8_t spanNum = 0;
int chNum = 0;
int chOfs = 0;
@@ -3188,7 +3224,8 @@ bool LoRaWANNode::verifyMIC(uint8_t* msg, size_t len, uint8_t* key) {
// calculate the expected value and compare
uint32_t micCalculated = generateMIC(msg, len - sizeof(uint32_t), key);
if(micCalculated != micReceived) {
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("MIC mismatch, expected %08x, got %08x", micCalculated, micReceived);
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("MIC mismatch, expected %08lx, got %08lx",
(unsigned long)micCalculated, (unsigned long)micReceived);
return(false);
}
@@ -3222,12 +3259,12 @@ uint8_t LoRaWANNode::getMaxPayloadLen() {
RADIOLIB_LORAWAN_UPLINK,
this->txPowerMax - 2*this->txPowerSteps);
// mandatory FHDR is 12/13, so add & subtract 13 from calculations where necessary
uint8_t minLen = 0;
uint8_t maxLen = this->band->payloadLenMax[this->channels[RADIOLIB_LORAWAN_UPLINK].dr] + 13;
uint8_t maxLen = this->band->payloadLenMax[this->channels[RADIOLIB_LORAWAN_UPLINK].dr];
if(this->TS011) {
maxLen = RADIOLIB_MIN(maxLen, 230 + 13); // payload length is limited to 230 if under repeater
maxLen = RADIOLIB_MIN(maxLen, 222); // payload length is limited to N=222 if under repeater
}
maxLen += 13; // mandatory FHDR is 12/13 bytes
// if not limited by dwell-time, just return maximum
if(!this->dwellTimeEnabledUp) {
@@ -3262,10 +3299,13 @@ int16_t LoRaWANNode::findDataRate(uint8_t dr, DataRate_t* dataRate) {
return(state);
}
ModemType_t modemNew;
uint8_t dataRateBand = this->band->dataRates[dr];
switch(dataRateBand & RADIOLIB_LORAWAN_DATA_RATE_MODEM) {
case(RADIOLIB_LORAWAN_DATA_RATE_LORA):
modemNew = ModemType_t::LoRa;
dataRate->lora.spreadingFactor = ((dataRateBand & RADIOLIB_LORAWAN_DATA_RATE_SF) >> 3) + 7;
switch(dataRateBand & RADIOLIB_LORAWAN_DATA_RATE_BW) {
case(RADIOLIB_LORAWAN_DATA_RATE_BW_125_KHZ):
@@ -3283,18 +3323,55 @@ int16_t LoRaWANNode::findDataRate(uint8_t dr, DataRate_t* dataRate) {
dataRate->lora.codingRate = 5;
break;
case(RADIOLIB_LORAWAN_DATA_RATE_FSK):
modemNew = ModemType_t::FSK;
dataRate->fsk.bitRate = 50;
dataRate->fsk.freqDev = 25;
break;
case(RADIOLIB_LORAWAN_DATA_RATE_LR_FHSS):
// not yet supported by DataRate_t
return(RADIOLIB_ERR_UNSUPPORTED);
modemNew = ModemType_t::LRFHSS;
switch(dataRateBand & RADIOLIB_LORAWAN_DATA_RATE_BW) {
case(RADIOLIB_LORAWAN_DATA_RATE_BW_137_KHZ):
dataRate->lrFhss.bw = 0x02; // specific encoding
dataRate->lrFhss.narrowGrid = 1;
break;
case(RADIOLIB_LORAWAN_DATA_RATE_BW_336_KHZ):
dataRate->lrFhss.bw = 0x04; // specific encoding
dataRate->lrFhss.narrowGrid = 1;
break;
case(RADIOLIB_LORAWAN_DATA_RATE_BW_1523_KHZ):
dataRate->lrFhss.bw = 0x08; // specific encoding
dataRate->lrFhss.narrowGrid = 0;
break;
default:
return(RADIOLIB_ERR_UNSUPPORTED);
}
switch(dataRateBand & RADIOLIB_LORAWAN_DATA_RATE_CR) {
case(RADIOLIB_LORAWAN_DATA_RATE_CR_1_3):
dataRate->lrFhss.cr = 0x03;
break;
case(RADIOLIB_LORAWAN_DATA_RATE_CR_2_3):
dataRate->lrFhss.cr = 0x01;
break;
default:
return(RADIOLIB_ERR_UNSUPPORTED);
}
break;
default:
return(RADIOLIB_ERR_UNSUPPORTED);
}
state = this->phyLayer->checkDataRate(*dataRate);
// get the currently configured modem from the radio
ModemType_t modemCurrent;
state = this->phyLayer->getModem(&modemCurrent);
RADIOLIB_ASSERT(state);
// if the required modem is different than the current one, change over
if(modemNew != modemCurrent) {
state = this->phyLayer->setModem(modemNew);
RADIOLIB_ASSERT(state);
}
state = this->phyLayer->checkDataRate(*dataRate);
return(state);
}
@@ -3373,30 +3450,4 @@ uint16_t LoRaWANNode::checkSum16(const uint8_t *key, uint16_t keyLen) {
return(checkSum);
}
template<typename T>
T LoRaWANNode::ntoh(uint8_t* buff, size_t size) {
uint8_t* buffPtr = buff;
size_t targetSize = sizeof(T);
if(size != 0) {
targetSize = size;
}
T res = 0;
for(size_t i = 0; i < targetSize; i++) {
res |= (uint32_t)(*(buffPtr++)) << 8*i;
}
return(res);
}
template<typename T>
void LoRaWANNode::hton(uint8_t* buff, T val, size_t size) {
uint8_t* buffPtr = buff;
size_t targetSize = sizeof(T);
if(size != 0) {
targetSize = size;
}
for(size_t i = 0; i < targetSize; i++) {
*(buffPtr++) = val >> 8*i;
}
}
#endif
+34 -12
View File
@@ -15,11 +15,6 @@
#define RADIOLIB_LORAWAN_CLASS_B (0x0B)
#define RADIOLIB_LORAWAN_CLASS_C (0x0C)
// modulation type
#define RADIOLIB_LORAWAN_MODULATION_LORA (0)
#define RADIOLIB_LORAWAN_MODULATION_GFSK (1)
#define RADIOLIB_LORAWAN_MODULATION_LR_FHSS (2)
// preamble format
#define RADIOLIB_LORAWAN_LORA_SYNC_WORD (0x34)
#define RADIOLIB_LORAWAN_LORA_PREAMBLE_LEN (8)
@@ -65,13 +60,14 @@
#define RADIOLIB_LORAWAN_DATA_RATE_SF_9 (0x02 << 3) // 5 3 SF9
#define RADIOLIB_LORAWAN_DATA_RATE_SF_8 (0x01 << 3) // 5 3 SF8
#define RADIOLIB_LORAWAN_DATA_RATE_SF_7 (0x00 << 3) // 5 3 SF7
#define RADIOLIB_LORAWAN_DATA_RATE_BW (0x03 << 1) // 2 1 bandwith mask
#define RADIOLIB_LORAWAN_DATA_RATE_BW (0x03 << 1) // 2 1 bandwidth mask
#define RADIOLIB_LORAWAN_DATA_RATE_BW_125_KHZ (0x00 << 1) // 2 1 125 kHz
#define RADIOLIB_LORAWAN_DATA_RATE_BW_250_KHZ (0x01 << 1) // 2 1 250 kHz
#define RADIOLIB_LORAWAN_DATA_RATE_BW_500_KHZ (0x02 << 1) // 2 1 LoRa bandwidth: 500 kHz
#define RADIOLIB_LORAWAN_DATA_RATE_BW_137_KHZ (0x00 << 1) // 2 1 137 kHz
#define RADIOLIB_LORAWAN_DATA_RATE_BW_336_KHZ (0x01 << 1) // 2 1 336 kHz
#define RADIOLIB_LORAWAN_DATA_RATE_BW_1523_KHZ (0x02 << 1) // 2 1 LR-FHSS bandwidth: 1523 kHz
#define RADIOLIB_LORAWAN_DATA_RATE_CR (0x01 << 0) // 0 0 coding rate mask
#define RADIOLIB_LORAWAN_DATA_RATE_CR_1_3 (0x00 << 0) // 0 0 LR-FHSS coding rate: 1/3
#define RADIOLIB_LORAWAN_DATA_RATE_CR_2_3 (0x01 << 0) // 0 0 2/3
#define RADIOLIB_LORAWAN_DATA_RATE_UNUSED (0xFF << 0) // 7 0 unused data rate
@@ -385,7 +381,7 @@ struct LoRaWANBand_t {
/*! \brief Maximum allowed frequency (coded in 100 Hz steps) */
uint32_t freqMax;
/*! \brief Array of allowed maximum payload lengths for each data rate (global maximum) */
/*! \brief Array of allowed maximum application payload lengths for each data rate (N-value) */
uint8_t payloadLenMax[RADIOLIB_LORAWAN_CHANNEL_NUM_DATARATES];
/*! \brief Maximum allowed output power in this band in dBm */
@@ -504,6 +500,9 @@ struct LoRaWANEvent_t {
(e.g., server downlink reply to confirmed uplink sent by user application)*/
bool confirming;
/*! \brief Whether further downlink messages are pending on the server side. */
bool frmPending;
/*! \brief Datarate */
uint8_t datarate;
@@ -605,7 +604,7 @@ class LoRaWANNode {
\param initialDr The datarate at which to send the first uplink and any subsequent uplinks (unless ADR is enabled).
\returns \ref status_codes
*/
int16_t activateABP(uint8_t initialDr = RADIOLIB_LORAWAN_DATA_RATE_UNUSED);
virtual int16_t activateABP(uint8_t initialDr = RADIOLIB_LORAWAN_DATA_RATE_UNUSED);
/*! \brief Whether there is an ongoing session active */
bool isActivated();
@@ -913,9 +912,6 @@ class LoRaWANNode {
uint32_t confFCntDown = RADIOLIB_LORAWAN_FCNT_NONE;
uint32_t adrFCnt = 0;
// modulation of the currently configured channel
uint8_t modulation = RADIOLIB_LORAWAN_MODULATION_LORA;
// ADR is enabled by default
bool adrEnabled = true;
@@ -1069,7 +1065,7 @@ class LoRaWANNode {
// perform a single CAD operation for the under SF/CH combination. Returns either busy or otherwise.
bool cadChannelClear();
// get or create a complete 80-bit channel mask for current configuration
// (dynamic bands:) get or (fixed bands:) create a complete 80-bit channel mask for current configuration
void getChannelPlanMask(uint64_t* chMaskGrp0123, uint32_t* chMaskGrp45);
// setup uplink/downlink channel data rates and frequencies
@@ -1127,4 +1123,30 @@ class LoRaWANNode {
static void hton(uint8_t* buff, T val, size_t size = 0);
};
template<typename T>
T LoRaWANNode::ntoh(uint8_t* buff, size_t size) {
uint8_t* buffPtr = buff;
size_t targetSize = sizeof(T);
if(size != 0) {
targetSize = size;
}
T res = 0;
for(size_t i = 0; i < targetSize; i++) {
res |= (uint32_t)(*(buffPtr++)) << 8*i;
}
return(res);
}
template<typename T>
void LoRaWANNode::hton(uint8_t* buff, T val, size_t size) {
uint8_t* buffPtr = buff;
size_t targetSize = sizeof(T);
if(size != 0) {
targetSize = size;
}
for(size_t i = 0; i < targetSize; i++) {
*(buffPtr++) = val >> 8*i;
}
}
#endif
@@ -22,7 +22,7 @@ const LoRaWANBand_t EU868 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 8630000,
.freqMax = 8700000,
.payloadLenMax = { 59, 59, 59, 123, 250, 250, 250, 250, 58, 123, 58, 123, 0, 0, 0 },
.payloadLenMax = { 51, 51, 51, 115, 242, 242, 242, 242, 50, 115, 50, 115, 0, 0, 0 },
.powerMax = 16,
.powerNumSteps = 7,
.dutyCycle = 36000,
@@ -95,7 +95,7 @@ const LoRaWANBand_t US915 = {
.bandType = RADIOLIB_LORAWAN_BAND_FIXED,
.freqMin = 9020000,
.freqMax = 9280000,
.payloadLenMax = { 19, 61, 133, 250, 250, 58, 133, 0, 61, 137, 250, 250, 250, 250, 0 },
.payloadLenMax = { 11, 53, 125, 242, 242, 50, 125, 0, 53, 129, 242, 242, 242, 242, 0 },
.powerMax = 30,
.powerNumSteps = 10,
.dutyCycle = 0,
@@ -189,7 +189,7 @@ const LoRaWANBand_t EU433 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 4330000,
.freqMax = 4340000,
.payloadLenMax = { 59, 59, 59, 123, 250, 250, 250, 250, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 51, 115, 242, 242, 242, 242, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 12,
.powerNumSteps = 5,
.dutyCycle = 36000,
@@ -262,7 +262,7 @@ const LoRaWANBand_t AU915 = {
.bandType = RADIOLIB_LORAWAN_BAND_FIXED,
.freqMin = 9150000,
.freqMax = 9280000,
.payloadLenMax = { 59, 59, 59, 123, 250, 250, 250, 58, 61, 137, 250, 250, 250, 250, 0 },
.payloadLenMax = { 51, 51, 51, 115, 242, 242, 242, 50, 53, 129, 242, 242, 242, 242, 0 },
.powerMax = 30,
.powerNumSteps = 10,
.dutyCycle = 0,
@@ -356,7 +356,7 @@ const LoRaWANBand_t CN500 = {
.bandType = RADIOLIB_LORAWAN_BAND_FIXED,
.freqMin = 4700000,
.freqMax = 5100000,
.payloadLenMax = { 59, 59, 59, 123, 250, 250, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 51, 115, 242, 242, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 19,
.powerNumSteps = 7,
.dutyCycle = 0,
@@ -443,7 +443,7 @@ const LoRaWANBand_t AS923 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 9150000,
.freqMax = 9280000,
.payloadLenMax = { 59, 59, 123, 123, 250, 250, 250, 250, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 115, 115, 242, 242, 242, 242, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 16,
.powerNumSteps = 7,
.dutyCycle = 36000,
@@ -516,7 +516,7 @@ const LoRaWANBand_t AS923_2 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 9150000,
.freqMax = 9280000,
.payloadLenMax = { 59, 59, 123, 123, 250, 250, 250, 250, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 115, 115, 242, 242, 242, 242, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 16,
.powerNumSteps = 7,
.dutyCycle = 36000,
@@ -589,7 +589,7 @@ const LoRaWANBand_t AS923_3 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 9150000,
.freqMax = 9280000,
.payloadLenMax = { 59, 59, 123, 123, 250, 250, 250, 250, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 115, 115, 242, 242, 242, 242, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 16,
.powerNumSteps = 7,
.dutyCycle = 36000,
@@ -662,7 +662,7 @@ const LoRaWANBand_t AS923_4 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 9170000,
.freqMax = 9200000,
.payloadLenMax = { 59, 59, 123, 123, 250, 250, 250, 250, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 115, 115, 242, 242, 242, 242, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 16,
.powerNumSteps = 7,
.dutyCycle = 36000,
@@ -735,7 +735,7 @@ const LoRaWANBand_t KR920 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 9209000,
.freqMax = 9233000,
.payloadLenMax = { 59, 59, 59, 123, 250, 250, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 51, 115, 242, 242, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 14,
.powerNumSteps = 7,
.dutyCycle = 0,
@@ -808,7 +808,7 @@ const LoRaWANBand_t IN865 = {
.bandType = RADIOLIB_LORAWAN_BAND_DYNAMIC,
.freqMin = 8650000,
.freqMax = 8670000,
.payloadLenMax = { 59, 59, 59, 123, 250, 250, 0, 250, 0, 0, 0, 0, 0, 0, 0 },
.payloadLenMax = { 51, 51, 51, 115, 242, 242, 0, 242, 0, 0, 0, 0, 0, 0, 0 },
.powerMax = 30,
.powerNumSteps = 10,
.dutyCycle = 0,
+8 -8
View File
@@ -1,6 +1,8 @@
#include "Pager.h"
#include <string.h>
#include <math.h>
#if defined(ESP_PLATFORM)
#include "esp_attr.h"
#endif
@@ -177,7 +179,7 @@ int16_t PagerClient::transmit(uint8_t* data, size_t len, uint32_t addr, uint8_t
// first insert the remainder from previous code word (if any)
if(remBits > 0) {
// this doesn't apply to BCD messages, so no need to check that here
uint8_t prev = Module::reflect(data[dataPos - 1], 8);
uint8_t prev = rlb_reflect(data[dataPos - 1], 8);
prev >>= 1;
msg[blockPos] |= (uint32_t)prev << (RADIOLIB_PAGER_CODE_WORD_LEN - 1 - remBits);
}
@@ -191,7 +193,7 @@ int16_t PagerClient::transmit(uint8_t* data, size_t len, uint32_t addr, uint8_t
if(encoding == RADIOLIB_PAGER_BCD) {
symbol = encodeBCD(symbol);
}
symbol = Module::reflect(symbol, 8);
symbol = rlb_reflect(symbol, 8);
symbol >>= (8 - symbolLength);
// insert the next message symbol
@@ -205,7 +207,7 @@ int16_t PagerClient::transmit(uint8_t* data, size_t len, uint32_t addr, uint8_t
uint8_t numSteps = (symbolPos - RADIOLIB_PAGER_FUNC_BITS_POS + symbolLength)/symbolLength;
for(uint8_t j = 0; j < numSteps; j++) {
symbol = encodeBCD(' ');
symbol = Module::reflect(symbol, 8);
symbol = rlb_reflect(symbol, 8);
symbol >>= (8 - symbolLength);
msg[blockPos] |= (uint32_t)symbol << symbolPos;
symbolPos -= symbolLength;
@@ -314,9 +316,7 @@ int16_t PagerClient::readData(String& str, size_t len, uint32_t* addr) {
uint8_t data[RADIOLIB_STATIC_ARRAY_SIZE + 1];
#else
uint8_t* data = new uint8_t[length + 1];
if(!data) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(data);
#endif
// read the received data
@@ -428,7 +428,7 @@ int16_t PagerClient::readData(uint8_t* data, size_t* len, uint32_t* addr) {
uint32_t symbol = prevSymbol << (symbolLength - ovfBits) | currSymbol;
// finally, we can flip the bits
symbol = Module::reflect((uint8_t)symbol, 8);
symbol = rlb_reflect((uint8_t)symbol, 8);
symbol >>= (8 - symbolLength);
// decode BCD and we're done
@@ -446,7 +446,7 @@ int16_t PagerClient::readData(uint8_t* data, size_t* len, uint32_t* addr) {
while(bitPos >= RADIOLIB_PAGER_MESSAGE_END_POS) {
// get the message symbol from the code word and reverse bits
uint32_t symbol = (cw & (0x7FUL << bitPos)) >> bitPos;
symbol = Module::reflect((uint8_t)symbol, 8);
symbol = rlb_reflect((uint8_t)symbol, 8);
symbol >>= (8 - symbolLength);
// decode BCD if needed
@@ -1,4 +1,5 @@
#include "PhysicalLayer.h"
#include <string.h>
PhysicalLayer::PhysicalLayer(float step, size_t maxLen) {
@@ -77,9 +78,7 @@ int16_t PhysicalLayer::receive(String& str, size_t len) {
} else {
data = new uint8_t[length + 1];
}
if(!data) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(data);
#endif
// attempt packet reception
@@ -179,9 +178,7 @@ int16_t PhysicalLayer::readData(String& str, size_t len) {
uint8_t data[RADIOLIB_STATIC_ARRAY_SIZE + 1];
#else
uint8_t* data = new uint8_t[length + 1];
if(!data) {
return(RADIOLIB_ERR_MEMORY_ALLOCATION_FAILED);
}
RADIOLIB_ASSERT_PTR(data);
#endif
// read the received data
@@ -481,7 +478,7 @@ void PhysicalLayer::updateDirectBuffer(uint8_t bit) {
// check complete byte
if(this->bufferBitPos == 8) {
this->buffer[this->bufferWritePos] = Module::reflect(this->buffer[this->bufferWritePos], 8);
this->buffer[this->bufferWritePos] = rlb_reflect(this->buffer[this->bufferWritePos], 8);
RADIOLIB_DEBUG_PROTOCOL_PRINTLN("R\t%X", this->buffer[this->bufferWritePos]);
this->bufferWritePos++;
@@ -530,6 +527,16 @@ void PhysicalLayer::clearChannelScanAction() {
}
int16_t PhysicalLayer::setModem(ModemType_t modem) {
(void)modem;
return(RADIOLIB_ERR_UNSUPPORTED);
}
int16_t PhysicalLayer::getModem(ModemType_t* modem) {
(void)modem;
return(RADIOLIB_ERR_UNSUPPORTED);
}
#if RADIOLIB_INTERRUPT_TIMING
void PhysicalLayer::setInterruptSetup(void (*func)(uint32_t)) {
Module* mod = getMod();
@@ -62,6 +62,9 @@ struct LrFhssRate_t {
/*! \brief Coding rate */
uint8_t cr;
/*! \brief Grid spacing */
bool narrowGrid;
};
/*!
@@ -74,6 +77,9 @@ union DataRate_t {
/*! \brief Interpretation for FSK modems */
FSKRate_t fsk;
/*! \brief Interpretation for LR-FHSS modems */
LrFhssRate_t lrFhss;
};
/*!
@@ -124,6 +130,16 @@ union ChannelScanConfig_t {
RSSIScanConfig_t rssi;
};
/*!
\enum ModemType_t
\brief Type of modem, used by setModem.
*/
enum ModemType_t {
FSK = 0,
LoRa,
LRFHSS,
};
/*!
\class PhysicalLayer
@@ -638,6 +654,21 @@ class PhysicalLayer {
*/
virtual void clearChannelScanAction();
/*!
\brief Set modem for the radio to use. Will perform full reset and reconfigure the radio
using its default parameters.
\param modem Modem type to set. Not all modems are implemented by all radio modules!
\returns \ref status_codes
*/
virtual int16_t setModem(ModemType_t modem);
/*!
\brief Get modem currently in use by the radio.
\param modem Pointer to a variable to save the retrieved configuration into.
\returns \ref status_codes
*/
virtual int16_t getModem(ModemType_t* modem);
#if RADIOLIB_INTERRUPT_TIMING
/*!
@@ -696,6 +727,7 @@ class PhysicalLayer {
friend class BellClient;
friend class FT8Client;
friend class LoRaWANNode;
friend class M17Client;
};
#endif
+2 -2
View File
@@ -11,7 +11,7 @@ uint32_t RadioLibCRC::checksum(const uint8_t* buff, size_t len) {
if(i % 8 == 0) {
uint32_t in = buff[pos++];
if(this->refIn) {
in = Module::reflect(in, 8);
in = rlb_reflect(in, 8);
}
crc ^= (in << (this->size - 8));
}
@@ -26,7 +26,7 @@ uint32_t RadioLibCRC::checksum(const uint8_t* buff, size_t len) {
crc ^= this->out;
if(this->refOut) {
crc = Module::reflect(crc, this->size);
crc = rlb_reflect(crc, this->size);
}
crc &= (uint32_t)0xFFFFFFFF >> (32 - this->size);
return(crc);
-3
View File
@@ -3,9 +3,6 @@
#include "../TypeDef.h"
#include "../Module.h"
#if defined(RADIOLIB_BUILD_ARDUINO)
#include "../ArduinoHal.h"
#endif
// CCITT CRC properties (used by AX.25)
#define RADIOLIB_CRC_CCITT_POLY (0x1021)
+56
View File
@@ -307,3 +307,59 @@ uint32_t RadioLibBCH::encode(uint32_t dataword) {
}
RadioLibBCH RadioLibBCHInstance;
RadioLibConvCode::RadioLibConvCode() {
}
void RadioLibConvCode::begin(uint8_t rt) {
this->enc_state = 0;
this->rate = rt;
}
int16_t RadioLibConvCode::encode(const uint8_t* in, size_t in_bits, uint8_t* out, size_t* out_bits) {
if(!in || !out) {
return(RADIOLIB_ERR_UNKNOWN);
}
size_t ind_bit;
uint16_t data_out_bitcount = 0;
uint32_t bin_out_word = 0;
// iterate over the provided bits
for(ind_bit = 0; ind_bit < in_bits; ind_bit++) {
uint8_t cur_bit = GET_BIT_IN_ARRAY_LSB(in, ind_bit);
const uint32_t* lut_ptr = (this->rate == 2) ? ConvCodeTable1_2 : ConvCodeTable1_3;
uint8_t word_pos = this->enc_state / 4;
uint8_t byte_pos = (3 - (this->enc_state % 4)) * 8;
uint8_t nibble_pos = (1 - cur_bit) * 4;
uint8_t g1g0 = (lut_ptr[word_pos] >> (byte_pos + nibble_pos)) & 0x0F;
uint8_t mod = this->rate == 2 ? 16 : 64;
this->enc_state = (this->enc_state * 2 + cur_bit) % mod;
bin_out_word |= (g1g0 << ((7 - (ind_bit % 8)) * this->rate));
if(ind_bit % 8 == 7) {
if(this->rate == 3) {
*out++ = (uint8_t)(bin_out_word >> 16);
}
*out++ = (uint8_t)(bin_out_word >> 8);
*out++ = (uint8_t)bin_out_word;
bin_out_word = 0;
}
data_out_bitcount += this->rate;
}
if(ind_bit % 8) {
if(this->rate == 3) {
*out++ = (uint8_t)(bin_out_word >> 16);
}
*out++ = (uint8_t)(bin_out_word >> 8);
*out++ = (uint8_t)bin_out_word;
}
if(out_bits) { *out_bits = data_out_bitcount; }
return(RADIOLIB_ERR_NONE);
}
RadioLibConvCode RadioLibConvCodeInstance;
+82 -9
View File
@@ -3,9 +3,6 @@
#include "../TypeDef.h"
#include "../Module.h"
#if defined(RADIOLIB_BUILD_ARDUINO)
#include "../ArduinoHal.h"
#endif
// BCH(31, 21) code constants
#define RADIOLIB_PAGER_BCH_N (31)
@@ -31,7 +28,7 @@ class RadioLibBCH {
RadioLibBCH();
/*!
\brief Default detructor.
\brief Default destructor.
*/
~RadioLibBCH();
@@ -71,11 +68,87 @@ class RadioLibBCH {
// the global singleton
extern RadioLibBCH RadioLibBCHInstance;
// macros to access bits in byte array, from http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html
#define SET_BIT_IN_ARRAY(A, k) ( A[(k/8)] |= (1 << (k%8)) )
#define CLEAR_BIT_IN_ARRAY(A, k) ( A[(k/8)] &= ~(1 << (k%8)) )
#define TEST_BIT_IN_ARRAY(A, k) ( A[(k/8)] & (1 << (k%8)) )
#define GET_BIT_IN_ARRAY(A, k) ( (A[(k/8)] & (1 << (k%8))) ? 1 : 0 )
/*!
\class RadioLibConvCode
\brief Class to perform convolutional coding with variable rates.
Only 1/2 and 1/3 rate is currently supported.
Convolutional coder implementation in this class is adapted from Semtech's LR-FHSS demo:
https://github.com/Lora-net/SWDM001/tree/master/lib/sx126x_driver
Its SX126x driver is distributed under the Clear BSD License,
and to comply with its terms, it is reproduced below.
The Clear BSD License
Copyright Semtech Corporation 2021. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the disclaimer
below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Semtech corporation nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SEMTECH CORPORATION BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
class RadioLibConvCode {
public:
/*!
\brief Default constructor.
*/
RadioLibConvCode();
/*!
\brief Initialization method.
\param rt Encoding rate denominator (1/x). Only 1/2 and 1/3 encoding is currently supported.
*/
void begin(uint8_t rt);
/*!
\brief Encoding method.
\param in Input buffer (a byte array).
\param in_bits Input length in bits.
\param out Output buffer (a byte array). It is up to the caller
to ensure the buffer is large enough to fit the encoded data!
\param out_bits Pointer to a variable to save the number of encoded bits.
Ignored if set to NULL.
\returns \ref status_codes
*/
int16_t encode(const uint8_t* in, size_t in_bits, uint8_t* out, size_t* out_bits = NULL);
private:
uint8_t enc_state = 0;
uint8_t rate = 0;
};
// each 32-bit word stores 8 values, one per each nibble
static const uint32_t ConvCodeTable1_3[16] = {
0x07347043, 0x61521625, 0x16256152, 0x70430734,
0x43703407, 0x25165261, 0x52612516, 0x34074370,
0x70430734, 0x16256152, 0x61521625, 0x07347043,
0x34074370, 0x52612516, 0x25165261, 0x43703407,
};
static const uint32_t ConvCodeTable1_2[4] = {
0x03122130, 0x21300312, 0x30211203, 0x12033021,
};
extern RadioLibConvCode RadioLibConvCodeInstance;
#endif
+105
View File
@@ -0,0 +1,105 @@
#include "Utils.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
uint32_t rlb_reflect(uint32_t in, uint8_t bits) {
uint32_t res = 0;
for(uint8_t i = 0; i < bits; i++) {
res |= (((in & ((uint32_t)1 << i)) >> i) << (bits - i - 1));
}
return(res);
}
void rlb_hexdump(const char* level, uint8_t* data, size_t len, uint32_t offset, uint8_t width, bool be) {
#if RADIOLIB_DEBUG
size_t rem_len = len;
for(size_t i = 0; i < len; i+=16) {
char str[120];
sprintf(str, "%08" PRIx32 ": ", (uint32_t)i+offset);
size_t line_len = 16;
if(rem_len < line_len) {
line_len = rem_len;
}
for(size_t j = 0; j < line_len; j+=width) {
if(width > 1) {
int m = 0;
int step = width/2;
if(be) {
step *= -1;
}
for(int32_t k = width - 1; k >= -width + 1; k+=step) {
sprintf(&str[10 + (j+m)*3], "%02x ", data[i+j+k+m]);
m++;
}
} else {
sprintf(&str[10 + (j)*3], "%02x ", data[i+j]);
}
}
for(size_t j = line_len; j < 16; j++) {
sprintf(&str[10 + j*3], " ");
}
str[58] = ' ';
// at this point we need to start escaping "%" characters
char* strPtr = &str[59];
for(size_t j = 0; j < line_len; j++) {
char c = data[i+j];
if((c < ' ') || (c > '~')) {
c = '.';
} else if(c == '%') {
*strPtr++ = '%';
}
sprintf(strPtr++, "%c", c);
}
for(size_t j = line_len; j < 16; j++) {
sprintf(strPtr++, " ");
}
if(level) {
RADIOLIB_DEBUG_PRINT(level);
}
RADIOLIB_DEBUG_PRINT(str);
RADIOLIB_DEBUG_PRINTLN();
rem_len -= 16;
}
#else
// outside of debug, this does nothing
(void)level;
(void)data;
(void)len;
(void)offset;
(void)width;
(void)be;
#endif
}
#if RADIOLIB_DEBUG && defined(RADIOLIB_BUILD_ARDUINO)
// https://github.com/esp8266/Arduino/blob/65579d29081cb8501e4d7f786747bf12e7b37da2/cores/esp8266/Print.cpp#L50
size_t rlb_printf(const char* format, ...) {
va_list arg;
va_start(arg, format);
char temp[64];
char* buffer = temp;
size_t len = vsnprintf(temp, sizeof(temp), format, arg);
va_end(arg);
if (len > sizeof(temp) - 1) {
buffer = new char[len + 1];
if (!buffer) {
return 0;
}
va_start(arg, format);
vsnprintf(buffer, len + 1, format, arg);
va_end(arg);
}
len = RADIOLIB_DEBUG_PORT.write(reinterpret_cast<const uint8_t*>(buffer), len);
if (buffer != temp) {
delete[] buffer;
}
return len;
}
#endif
+42
View File
@@ -0,0 +1,42 @@
#if !defined(_RADIOLIB_UTILS_H)
#define _RADIOLIB_UTILS_H
#include <stdint.h>
#include <stdlib.h>
#include "../BuildOpt.h"
// macros to access bits in byte array, from http://www.mathcs.emory.edu/~cheung/Courses/255/Syllabus/1-C-intro/bit-array.html
#define SET_BIT_IN_ARRAY_MSB(A, k) ( A[((k)/8)] |= (1 << ((k)%8)) )
#define CLEAR_BIT_IN_ARRAY_MSB(A, k) ( A[((k)/8)] &= ~(1 << ((k)%8)) )
#define TEST_BIT_IN_ARRAY_MSB(A, k) ( A[((k)/8)] & (1 << ((k)%8)) )
#define GET_BIT_IN_ARRAY_MSB(A, k) ( (A[((k)/8)] & (1 << ((k)%8))) ? 1 : 0 )
#define SET_BIT_IN_ARRAY_LSB(A, k) ( A[((k)/8)] |= (1 << (7 - ((k)%8))) )
#define CLEAR_BIT_IN_ARRAY_LSB(A, k) ( A[((k)/8)] &= ~(1 << (7 - ((k)%8))) )
#define TEST_BIT_IN_ARRAY_LSB(A, k) ( A[((k)/8)] & (1 << (7 - ((k)%8))) )
#define GET_BIT_IN_ARRAY_LSB(A, k) ( (A[((k)/8)] & (1 << (7 - ((k)%8)))) ? 1 : 0 )
/*!
\brief Function to reflect bits within a byte.
\param in The input to reflect.
\param bits Number of bits to reflect.
\return The reflected input.
*/
uint32_t rlb_reflect(uint32_t in, uint8_t bits);
/*!
\brief Function to dump data as hex into the debug port.
\param level RadioLib debug level, set to NULL to not print.
\param data Data to dump.
\param len Number of bytes to dump.
\param offset Address offset to add when printing the data.
\param width Word width (1 for uint8_t, 2 for uint16_t, 4 for uint32_t).
\param be Print multi-byte data as big endian. Defaults to false.
*/
void rlb_hexdump(const char* level, uint8_t* data, size_t len, uint32_t offset = 0, uint8_t width = 1, bool be = false);
#if RADIOLIB_DEBUG && defined(RADIOLIB_BUILD_ARDUINO)
size_t rlb_printf(const char* format, ...);
#endif
#endif