126 lines
3.3 KiB
C++

#include "Sx1262.h"
#include <cstring>
constexpr const char* TAG = "LoraDevice";
bool Sx1262::configure(const Parameter parameter, const float value) {
using enum Parameter;
switch (parameter) {
case Power:
power = value;
return true;
case Frequency:
frequency = value;
return true;
case Bandwidth:
bandwidth = value;
return true;
case SpreadFactor:
spreadFactor = value;
return true;
case CodingRate:
codingRate = value;
return true;
case SyncWord:
syncWord = value;
return true;
case PreambleLength:
preambleLength = value;
return true;
case DataRate:
bitRate = value;
return true;
case FrequencyDeviation:
frequencyDeviation = value;
return true;
default:
break;
}
return false;
}
void Sx1262::onReceive() {
getEventFlag().set(RADIO_RECEIVED_BIT);
}
int32_t Sx1262::threadMain(const Modulation modulation) {
uint16_t rc = RADIOLIB_ERR_NONE;
if (modulation == Modulation::LoRa) {
rc = radio.begin(
frequency,
bandwidth,
spreadFactor,
codingRate,
syncWord,
power,
preambleLength,
configuration.tcxoVoltage,
configuration.useRegulatorLdo
);
} else if (modulation == Modulation::Fsk) {
rc = radio.beginFSK(
frequency,
bitRate,
frequencyDeviation,
bandwidth,
power,
preambleLength,
configuration.tcxoVoltage,
configuration.useRegulatorLdo
);
} else {
TT_LOG_E(TAG, "SX1262 not capable of modulation \"%s\"", toString(modulation));
setState(State::Error);
return -1;
}
if (rc != RADIOLIB_ERR_NONE) {
TT_LOG_E(TAG, "Radiolib init failed with code %hi", rc);
setState(State::Error);
return -1;
}
setState(State::On);
TT_LOG_I(TAG, "SX1262 device ready to receive!");
while (!isThreadInterrupted()) {
radio.startReceive();
getEventFlag().wait(RADIO_TERMINATE_BIT, RADIO_RECEIVED_BIT);
// Thread might've been interrupted in the meanwhile
if (isThreadInterrupted()) {
break;
}
uint16_t rxSize = radio.getPacketLength(true);
uint8_t *dataBuffer = new uint8_t[rxSize];
uint16_t rc = radio.readData(dataBuffer, rxSize);
if (rc != RADIOLIB_ERR_NONE) {
TT_LOG_E(TAG, "Error receiving data, RadioLib returned %hi", rc);
} else {
float rssi = radio.getRSSI();
float snr = radio.getSNR();
TT_LOG_I(TAG, "LoRa RX size=%d RSSI=%f SNR=%f", rxSize, rssi, snr);
std::string message((char*)dataBuffer, rxSize);
TT_LOG_I(TAG, "msg=%s", message.c_str());
auto rxPacket = tt::hal::radio::RxPacket {
.data = dataBuffer,
.size = rxSize,
.rssi = rssi,
.snr = snr
};
publishRx(rxPacket);
}
delete[] dataBuffer;
}
return 0;
}