Skip to content

Commit 350e88d

Browse files
authored
Merge pull request #3324 from hierophect/esp32-random
Add random to ESP32-S2, fix it on STM32
2 parents 6100027 + a15f948 commit 350e88d

File tree

3 files changed

+22
-8
lines changed

3 files changed

+22
-8
lines changed

ports/esp32s2/common-hal/os/__init__.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
#include "py/objtuple.h"
3131
#include "py/qstr.h"
3232

33+
#include "esp_system.h"
34+
3335
STATIC const qstr os_uname_info_fields[] = {
3436
MP_QSTR_sysname, MP_QSTR_nodename,
3537
MP_QSTR_release, MP_QSTR_version, MP_QSTR_machine
@@ -57,5 +59,15 @@ mp_obj_t common_hal_os_uname(void) {
5759
}
5860

5961
bool common_hal_os_urandom(uint8_t* buffer, uint32_t length) {
60-
return false;
62+
uint32_t i = 0;
63+
while (i < length) {
64+
uint32_t new_random = esp_random();
65+
for (int j = 0; j < 4 && i < length; j++) {
66+
buffer[i] = new_random & 0xff;
67+
i++;
68+
new_random >>= 8;
69+
}
70+
}
71+
72+
return true;
6173
}

ports/esp32s2/mpconfigport.mk

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@ CIRCUITPY_COUNTIO = 0
2525

2626
# These modules are implemented in shared-module/ - they can be included in
2727
# any port once their prerequisites in common-hal are complete.
28-
# Requires OS
29-
CIRCUITPY_RANDOM = 0
3028
# Requires USB
3129
CIRCUITPY_USB_MIDI = 0
3230
# Too large for the partition table!

ports/stm/common-hal/os/__init__.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,20 @@ bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) {
7272
if (HAL_RNG_Init(&handle) != HAL_OK) mp_raise_ValueError(translate("RNG Init Error"));
7373

7474
//Assign bytes
75-
for (uint i = 0; i < length; i++) {
76-
uint32_t temp;
75+
uint32_t i = 0;
76+
while (i < length) {
77+
uint32_t new_random;
7778
uint32_t start = HAL_GetTick();
7879
//the HAL function has a timeout, but it isn't long enough, and isn't adjustable
7980
while(!(__HAL_RNG_GET_FLAG(&handle,RNG_FLAG_DRDY)) && ((HAL_GetTick() - start) < RNG_TIMEOUT));
80-
//
81-
if (HAL_RNG_GenerateRandomNumber(&handle, &temp) != HAL_OK) {
81+
if (HAL_RNG_GenerateRandomNumber(&handle, &new_random) != HAL_OK) {
8282
mp_raise_ValueError(translate("Random number generation error"));
8383
}
84-
*buffer = (uint8_t)temp;
84+
for (int j = 0; j < 4 && i < length; j++) {
85+
buffer[i] = new_random & 0xff;
86+
i++;
87+
new_random >>= 8;
88+
}
8589
}
8690

8791
//shut down the peripheral

0 commit comments

Comments
 (0)