def generate_key(x: [bytearray, bytes, int], seed=None) -> [None, bytearray]: # Pseudorandomly generates len(x) or x bytes. # 32 bits is the maximum amount of bits that can be returned by urandom.getrandbits, as per: # https://github.com/micropython/micropython/blob/84fa3312cfa7d2237d4b56952f2cd6e3591210c4/extmod/modurandom.c#L76 try: key_size = len(x) buf = x return_buf = False except TypeError: key_size = x buf = bytearray(key_size) return_buf = True if seed is not None: urandom.seed(seed) q, r = divmod(key_size, 4) # 32 bits == 4 bytes if r: if r == 3: ustruct.pack_into('>HB', buf, 0, urandom.getrandbits(16), urandom.getrandbits(8)) else: ustruct.pack_into('>H' if r == 2 else '>B', buf, 0, urandom.getrandbits(8 * r)) while q: ustruct.pack_into('>I', buf, 4 * (q - 1) + r, urandom.getrandbits(32)) q -= 1 if return_buf: return buf
def __init__(self, base, size, name_list): """ creates in-object object list of addresses + sizes. """ # remember random generator state (missing in uPy) try: rand_stat = urandom.getstate() except AttributeError: rand_stat = None urandom.seed(RANDOM_SEED) try: self._base = base self._name_map = {} addr = self._base # print("len name_list", len(name_list)) for i in range(0, len(name_list), 2): name = name_list[i] size = name_list[i + 1] # print(i, name, size) if not isinstance(size, int): raise ValueError # ("expected int address, not " + str(type(size))) self._name_map[name] = MemMap.MemDesc(addr, size, urandom.getrandbits(32)) addr += size finally: if rand_stat: urandom.setstate(rand_stat) pass
def add_line(self): # Move lines up for row in range(self.game_height - 1): for col in range(self.game_width): self.field[row][col] = self.field[row + 1][col] self.draw() if self.multiplayer_lines == self.MULTIPLAYER_LINES_SURVIVOR: # Temporary draw lines in color "added line" for .5 seconds for col in range(self.game_width): self.draw_pixel(self.game_height - 1, col, self.game_color_addedline) rgb.frame(self.frame) time.sleep(.5) # Add the blocked line self.game_blockedlines += 1 for col in range(self.game_width): self.field[self.game_height - 1][col] = True elif self.multiplayer_lines == self.MULTIPLAYER_LINES_RANDOM: # pick a random hole in the line urandom.seed(time.ticks_ms()) random_hole = urandom.getrandbits(8) % self.game_width # Temporary draw lines in color "added line" for .5 seconds for col in range(self.game_width): color = self.game_color_addedline if col != random_hole else self.game_color_background self.draw_pixel(self.game_height - 1, col, color) rgb.frame(self.frame) time.sleep(.5) for col in range(self.game_width): self.field[self.game_height - 1][col] = col != random_hole
def spawn_new_piece(self): self.piece_current = self.piece_next urandom.seed(time.ticks_ms()) self.piece_next = urandom.getrandbits(8) % 7 # self.piece_current = 1 self.piece_x = 4 self.piece_y = 0 self.piece_rot = 0
def randint(min, max, seed=None): if seed is not None: urandom.seed(seed) span = max - min + 1 div = 0x3fffffff // span offset = urandom.getrandbits(30) // div val = min + offset return val
def setup(): # fingers corssed, the seeding makes sense to really get random colors... apin = AnalogIn(analog_input) random.seed(apin.value) apin.deinit() # let's go! nextcolor() strip.write()
def random_string(length=8): #Generate a random string of fixed length _randomstring = '' x = 0 #add random seed seconds of localtime seed(localtime()[5]) while x < length: _randomstring = _randomstring + choice( 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890') x += 1 return _randomstring
def _uuid_bytes(): _random.seed(round(_time.time() * 1000)) values = ( _random.getrandbits(32), _random.getrandbits(32), _random.getrandbits(32), _random.getrandbits(32), ) return _struct.pack("IIII", *values)
def __init__(self): self.ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12 self.ow.scan() # return a list of devices on the bus self.ow.reset() # reset the bus self.ds = ds18x20.DS18X20(self.ow) self.rtc = machine.RTC() self.rtc.irq(trigger=self.rtc.ALARM0, wake=machine.DEEPSLEEP) self.led = Pin(2, Pin.OUT) self.led.on() # led is inverted # seeding prng t1 = utime.ticks_cpu() self.get_temp() t2 = utime.ticks_cpu() urandom.seed(t2 - t1)
def main(): ''' Main entry point ''' driver = LEDBTN() game = Simon(driver) print('Welcome Lights') game.welcome() while True: # Wait for keypress to start game driver.get_pressed() print('Game Start') game.fail_game() urandom.seed(time.ticks_cpu()) game.game_loop() print("Game finished, starting new game")
def game_setup(i2c, oled): # wait until the user touches the proximity sensor # get the seed to start the random sequence (light) = bootstrap( i2c, oled ) # Enables the proximity and ambient light sensors and returns a reading from the ambient light sensor random.seed( light ) # The ambient light reading is used as a random seed to initialise the generator oled.text('Seed: ' + str(light), 0, 10) oled.text('Hover over ', 25, 30) oled.text('sensor to start', 5, 40) oled.show() # time.sleep(2) results = results_init( ) # Array of 90 locations to accomodate the generated numbers ctr = 0 # Measures the number of samples stored in the array. return (light, results, ctr, oled)
def __init__(self, pin=5): random_number = None try: urandom.seed(int(open('seed_file', 'r').read())) finally: file = open('seed_file', 'w') random_number = urandom.getrandbits(20) file.write(str(random_number)) file.close() self.temp_pin = pin self.data = { 'temp': None, 'id': random_number, } self.__setup_pin() self.__setup_wifi()
def setup(): global fade # Random number generator is seeded from an unused 'floating' # analog input - this helps ensure the random color choices # aren't always the same order. pin = AnalogIn(board.A0) random.seed(pin.value) pin.deinit() for he in range(n_horns): for wi in range(n_waves): random_wave(he, wi) fade = 233 + n_leds / 2 if fade > 233: fade = 233
def game_init(self): # Init game state self.game_step_time = self.game_default_step_time self.game_won = False self.game_over = False urandom.seed(time.ticks_ms()) self.piece_next = urandom.getrandbits(8) % 7 rgb.clear rgb.disablecomp() for i in range(256): self.frame[i] = 0 self.spawn_new_piece() self.field = [[0 for i in range(self.game_width)] for j in range(self.game_height)] self.last_update = time.ticks_ms() self.score = 0 self.game_blockedlines = 0
def adhan(sidx): global _stopadhan _stopadhan = False wbutton.irq(irq_stop_adhan, Pin.IRQ_FALLING, machine.SLEEP | machine.DEEPSLEEP) print('Adhan %s' % SALATS[sidx]) led.value(1) if sidx == 1: #chorok : beep only player.volume(30) player.say_salat_name(1) return urandom.seed(time.mktime(localtime())) # RNG needs some heetup to get a good enough quality for k in range(1, 10): urandom.random() player.wakeup() player.volume(sdb.getsvolume(sidx)) if sidx == 0: #Fajr special ringing for i in range(1, 17): led.value(1) time.sleep_ms(100) led.value(0) if _stopadhan: return time.sleep_ms(300 if i % 4 == 0 else 50) led.value(1) player.play_adhan(FAJR_ADHAN_FOLDER) else: for i in range(0, sidx): led.value(1) time.sleep_ms(100) led.value(0) if _stopadhan: return time.sleep_ms(500) led.value(1) _, _, _, h, mi, _, _, _ = localtime() player.say_current_time(h, mi) time.sleep_ms(500) player.play_adhan(ALL_ADHAN_FOLDER)
def __init__(self, topic=None, server="broker.hivemq.com", client=None, callback=None, check_msg=False): conectar_wifi() urandom.seed(ADC(0).read()) self.server = server self.id_client = str( urandom.getrandbits(18)) if client is None else client self.topic = topic self.client = MQTTClient(self.id_client, self.server) self.client.set_callback( self.callback_msg if callback is None else callback) self.client.connect() self.check_msg = check_msg self.timer = Timer(-1) self.timer.init(period=1000, mode=Timer.PERIODIC, callback=self.timer_check_msg)
frame[frame_y][x] = int(row[x]) frame_y = frame_y + 1 if frame_y == size_y: #render_error('render', 'screen') draw_blinken_screen() utime.sleep_ms(frame_duration * 0.7) clear_frame() frame_y = 0 f.close() def play_all_files(): files = os.listdir('.') for file in files: if (file[-4:] == '.blm'): render_error('file:', file[:-4]) play_blinken_blm_file(file) def play_all_files_random_order(): files = os.listdir('.') # print(files) file = choice(files) if (file[-4:] == '.blm'): #vibra.vibrate(60) render_error('file:', file[:-4]) play_blinken_blm_file(file) #render_error('hello', 'world') seed(light_sensor.get_reading()) while True: play_all_files_random_order() # play_blinken_blm_file("ask_for_bombs.blm")
cooldown_at = 2.0 # After this many seconds, start slowing down dim_at = 2.5 # After this many seconds, dim LEDs brightness_high = 0.5 # Active brightness brightness_low = 0.125 # Idle brightness color = [0, 120, 30] # Initial LED color offset = 0 # Animation position frame_len = default_frame_len # Frame-to-frame time, seconds last_vibration = 0.0 # Time of last vibration last_frame = 0.0 # Time of last animation frame # Random number generator is seeded from an unused 'floating' # analog input - this helps ensure the random color choices # aren't always the same order. pin = analogio.AnalogIn(analog_pin) random.seed(pin.value) pin.deinit() # Set up digital pin for reading vibration switch pin = digitalio.DigitalInOut(vibration_pin) pin.direction = digitalio.Direction.INPUT pin.pull = digitalio.Pull.UP while True: # Loop forever... while True: # Compare time.monotonic() against last_frame to keep # frame-to-frame animation timing consistent. Use this # idle time to check the vibration switch for activity. t = time.monotonic() if t - last_frame >= frame_len:
# horo_main.py version = '1.0' import network, time import ubinascii import urandom urandom.seed(time.time()) from machine import unique_id, Pin, I2C, Timer, reset from micropython import schedule import os import sys import hashlib import micropython micropython.alloc_emergency_exception_buf(100) uid = unique_id() HEADER = 'horo-1.0m' AP_ESSID = "horo-%02x%02x" % (uid[-2], uid[-1]) AP_AUTHMODE = 3 AP_PASSW = '' WEBREPL_PASSW = '1234' help_dict = {'epd_type': 'M5'} # prepare for global oled = None timer = None wlan = None sta = None PASS = None info = {}
# Conway's Game of Life on 128x64 SSD1306 OLED and ESP8266 (by Alan Wang) # game rule B = "3" # number of nearby cells to give birth of a new cell S = "23" # number of nearby cells to sustain an existing cell matrix_factor = 3 # matrix factor (3 -> 128/3 x 64/3 -> 42 x 21) random_bit_num = 2 # initial randomize factor (2 = 2^2 (1/4 chance)) # ------------------------------------------------------------ import urandom, gc from machine import Pin, I2C, ADC, freq from ssd1306 import SSD1306_I2C freq(160000000) urandom.seed(ADC(0).read()) # randomize seed from floating analog readings B_list = list(map(int, B)) S_list = list(map(int, S)) matrix_size_x = int(128 / matrix_factor) matrix_size_y = int(64 / matrix_factor) matrix = [bytearray(1 if urandom.getrandbits(random_bit_num) == 0 else 0 for _ in range(matrix_size_y)) for _ in range(matrix_size_x)] # calculate next generation def calculate_next_gen(): global matrix matrix_buf = [bytearray(0 for _ in range(matrix_size_y))
BIRTH = (3, ) # number of nearby cells for a new cell to be born SURVIVAL = (2, 3) # number of nearby cells for an existing cell to survive WIDTH = 128 HEIGHT = 64 DOT_SIZE = 3 # draw 3x3 dots -> board size 128/3 x 64/3 RAND_BIT = 2 # cell randomize factor (2 = 2^2 (1/4 chance)) from machine import Pin, ADC, SoftI2C, freq from micropython import const from ssd1306 import SSD1306_I2C import urandom, utime, gc freq(160000000) gc.enable() urandom.seed(sum([ADC(0).read() for _ in range(1000) ])) # generate randomize seed from floating analog pin X = WIDTH // DOT_SIZE Y = HEIGHT // DOT_SIZE TOTAL = X * Y board = [0 if urandom.getrandbits(RAND_BIT) else 1 for _ in range(TOTAL)] gen = 0 display = SSD1306_I2C(WIDTH, HEIGHT, SoftI2C(scl=Pin(5), sda=Pin(4), freq=400000)) display.fill(0) display.show() print('Conway\'s Game of Life: matrix size {} x {}'.format(X, Y))
import urandom, utime, gc, _thread from machine import Pin, ADC, I2C from micropython import const from ssd1306 import SSD1306_I2C # https://github.com/stlehmann/micropython-ssd1306 gc.enable() urandom.seed(sum([ADC(2).read_u16() for _ in range(1000)])) BIRTH = (3, ) SURVIVAL = (2, 3) WIDTH = const(128) HEIGHT = const(64) DOT_SIZE = const(3) RAND_PCT = const(25) SCL_PIN = const(27) SDA_PIN = const(26) X = WIDTH // DOT_SIZE Y = HEIGHT // DOT_SIZE TOTAL = X * Y board = bytearray([ 0 if urandom.randint(0, (100 // RAND_PCT) - 1) else 1 for _ in range(TOTAL) ]) buffer = bytearray([]) task = [] gen = 0 display = SSD1306_I2C(WIDTH, HEIGHT, I2C(1, scl=Pin(SCL_PIN), sda=Pin(SDA_PIN), freq=400000)) display.fill(0) display.show()
# # neopixcel test programn 2017-06-03 # CC0:No rights reserved # ハートの鼓動をイメージして色を変化させる # from machine import Pin from neopixel import NeoPixel from time import * import urandom urandom.seed(2017) pin = Pin(4,Pin.OUT) # NeoPixel data port np = NeoPixel(pin, 5) # use 5 NeoPixels def test(pw, t, bia): for i in range(pw): np.fill([i, pw-i, bia]) np.write() sleep(t) for i in range(pw): np.fill([pw-i, bia, i]) np.write() sleep(t) for i in range(pw): np.fill([bia, i, pw-i]) np.write() sleep(t) while True: test(100,0.01,urandom.getrandbits(6))
def rand(max): utime.sleep(0.001) urandom.seed(int(utime.ticks_ms())) return int(urandom.getrandbits(8) * max / 255)
# random number generator # if os.urandom is available - entropy goes from TRNG # otherwise - use whatever we have # FIXME: mix in extra entropy try: from os import urandom as get_random_bytes except: # read /dev/urandom instead? import urandom, time urandom.seed(int(time.time())) def get_random_bytes(nbytes): return bytes([urandom.getrandbits(8) for i in range(nbytes)])
from utime import ticks_ms import struct import urandom from machine import unique_id urandom.seed(struct.unpack('i', unique_id())[0] + ticks_ms()) def randint(bits=8): return urandom.getrandbits(bits)
################################################################################################## # Workaround for including frozen modules when running micropython with a script argument # https://github.com/micropython/micropython/issues/6419 import usys as sys sys.path.append('') # Imports from urandom import getrandbits, seed from utime import ticks_us from uasyncio import sleep, create_task, Loop, CancelledError import lv_utils import lvgl as lv seed(ticks_us()) lv.init() ################################################################################################## # Display initialization ################################################################################################## # Default resolution match ili9341 HOR_RES = 240 VER_RES = 320 # Try initialize ili9341/xpt2046 try: from ili9XXX import ili9341 from xpt2046 import xpt2046
try: import urandom as random except ImportError: import random # check getrandbits returns a value within the bit range for b in (1, 2, 3, 4, 16, 32): for i in range(50): assert random.getrandbits(b) < (1 << b) # check that seed(0) gives a non-zero value random.seed(0) print(random.getrandbits(16) != 0) # check that PRNG is repeatable random.seed(1) r = random.getrandbits(16) random.seed(1) print(random.getrandbits(16) == r) # check that it throws an error for zero bits try: random.getrandbits(0) except ValueError: print('ValueError')
try: import urandom as random except ImportError: try: import random except ImportError: print("SKIP") raise SystemExit # check getrandbits returns a value within the bit range for b in (1, 2, 3, 4, 16, 32): for i in range(50): assert random.getrandbits(b) < (1 << b) # check that seed(0) gives a non-zero value random.seed(0) print(random.getrandbits(16) != 0) # check that PRNG is repeatable random.seed(1) r = random.getrandbits(16) random.seed(1) print(random.getrandbits(16) == r) # check that it throws an error for zero bits try: random.getrandbits(0) except ValueError: print('ValueError')
import uasyncio as asyncio import json as json import utime as time import select from zbee.zigbee import ZigBee import gc import serial import os import crc32 import accelreader import networking from algorithms import np from algorithms import basis_pursuit as bp from algorithms import fourier_basis as ft import urandom urandom.seed(int(os.getenv("NODE_ID"))) import ujson def macrotimer(method): def timed(*args, **kw): ts = time.time() user = yield from method(*args, **kw) te = time.time() ex_time = te - ts append_record('/etc/init.d/beeview_liss/macro', { 'u': user, 't': ex_time }) return user
try: from os import urandom except ImportError: import urandom as rnd import utime rnd.seed(utime.ticks_ms()) def urandom(n): result = [] for _ in range(n): result.append(rnd.getrandbits(8)) return result
import unittest import logger import random import urandom import utime import ujson import uio import sys urandom.seed(utime.ticks_ms()) class TestJsonFormatter(unittest.TestCase): def test_format_with_msg(self): msg = 'Something is happening %d' % random.randint(10, 1000) level = 'info' now = 'time %d' % random.randint(10, 1000) want_message = ujson.dumps({ 'msg': msg, 'time': now, 'level': level, 'v': 1 }) got_message = logger.json_formatter(msg=msg, level=level, now=now) self.assertEqual(got_message, want_message) def test_format_with_data(self): msg = 'Hello' level = 'info' now = 'now' data = {