diff --git a/src/protocols/PhysicalLayer/PhysicalLayer.cpp b/src/protocols/PhysicalLayer/PhysicalLayer.cpp index b0174c51..b30a0cf9 100644 --- a/src/protocols/PhysicalLayer/PhysicalLayer.cpp +++ b/src/protocols/PhysicalLayer/PhysicalLayer.cpp @@ -143,3 +143,27 @@ int16_t PhysicalLayer::receive(String& str, size_t len) { float PhysicalLayer::getFreqStep() const { return(_freqStep); } + +int32_t PhysicalLayer::random(int32_t max) { + if(max == 0) { + return(0); + } + + // get random bytes from the radio + uint8_t randBuff[4]; + for(uint8_t i = 0; i < 4; i++) { + randBuff[i] = random(); + } + + // create 32-bit TRNG number + int32_t randNum = ((int32_t)randBuff[0] << 24) | ((int32_t)randBuff[1] << 16) | ((int32_t)randBuff[2] << 8) | ((int32_t)randBuff[3]); + return(randNum % max); +} + +int32_t PhysicalLayer::random(int32_t min, int32_t max) { + if(min >= max) { + return(min); + } + + return(PhysicalLayer::random(max - min) + min); +} diff --git a/src/protocols/PhysicalLayer/PhysicalLayer.h b/src/protocols/PhysicalLayer/PhysicalLayer.h index 11bfb490..d817fbcc 100644 --- a/src/protocols/PhysicalLayer/PhysicalLayer.h +++ b/src/protocols/PhysicalLayer/PhysicalLayer.h @@ -216,7 +216,7 @@ class PhysicalLayer { float getFreqStep() const; /*! - \brief Query modem for the packet length of received payload. + \brief Query modem for the packet length of received payload. Must be implemented in module class. \param update Update received packet length. Will return cached value when set to false. @@ -224,6 +224,33 @@ class PhysicalLayer { */ virtual size_t getPacketLength(bool update = true) = 0; + /*! + \brief Get truly random number in range 0 - max. + + \param max The maximum value of the random number (non-inclusive). + + \returns Random number. + */ + int32_t random(int32_t max); + + /*! + \brief Get truly random number in range min - max. + + \param min The minimum value of the random number (inclusive). + + \param max The maximum value of the random number (non-inclusive). + + \returns Random number. + */ + int32_t random(int32_t min, int32_t max); + + /*! + \brief Get one truly random byte from RSSI noise. Must be implemented in module class. + + \returns TRNG byte. + */ + virtual uint8_t random() = 0; + #ifndef RADIOLIB_GODMODE private: #endif