Skip to content

Commit 6ca17c1

Browse files
dpgeorgepfalcon
authored andcommitted
esp8266: Implement os.urandom function.
Uses what is suspected to be a hardware random number generator.
1 parent b4070ee commit 6ca17c1

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

esp8266/etshal.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33

44
#include <os_type.h>
55

6+
// see http://esp8266-re.foogod.com/wiki/Random_Number_Generator
7+
#define WDEV_HWRNG ((volatile uint32_t*)0x3ff20e44)
8+
69
void ets_delay_us();
710
void ets_intr_lock(void);
811
void ets_intr_unlock(void);

esp8266/moduos.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
#include "py/objstr.h"
3535
#include "py/runtime.h"
3636
#include "genhdr/mpversion.h"
37+
#include "etshal.h"
3738
#include "user_interface.h"
3839

3940
extern const mp_obj_type_t mp_fat_vfs_type;
@@ -92,9 +93,21 @@ STATIC mp_obj_t os_remove(mp_obj_t path_in) {
9293
STATIC MP_DEFINE_CONST_FUN_OBJ_1(os_remove_obj, os_remove);
9394
#endif
9495

96+
STATIC mp_obj_t os_urandom(mp_obj_t num) {
97+
mp_int_t n = mp_obj_get_int(num);
98+
vstr_t vstr;
99+
vstr_init_len(&vstr, n);
100+
for (int i = 0; i < n; i++) {
101+
vstr.buf[i] = *WDEV_HWRNG;
102+
}
103+
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
104+
}
105+
STATIC MP_DEFINE_CONST_FUN_OBJ_1(os_urandom_obj, os_urandom);
106+
95107
STATIC const mp_rom_map_elem_t os_module_globals_table[] = {
96108
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uos) },
97109
{ MP_ROM_QSTR(MP_QSTR_uname), MP_ROM_PTR(&os_uname_obj) },
110+
{ MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&os_urandom_obj) },
98111
#if MICROPY_VFS_FAT
99112
{ MP_ROM_QSTR(MP_QSTR_VfsFat), MP_ROM_PTR(&mp_fat_vfs_type) },
100113
{ MP_ROM_QSTR(MP_QSTR_listdir), MP_ROM_PTR(&os_listdir_obj) },

0 commit comments

Comments
 (0)