modrandom.c 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 Paul Sokolovsky
  7. * Copyright (c) 2016 Damien P. George
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #include <assert.h>
  28. #include <string.h>
  29. #include "py/runtime.h"
  30. #if MICROPY_PY_RANDOM_HW_RNG
  31. #include "nrf_rng.h"
  32. #include "modrandom.h"
  33. #if BLUETOOTH_SD
  34. #include "nrf_soc.h"
  35. #include "ble_drv.h"
  36. #define BLUETOOTH_STACK_ENABLED() (ble_drv_stack_enabled())
  37. #endif
  38. static inline uint32_t generate_hw_random(void) {
  39. uint32_t retval = 0;
  40. uint8_t * p_retval = (uint8_t *)&retval;
  41. nrf_rng_event_clear(NRF_RNG_EVENT_VALRDY);
  42. nrf_rng_task_trigger(NRF_RNG_TASK_START);
  43. for (uint16_t i = 0; i < 4; i++) {
  44. while (!nrf_rng_event_get(NRF_RNG_EVENT_VALRDY)) {
  45. ;
  46. }
  47. nrf_rng_event_clear(NRF_RNG_EVENT_VALRDY);
  48. p_retval[i] = nrf_rng_random_value_get();
  49. }
  50. nrf_rng_task_trigger(NRF_RNG_TASK_STOP);
  51. return retval;
  52. }
  53. uint32_t machine_rng_generate_random_word(void) {
  54. #if BLUETOOTH_SD
  55. if (BLUETOOTH_STACK_ENABLED() == 1) {
  56. uint32_t retval = 0;
  57. uint32_t status;
  58. do {
  59. status = sd_rand_application_vector_get((uint8_t *)&retval, 4); // Extract 4 bytes
  60. } while (status != 0);
  61. return retval;
  62. }
  63. #endif
  64. return generate_hw_random();
  65. }
  66. static inline int rand30(void) {
  67. uint32_t val = machine_rng_generate_random_word();
  68. return (val & 0x3fffffff); // binary mask b00111111111111111111111111111111
  69. }
  70. static inline int randbelow(int n) {
  71. return rand30() % n;
  72. }
  73. STATIC mp_obj_t mod_random_getrandbits(mp_obj_t num_in) {
  74. int n = mp_obj_get_int(num_in);
  75. if (n > 30 || n == 0) {
  76. mp_raise_ValueError(NULL);
  77. }
  78. uint32_t mask = ~0;
  79. // Beware of C undefined behavior when shifting by >= than bit size
  80. mask >>= (32 - n);
  81. return mp_obj_new_int_from_uint(rand30() & mask);
  82. }
  83. STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_random_getrandbits_obj, mod_random_getrandbits);
  84. STATIC mp_obj_t mod_random_randrange(size_t n_args, const mp_obj_t *args) {
  85. mp_int_t start = mp_obj_get_int(args[0]);
  86. if (n_args == 1) {
  87. // range(stop)
  88. if (start > 0) {
  89. return mp_obj_new_int(randbelow(start));
  90. } else {
  91. mp_raise_ValueError(NULL);
  92. }
  93. } else {
  94. mp_int_t stop = mp_obj_get_int(args[1]);
  95. if (n_args == 2) {
  96. // range(start, stop)
  97. if (start < stop) {
  98. return mp_obj_new_int(start + randbelow(stop - start));
  99. } else {
  100. mp_raise_ValueError(NULL);
  101. }
  102. } else {
  103. // range(start, stop, step)
  104. mp_int_t step = mp_obj_get_int(args[2]);
  105. mp_int_t n;
  106. if (step > 0) {
  107. n = (stop - start + step - 1) / step;
  108. } else if (step < 0) {
  109. n = (stop - start + step + 1) / step;
  110. } else {
  111. mp_raise_ValueError(NULL);
  112. }
  113. if (n > 0) {
  114. return mp_obj_new_int(start + step * randbelow(n));
  115. } else {
  116. mp_raise_ValueError(NULL);
  117. }
  118. }
  119. }
  120. }
  121. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_random_randrange_obj, 1, 3, mod_random_randrange);
  122. STATIC mp_obj_t mod_random_randint(mp_obj_t a_in, mp_obj_t b_in) {
  123. mp_int_t a = mp_obj_get_int(a_in);
  124. mp_int_t b = mp_obj_get_int(b_in);
  125. if (a <= b) {
  126. return mp_obj_new_int(a + randbelow(b - a + 1));
  127. } else {
  128. mp_raise_ValueError(NULL);
  129. }
  130. }
  131. STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_random_randint_obj, mod_random_randint);
  132. STATIC mp_obj_t mod_random_choice(mp_obj_t seq) {
  133. mp_int_t len = mp_obj_get_int(mp_obj_len(seq));
  134. if (len > 0) {
  135. return mp_obj_subscr(seq, mp_obj_new_int(randbelow(len)), MP_OBJ_SENTINEL);
  136. } else {
  137. nlr_raise(mp_obj_new_exception(&mp_type_IndexError));
  138. }
  139. }
  140. STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_random_choice_obj, mod_random_choice);
  141. #if MICROPY_PY_BUILTINS_FLOAT
  142. // returns a number in the range [0..1) using RNG to fill in the fraction bits
  143. STATIC mp_float_t randfloat(void) {
  144. #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
  145. typedef uint64_t mp_float_int_t;
  146. #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
  147. typedef uint32_t mp_float_int_t;
  148. #endif
  149. union {
  150. mp_float_t f;
  151. #if MP_ENDIANNESS_LITTLE
  152. struct { mp_float_int_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p;
  153. #else
  154. struct { mp_float_int_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p;
  155. #endif
  156. } u;
  157. u.p.sgn = 0;
  158. u.p.exp = (1 << (MP_FLOAT_EXP_BITS - 1)) - 1;
  159. if (MP_FLOAT_FRAC_BITS <= 30) {
  160. u.p.frc = rand30();
  161. } else {
  162. u.p.frc = ((uint64_t)rand30() << 30) | (uint64_t)rand30();
  163. }
  164. return u.f - 1;
  165. }
  166. STATIC mp_obj_t mod_random_random(void) {
  167. return mp_obj_new_float(randfloat());
  168. }
  169. STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_random_random_obj, mod_random_random);
  170. STATIC mp_obj_t mod_random_uniform(mp_obj_t a_in, mp_obj_t b_in) {
  171. mp_float_t a = mp_obj_get_float(a_in);
  172. mp_float_t b = mp_obj_get_float(b_in);
  173. return mp_obj_new_float(a + (b - a) * randfloat());
  174. }
  175. STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_random_uniform_obj, mod_random_uniform);
  176. #endif
  177. STATIC const mp_rom_map_elem_t mp_module_random_globals_table[] = {
  178. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_random) },
  179. { MP_ROM_QSTR(MP_QSTR_getrandbits), MP_ROM_PTR(&mod_random_getrandbits_obj) },
  180. { MP_ROM_QSTR(MP_QSTR_randrange), MP_ROM_PTR(&mod_random_randrange_obj) },
  181. { MP_ROM_QSTR(MP_QSTR_randint), MP_ROM_PTR(&mod_random_randint_obj) },
  182. { MP_ROM_QSTR(MP_QSTR_choice), MP_ROM_PTR(&mod_random_choice_obj) },
  183. #if MICROPY_PY_BUILTINS_FLOAT
  184. { MP_ROM_QSTR(MP_QSTR_random), MP_ROM_PTR(&mod_random_random_obj) },
  185. { MP_ROM_QSTR(MP_QSTR_uniform), MP_ROM_PTR(&mod_random_uniform_obj) },
  186. #endif
  187. };
  188. STATIC MP_DEFINE_CONST_DICT(mp_module_random_globals, mp_module_random_globals_table);
  189. const mp_obj_module_t random_module = {
  190. .base = { &mp_type_module },
  191. .globals = (mp_obj_dict_t*)&mp_module_random_globals,
  192. };
  193. #endif // MICROPY_PY_RANDOM_HW_RNG