From 1d762d46251244e6ac728ad1b80afcf3a03d43ad Mon Sep 17 00:00:00 2001 From: Franz Pletz <fpletz@fnordicwalking.de> Date: Wed, 21 Aug 2019 22:12:18 +0200 Subject: [PATCH] feat(pycardium): add trng module --- pycardium/meson.build | 1 + pycardium/modules/qstrdefs.h | 4 ++++ pycardium/modules/trng.c | 31 +++++++++++++++++++++++++++++++ pycardium/mpconfigport.h | 1 + 4 files changed, 37 insertions(+) create mode 100644 pycardium/modules/trng.c diff --git a/pycardium/meson.build b/pycardium/meson.build index 40fabde70..eb99562bb 100644 --- a/pycardium/meson.build +++ b/pycardium/meson.build @@ -11,6 +11,7 @@ modsrc = files( 'modules/os.c', 'modules/personal_state.c', 'modules/sys_display.c', + 'modules/trng.c', 'modules/utime.c', 'modules/vibra.c', ) diff --git a/pycardium/modules/qstrdefs.h b/pycardium/modules/qstrdefs.h index f78afd25e..57913108c 100644 --- a/pycardium/modules/qstrdefs.h +++ b/pycardium/modules/qstrdefs.h @@ -54,6 +54,10 @@ Q(set_unix_time) Q(vibra) Q(vibrate) +/* trng */ +Q(trng) +Q(getrandbytes) + Q(set_callback) Q(enable_callback) Q(disable_callback) diff --git a/pycardium/modules/trng.c b/pycardium/modules/trng.c new file mode 100644 index 000000000..036c5320e --- /dev/null +++ b/pycardium/modules/trng.c @@ -0,0 +1,31 @@ +#include "epicardium.h" + +#include "py/builtin.h" +#include "py/obj.h" +#include "py/runtime.h" + +static mp_obj_t mp_trng_getrandbytes(mp_obj_t n) +{ + size_t amount = mp_obj_get_int(n); + uint8_t randbytes[amount]; + epic_trng_read(randbytes, amount); + return mp_obj_new_bytearray_by_ref(amount, randbytes); +} +static MP_DEFINE_CONST_FUN_OBJ_1(trng_getrandbytes_obj, mp_trng_getrandbytes); + +static const mp_rom_map_elem_t trng_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_trng) }, + { MP_ROM_QSTR(MP_QSTR_getrandbytes), + MP_ROM_PTR(&trng_getrandbytes_obj) }, +}; +static MP_DEFINE_CONST_DICT(trng_module_globals, trng_module_globals_table); + +// Define module object. +const mp_obj_module_t trng_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&trng_module_globals, +}; + +/* Register the module to make it available in Python */ +/* clang-format off */ +MP_REGISTER_MODULE(MP_QSTR_trng, trng_module, MODULE_TRNG_ENABLED); diff --git a/pycardium/mpconfigport.h b/pycardium/mpconfigport.h index a1c88a747..1fdaa0f48 100644 --- a/pycardium/mpconfigport.h +++ b/pycardium/mpconfigport.h @@ -55,6 +55,7 @@ int mp_hal_trng_read_int(void); #define MODULE_PERSONAL_STATE_ENABLED (1) #define MODULE_UTIME_ENABLED (1) #define MODULE_VIBRA_ENABLED (1) +#define MODULE_TRNG_ENABLED (1) /* * This port is intended to be 32-bit, but unfortunately, int32_t for -- GitLab