コード例 #1
0
ファイル: objects.py プロジェクト: jvdw008/pokabalt
 def __init__(self, img, startX, startY, objectType, objHeight, objWidth):
     self.x = startX
     self.type = objectType
     self.landed = False
     self.hit = False
     
     if objectType == 0:
         self.y = startY - objHeight
         self.image = img[random.getrandbits(1)]
     else:
         self.y = -objHeight
         self.image = img
         
     self.height = objHeight
     self.width = objWidth
コード例 #2
0
 def __init__(self, ble, name="covid19"):
     self._ble = ble
     self._ble.active(True)
     self._ble.irq(handler=self._irq)
     ((self._handle, ), ) = self._ble.gatts_register_services(
         (_ENV_SENSE_SERVICE, ))
     self._connections = set()
     #        name = "covid" + ubinascii.hexlify(b'~\xd8\xc6\x00').decode('utf-8')
     name = "covid" + str(urandom.getrandbits(30))
     self.name = name
     self._payload = advertising_payload(
         name=name,
         services=[_ENV_SENSE_UUID],
         appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER)
     self._advertise()
コード例 #3
0
 def update(self, sizes):
     # Move Y
     self.y += 1
     if self.ySpeed > 1:
         self.y += 1
         
     # Move X
     if self.xSpeed != 0:
         self.x += self.dir
         
     if self.y > 100:
         tmpRnd = random.getrandbits(7)
         if tmpRnd > 125:
             self.resetYPos(sizes)
             self.y = -20
コード例 #4
0
def randrange(start, stop=None):
    if stop is None:
        stop = start
        start = 0
    upper = stop - start
    bits = 0
    pwr2 = 1
    while upper > pwr2:
        pwr2 <<= 1
        bits += 1
    while True:
        r = urandom.getrandbits(bits)
        if r < upper:
            break
    return r + start
コード例 #5
0
 def cometPlacer(self, freq, group):
     """ place comets at top of screen randomly"""
     if (self.frameNum % freq) == 0:
         for s in group:
             if s.rect.y > 80:
                 s.rect.y = -10
                 x = 10 + random.getrandbits(8) * 90 // 256
                 if abs(x - self.lastX) < 7:
                     if x < self.lastX:
                         x -= 7
                     else:
                         x += 7
                 s.rect.x = x
                 self.lastX = x
                 break
コード例 #6
0
ファイル: c_qos.py プロジェクト: mbenitez01/micropython-iot
 async def writer(self):
     self.verbose and print('Started writer')
     st = time.time()
     while True:
         gc.collect()
         ut = time.time() - st  # Uptime in secs
         data = [
             self.tx_msg_id, self.cl.connects,
             gc.mem_free(), self.cm.dupe, self.cm.miss, ut
         ]
         self.tx_msg_id += 1
         print('Sent', data, 'to server app\n')
         dstr = ujson.dumps(data)
         await self.cl.write(dstr)  # Wait out any outage
         await asyncio.sleep_ms(7000 + urandom.getrandbits(10))
コード例 #7
0
ファイル: cringo.py プロジェクト: VasiliosRallis/iot-cringo
def bingo_game(i2c, client, light, ctr, results, oled):
    while BINGO != True:
        proximity = read_prox(i2c)  # Take a proximity reading
        # check from the server if there is a bingo
        client.check_msg()

        if (proximity > NEXT_THR):
            if BINGO == False:
                while True:
                    # generate a new random number
                    r = random.getrandbits(N)
                    sample = int(
                        r * pow(2, N - 1) /
                        90)  # Map the generated number in the range of 1 to 90

                    if sample == 0 or sample > 90:  # If for some reason, number is out of range
                        #ignore reading
                        print(
                            str(sample) +
                            ' is ignored. Generating another number')
                    elif results[
                            sample -
                            1] != 0:  # If the number already exists in the list ignore it
                        print('Number ' + str(sample) +
                              ' spotted again. Generating another number'
                              )  # generate another random number
                    else:
                        results[
                            sample -
                            1] = sample  # use the sample as the index of the array too (use -1 to compensaty for the zero indexing)
                        ctr = ctr + 1  # increase the counter by one
                        oled.fill(0)
                        oled.text(str(sample), 50,
                                  30)  # Print the number on the screen
                        oled.show()
                        json_string = {
                            'Seed': str(light),
                            'Counter': str(ctr),
                            'Sample': str(sample)
                        }  # Create the JSON message
                        send_data(
                            client, json_string
                        )  # Send the message to the server through the MQTT broker
                        # json_string= sample
                        # send_to_app(client,json_string)
                        break

                time.sleep(1)
コード例 #8
0
    def starburst(self,
                  pixels=range(21),
                  color=(0, 0, 255),
                  dim=0.80,
                  freq=0.05,
                  ms_pause=50):

        while True:
            for i in pixels:
                if self.pixel[i] == (0, 0, 0):
                    if freq * 100 > getrandbits(7):
                        self.pixel[i] = color
                else:
                    self.dim(i, dim)
            self.pixel.write()
            time.sleep_ms(ms_pause)
コード例 #9
0
	def _init_ap_if(self):
		self.ap_if = network.WLAN(network.AP_IF)
		self.ap_if.active(True)
		await asyncio.sleep(1) 
		self.my_ssid = self.ap_if.config('essid')
		i = 0
		for n in self.my_ssid:
			i += ord(n)
		while i!=0:
			i = i-1
			channel = urandom.getrandbits(4)
		if channel > 11:
			channel =  16 - channel
		self.my_channel = channel
		self.ap_if.config(essid=self.my_ssid, channel=self.my_channel)
		network.phy_mode(3)
コード例 #10
0
    def randomise(self):
        """
        Generate a seudo-random cells on the screen.

        Returns:
            Nothing.
        """
        size = self.size
        width = self.width
        height = self.height
        self.oled.display.fill(0)

        for x in range(0, width, size):
            for y in range(0, height, size):
                # random bit: 0 = pixel off, 1 = pixel on
                self.cell(x, y, getrandbits(1))
コード例 #11
0
 def test_continuity(self):
     # send a contnuous load for xx hours
     global r_topic, r_message
     hrs = 8
     dur = 60 * 60 * hrs
     start = time()
     i = 0
     while time() - start < dur:
         for t in test_topics:
             m = getrandstr(getrandbits(8))
             self.sender.publish(t, m)
             self.reciev.check_msg()
             #                self.assertEqual(t, r_topic)
             #                self.assertEqual(m, r_message)
             sleep_ms(200)
             print(strftime())
コード例 #12
0
    def __init__(self):
        #self.resetYPos()
        self.x = 0
        self.y = -30
        self.dir = 0
        self.maxX = 120
        self.minX = -40
        self.maxY = 90
        self.bulletShot = False  # Used in conjunction with the timer to shoot more bullets
        self.bulletTimer = 0
        self.bulletTimerMax = 0

        self.shipId = random.getrandbits(2)
        if self.shipId > 2:
            self.shipId = 2

        # Set horizontal speed
        self.xSpeed = random.getrandbits(1)

        # Set vertical if shipId > 0
        if self.shipId > 0:
            self.ySpeed = random.getrandbits(1)

            # Now set x pos
            self.x = random.getrandbits(7)
            if self.x > 55:
                self.dir = -1
            else:
                self.dir = 1

            # Sert boundaries
            if self.x > self.maxX:
                self.x = self.maxX

            if self.x < self.minX:
                self.x = self.minX

            # Bullet timer
            self.bulletTimerMax = 10

        else:
            # Now set horizontal ship
            self.y = random.getrandbits(5)
            self.dir = random.getrandbits(1)
            if self.dir == 0:
                # Move left
                self.dir = -1
                self.x = self.maxX

            else:
                # Move right
                self.x = self.minX

            # Bullet timer
            self.bulletTimerMax = 15
コード例 #13
0
def get_random_str(items):
    """
    Select a seudo-random string from a given list.

    Args:
        items (lst): List from where to select item.

    Returns:
        item selected value.
    """
    choise = urandom.getrandbits(5)
    try:
        s_return = items[choise]
        return s_return
    except IndexError:
        return get_random_str(items)
コード例 #14
0
ファイル: snippet.py プロジェクト: szabo92/gistable
 def clear():
     res = 16
     for i in range(10):
         effect = urandom.getrandbits(2)
         for j in range(urandint(0, 200) / res):
             if effect == 0:
                 green.duty(800 + (j*res))
             else:
                 red.duty(800 + (j*res))
             time.sleep(0.1)
         for j in range(urandint(0, 200) / res):
             if effect == 1:
                 green.duty(1024-(j*res))
             else:
                 red.duty(1024-(j*res))
             time.sleep(0.1)
コード例 #15
0
def connect(uri):
    """
    Connect a websocket.
    """

    uri = urlparse(uri)
    assert uri

    if __debug__: LOGGER.debug("open connection %s:%s",
                                uri.hostname, uri.port)

    sock = socket.socket()
    addr = socket.getaddrinfo(uri.hostname, uri.port)
    sock.connect(addr[0][4])
    if uri.protocol == 'wss':
        sock = ussl.wrap_socket(sock)

    def send_header(header, *args):
        if __debug__: LOGGER.debug(str(header), *args)
        sock.write(header % args + '\r\n')

    # Sec-WebSocket-Key is 16 bytes of random base64 encoded
    key = binascii.b2a_base64(bytes(random.getrandbits(8)
                                    for _ in range(16)))[:-1]

    send_header(b'GET %s HTTP/1.1', uri.path or '/')
    send_header(b'Host: %s:%s', uri.hostname, uri.port)
    send_header(b'Connection: Upgrade')
    send_header(b'Upgrade: websocket')
    send_header(b'Sec-WebSocket-Key: %s', key)
    send_header(b'Sec-WebSocket-Version: 13')
    send_header(b'Origin: http://{hostname}:{port}'.format(
        hostname=uri.hostname,
        port=uri.port)
    )
    send_header(b'')

    header = sock.readline()[:-2]
    assert header.startswith(b'HTTP/1.1 101 '), header

    # We don't (currently) need these headers
    # FIXME: should we check the return key?
    while header:
        if __debug__: LOGGER.debug(str(header))
        header = sock.readline()[:-2]

    return WebsocketClient(sock)
コード例 #16
0
ファイル: main.py プロジェクト: olablt/esp8266-tree
 async def run(self):
     global current_fx
     while True:
         # run 20 loops
         # for i in range(2):
         if current_fx == 1:
             for i in range(len(self.long_buf) // 3):
                 # [:3] is the list up to [3] and not including [3]
                 # [3:] is the list from [3] to the end of the list
                 self.long_buf = self.long_buf[3:] + self.long_buf[:3]
                 self.np.buf = self.long_buf
                 self.np.write()
                 await asyncio.sleep_ms(self.delay)
             await asyncio.sleep(1)
             self.delay = urandom.getrandbits(4)
         else:
             await asyncio.sleep(1)
コード例 #17
0
    def mesure(self, x, u, t):
        z = self.comportement(x, u, t)

        n = len(self._name_of_mes)
        n2 = int((n + 1) / 2) * 2
        # Vecteur de nombre aleatoires uniformes entre 0 et 1
        vu = [urandom.getrandbits(8 * 4) / float(2 ** 32)] * n2
        for i in range(n2 / 2):
            vu[2 * i + 0], vu[2 * i + 1] = (
                sqrt(-log(vu[2 * i + 0])) * cos(2 * pi * vu[2 * i + 1]),
                sqrt(-log(vu[2 * i + 0])) * sin(2 * pi * vu[2 * i + 1]),
            )

        bn = umatrix.matrix([vu[:n]]).T
        bg = self._cho * bn + self._moy

        self._mes = z + bg
コード例 #18
0
ファイル: pir.py プロジェクト: GeorgetownMakerHubOrg/MP3-PIR
def main():
    from machine import Pin, Signal
    from utime import sleep

    pin = Pin(0, Pin.IN)  # set GPIO4 as input with pullup
    pir = Signal(pin, invert=False)  # let's use Signals, eh?
    detected = False
    while True:
        if not detected and pir.value():  # gone HIGH
            print("A Visitor!")
            mp3.play_track(urandom.getrandbits(BITS) +
                           1)  # since the MP3 doesn't recognize song 0
            detected = True
        elif detected and not pir.value():  # gone LOW
            print("Bye!")
            detected = False
            sleep(60 * 20)  # sleep 20 minutes
コード例 #19
0
    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()
コード例 #20
0
    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
コード例 #21
0
    def get(self, x, y):
        """
        Function to return the value of the given pixel x, y.

        Args:
            x: Integer with the `x` axis position.
            y: Integer with the `y` axis position.

        Returns:
            type: Boolean with the value of the pixel.
        """
        if not 0 <= x < self.width or not 0 <= y < self.height:
            return 0
        if self.oled.display.pixel(x, y) is None:
            bln_return = getrandbits(1)
        else:
            bln_return = self.oled.display.pixel(x, y)
        return bln_return & 1
コード例 #22
0
    def clearBoard(self):
        global coins, topFaceVal, btmFaceVal, leftFaceVal, rightFaceVal, timer, totalTimer

        self.clearChoice = random.getrandbits(2)
        if (coins > 0):
            coins -= 1
            if (self.clearChoice == 0):
                topFaceVal = [0, 0, 0, 0]
            elif (self.clearChoice == 1):
                btmFaceVal = [0, 0, 0, 0]
            elif (self.clearChoice == 2):
                leftFaceVal = [0, 0, 0, 0]
            else:
                rightFaceVal = [0, 0, 0, 0]

            interface.playClear()
            self.randomizeFace()
            timer = totalTimer
コード例 #23
0
async def run(meters, vctrl, bctrl):
    grv = lambda: urandom.getrandbits(16) / 2**16  # Random: range 0.0 to +1.0
    while True:
        v = 1.5 * grv() * vctrl.value()
        d = 1 + 0.1 * grv()
        vl = v * d * 2 * (1 - bctrl.value())
        vr = (v / d) * 2 * bctrl.value()  # left and right show similar values
        if vl > 0.8:
            meters[0].color(RED if vl >= 1 else YELLOW)
        else:
            meters[0].color(CYAN)
        if vr > 0.8:
            meters[1].color(RED if vr >= 1 else YELLOW)
        else:
            meters[1].color(CYAN)
        meters[0].value(min(1.0, vl))
        meters[1].value(min(1.0, vr))
        await asyncio.sleep_ms(200)
コード例 #24
0
ファイル: minianim.py プロジェクト: haviital/pandemic
def RaffleMiniAnim(screen_):

    global screen
    global lastRaffleTime
    screen = screen_
    minianim = None

    now = umachine.time_ms()
    #print("lastRaffleTime",lastRaffleTime,"lastRaffleTime + raffleTimeout", lastRaffleTime + raffleTimeout,"now",now)
    if now > (lastRaffleTime + raffleTimeout):

        lastRaffleTime = now
        minaminCount = len(data.minianimList)
        r = random.getrandbits(8)  # between 0 and 255
        probabilityFactor = 10  # One in 10 wins
        animNum = (
            minaminCount * probabilityFactor
        ) * r // 256  # between 0 and (minaminCount*probabilityFactor)
        #animNum = 2
        print("raffled animNum", animNum)

        if animNum < minaminCount:
            # (x,y,w,h, duration,(fram1, frame2,...),(frame1Pos, frame2Pos,...)),
            animData = data.minianimList[animNum]
            #print("animData",animData)
            frameW = animData[2]
            frameH = animData[3]
            frameSurfaces = []
            frameOffsets = []
            animPixelDataList = animData[6]
            #print("animPixelDataList",animPixelDataList)
            animFrameOffsetList = animData[7]
            #print("animFrameOffsetList",animFrameOffsetList)
            for i in range(len(animPixelDataList)):
                frameSurfaces.append(
                    pygame.surface.Surface(frameW, frameH,
                                           animPixelDataList[i]))
                frameOffsets.append(animFrameOffsetList[i])

            #print("frameOffsets",frameOffsets)
            minianim = MiniAnim(frameSurfaces, frameOffsets, animData[0],
                                animData[1], animData[4], animData[5])

    return minianim
コード例 #25
0
    async def write_frame(self, opcode, data=b''):
        """
        Write a frame to the socket.
        See https://tools.ietf.org/html/rfc6455#section-5.2 for the details.
        """
        fin = True
        mask = self.is_client  # messages sent by client are masked

        length = len(data)

        # Frame header
        # Byte 1: FIN(1) _(1) _(1) _(1) OPCODE(4)
        byte1 = 0x80 if fin else 0
        byte1 |= opcode

        # Byte 2: MASK(1) LENGTH(7)
        byte2 = 0x80 if mask else 0

        if length < 126:  # 126 is magic value to use 2-byte length header
            byte2 |= length
            await self.swriter.awrite(struct.pack('!BB', byte1, byte2))

        elif length < (1 << 16):  # Length fits in 2-bytes
            byte2 |= 126  # Magic code
            await self.srwriter.awrite(
                struct.pack('!BBH', byte1, byte2, length))

        elif length < (1 << 64):
            byte2 |= 127  # Magic code
            await self.swriter.awrite(struct.pack('!BBQ', byte1, byte2,
                                                  length))

        else:
            raise ValueError()

        if mask:  # Mask is 4 bytes
            mask_bits = struct.pack('!I', random.getrandbits(32))
            await self.swriter.awrite(mask_bits)

            data = bytes(b ^ mask_bits[i % 4] for i, b in enumerate(data))

        await self.swriter.awrite(data)
コード例 #26
0
ファイル: rocket.py プロジェクト: marcwagner/mqtt_lights
    def starburst(self,
                  pixels=None,
                  color=(0, 0, 255),
                  dim=0.80,
                  freq=0.05,
                  ms_pause=50,
                  loops=10):

        pixels = self.strip_range if pixels == None else pixels
        l = 0
        while l != loops * len(pixels):
            for i in pixels:
                if self.pixel[i] == (0, 0, 0):
                    if freq * 100 > getrandbits(7):
                        self.pixel[i] = color
                else:
                    self.dim(i, dim)
            self.pixel.write()
            time.sleep_ms(ms_pause)
            l += 1
コード例 #27
0
ファイル: main.py プロジェクト: olablt/esp8266-tree
 async def run(self):
     global current_fx
     while True:
         # run 20 loops
         # for i in range(2):
         if current_fx == 2:
             print("cool 2")
             for i in range(len(self.long_buf) // 3):
                 # [:3] is the list up to [3] and not including [3]
                 # [3:] is the list from [3] to the end of the list
                 self.long_buf = self.long_buf[3:] + self.long_buf[:3]
                 # self.np.buf = self.long_buf[self.star_length*3 : self.led_count*3 + self.star_length*3]
                 self.np.buf = self.long_buf[0:self.led_count * 3]
                 self.np.write()
                 # time.sleep_ms(self.delay)
                 await asyncio.sleep_ms(self.delay)
             await asyncio.sleep(0.2)
             self.delay = urandom.getrandbits(4)
         else:
             await asyncio.sleep(1)
コード例 #28
0
ファイル: client.py プロジェクト: Elsinor/reti
def connect(hostname, port, path):
    """
    Connect a websocket.
    """
    print('!!! client.py :: connect')

    #if __debug__: LOGGER.debug("open connection %s:%s",
    #                            uri.hostname, uri.port)

    sock = socket.socket()
    addr = socket.getaddrinfo(hostname, port)
    addr = addr[0][-1]
    sock.connect(addr)

    def send_header(header, *args):
        if __debug__: LOGGER.debug(str(header), *args)
        sock.send(header % args + '\r\n')

    # Sec-WebSocket-Key is 16 bytes of random base64 encoded
    key = binascii.b2a_base64(bytes(random.getrandbits(8)
                                    for _ in range(16)))[:-1]

    send_header(b'GET %s HTTP/1.1', path or '/')
    send_header(b'Host: %s:%s', hostname, port)
    send_header(b'Connection: Upgrade')
    send_header(b'Upgrade: websocket')
    send_header(b'Sec-WebSocket-Key: %s', key)
    send_header(b'Sec-WebSocket-Version: 13')
    send_header(b'Origin: http://localhost')
    send_header(b'')

    header = sock.readline()[:-2]
    assert header == b'HTTP/1.1 101 Switching Protocols', header

    # We don't (currently) need these headers
    # FIXME: should we check the return key?
    while header:
        if __debug__: LOGGER.debug(str(header))
        header = sock.readline()[:-2]

    return WebsocketClient(sock)
コード例 #29
0
 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)
コード例 #30
0
ファイル: shake.py プロジェクト: jvdw008/pokabalt
    def update(self):
        if self.shake:
            if self.shakeSpeed > 0:
                if random.getrandbits(1) == 1:
                    self.shakeSpeed -= 1
            else:
                self.shakeSpeed = self.shakeSpeedMax
                self.shakeAmount -= 1

            if self.shakeAmount <= 0:
                self.shakeAmount == self.shakeMax
                self.shake = False

        if self.shake:
            self.direction = -self.direction
            if self.direction == 1:
                return self.shakeAmount
            else:
                return -self.shakeAmount
        else:
            return 0
コード例 #31
0
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')
コード例 #32
0
ファイル: bounce.py プロジェクト: PinkInk/upylib
 def rand():
     return getrandbits(8)
コード例 #33
0
ファイル: heart.py プロジェクト: penkich/esp8266-micropython
# 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))