def __init__(self, n_leds, positions, normals, inside, remap=None, circuits={}): self.n_leds = n_leds self.positions = positions self.normals = normals self.flat_data = uarray.array('f') for p, n in zip(positions, normals): for x in p + n: self.flat_data.append(x) if remap == None: self.remap = None else: self.remap = uarray.array('H', remap) self.circuits = circuits self.inside = inside
def ecb(self, data, block_func): """Perform ECB mode with the given function""" if len(data) % self.block_size != 0: raise ValueError("Input length must be multiple of 16") block_size = self.block_size data = array('B', data) for offset in range(0, len(data), block_size): block = data[offset:offset + block_size] block_func(block) data[offset:offset + block_size] = block return data
def test(): tests = [ isclose(add(0.1, 0.2), 0.3), isclose(add_f(0.1, 0.2), 0.3), ] ar = array.array("f", [1, 2, 3.5]) productf(ar) tests.append(isclose(ar[0], 7)) if "add_d" in globals(): tests.append(isclose(add_d(0.1, 0.2), 0.3)) print(tests) if not all(tests): raise SystemExit(1)
def __init__(self, leds, config=None): self.leds = leds self.spots = [ _Spot( ( 0, 0 ), 2, 3, (255, 255, 255), .2 ) ] self.shader_flat = uarray.array('f', # position color * intensity [ -1,-1,-1, 0, 0, 0, -1,-1,-1, 0, 0, 0, -1,-1,-1, 0, 0, 0 ] # -1,-1,-1, 0, 0, 0, # -1,-1,-1, 0, 0, 0, # -1,-1,-1, 0, 0, 0 ] ) config.add_color( 'color', self.spots[0].get_color, self.spots[0].set_color, caption="color" ) config.add_slider('x_axis_rotation', -pi/2, pi/2, .01, self.spots[0].get_x_axis_rotation, self.spots[0].set_x_axis_rotation, caption='x-axis rotation') config.add_slider('y_axis_rotation', -pi, pi, .01, self.spots[0].get_y_axis_rotation, self.spots[0].set_y_axis_rotation, caption='y-axis rotation') config.add_slider('chroma', 0, 1, .01, self.spots[0].get_chroma, self.spots[0].set_chroma, caption='chroma') config.add_slider('brightness', 0, 12, .01, self.spots[0].get_brightness, self.spots[0].set_brightness, caption='intensity')
def _convert_pulses_to_buffer(self, pulses): """Convert a list of 80 pulses into a 5 byte buffer The resulting 5 bytes in the buffer will be: 0: Integral relative humidity data 1: Decimal relative humidity data 2: Integral temperature data 3: Decimal temperature data 4: Checksum """ # Convert the pulses to 40 bits binary = 0 for idx in range(0, len(pulses), 2): binary = binary << 1 | int(pulses[idx] > HIGH_LEVEL) # Split into 5 bytes buffer = array.array("B") for shift in range(4, -1, -1): buffer.append(binary >> shift * 8 & 0xFF) return buffer
def __init__( self, *, out_init=None, set_init=None, sideset_init=None, in_shiftdir=0, out_shiftdir=0, autopush=False, autopull=False, push_thresh=32, pull_thresh=32, fifo_join=0, ): # uarray is a built-in module so importing it here won't require # scanning the filesystem. from uarray import array self.labels = {} execctrl = 0 shiftctrl = (fifo_join << 30 | (pull_thresh & 0x1F) << 25 | (push_thresh & 0x1F) << 20 | out_shiftdir << 19 | in_shiftdir << 18 | autopull << 17 | autopush << 16) self.prog = [ array("H"), -1, -1, execctrl, shiftctrl, out_init, set_init, sideset_init ] self.wrap_used = False if sideset_init is None: self.sideset_count = 0 elif isinstance(sideset_init, int): self.sideset_count = 1 else: self.sideset_count = len(sideset_init)
async def tcp_client(): reader, writer = await asyncio.open_connection(IP, PORT) ba = bytearray(2) n = await reader.readinto(ba) print(n) print(ba[:n]) a = array.array("b", [0, 0]) n = await reader.readinto(a) print(n) print(a[:n]) try: n = await reader.readinto(5) except TypeError as er: print("TypeError") try: n = await reader.readinto() except TypeError as er: print("TypeError")
def encrypt(self, data): """Encrypt data in CBC mode""" block_size = self.block_size if len(data) % block_size != 0: raise ValueError("Plaintext length must be multiple of 16") data = array('B', bytes(data, 'utf-8')) IV = self.IV for offset in range(0, len(data), block_size): block = data[offset:offset + block_size] # Perform CBC chaining for i in range(block_size): block[i] ^= IV[i] self.cipher.encrypt_block(block) data[offset:offset + block_size] = block IV = block self.IV = IV return data
def __init__(self, leds, config=None): n = 2048 self.wave = get_smooth_wave() self.rotations = uarray.array('H', 0 for _ in range(leds.n_leds * 3)) for i in range(leds.n_leds): x, y, z = leds.positions[i] self.rotations[i * 3] = int( (n * (1 + cmath.phase(complex(z, x)) / (math.pi * 2))) % n) self.rotations[i * 3 + 1] = int( (n * (1 + cmath.phase(complex(z, x)) / (math.pi * 2))) % n) self.rotations[i * 3 + 2] = int((786 * y) % n) self.phase = 0 self.phase_max = 512 * 3 * 3 * 10 self.speed = 10 if config: config.add_slider('speed', 0, 20, 1, self.get_speed, self.set_speed, caption="speed")
# test construction of bytearray from different objects try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit # arrays print(bytearray(array('h', [1, 2]))) print(bytearray(array('I', [1, 2])))
m = memoryview(b) m[0] = 1 print(b) print(list(m)) # test slice m = memoryview(b'1234') print(list(m[1:])) print(list(m[1:-1])) # this tests get_buffer of memoryview m = memoryview(bytearray(2)) print(bytearray(m)) print(list(memoryview(memoryview(b'1234')))) # read-only memoryview a = array.array('i', [1, 2, 3, 4]) m = memoryview(a) print(list(m)) print(list(m[1:-1])) m[2] = 6 print(a) # invalid attribute try: memoryview(b'a').noexist except AttributeError: print('AttributeError') # equality print(memoryview(b'abc') == b'abc') print(memoryview(b'abc') != b'abc')
can.send('01234567', 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) can.send('abc', 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) micropython.heap_unlock() # Test that recv can work with different arrays behind the memoryview can.send('abc', 1) print(bytes(can.recv(0, [0, 0, 0, memoryview(array('B', range(8)))])[3])) can.send('def', 1) print(bytes(can.recv(0, [0, 0, 0, memoryview(array('b', range(8)))])[3])) # Test for non-list passed as second arg to recv can.send('abc', 1) try: can.recv(0, 1) except TypeError: print('TypeError') # Test for too-short-list passed as second arg to recv can.send('abc', 1) try: can.recv(0, [0, 0, 0]) except ValueError:
# test memoryview accessing maximum values for signed/unsigned elements try: memoryview except: print("SKIP") raise SystemExit try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit print(list(memoryview(array('i', [0x7f000000, -0x80000000])))) print( list( memoryview(array('I', [0x7f000000, 0x80000000, 0x81000000, 0xffffffff]))))
can.send("01234567", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) can.send("abc", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) micropython.heap_unlock() # Test that recv can work with different arrays behind the memoryview can.send("abc", 1) print(bytes(can.recv(0, [0, 0, 0, memoryview(array("B", range(8)))])[3])) can.send("def", 1) print(bytes(can.recv(0, [0, 0, 0, memoryview(array("b", range(8)))])[3])) # Test for non-list passed as second arg to recv can.send("abc", 1) try: can.recv(0, 1) except TypeError: print("TypeError") # Test for too-short-list passed as second arg to recv can.send("abc", 1) try: can.recv(0, [0, 0, 0]) except ValueError:
def pipe(): a = array.array('i', [0, 0]) r = pipe_(a) check_error(r) return a[0], a[1]
# test construction of array from array with float type try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit print(array("f", array("h", [1, 2]))) print(array("d", array("f", [1, 2])))
# test MicroPython-specific features of array.array try: import uarray as array except ImportError: try: import array except ImportError: print("SKIP") raise SystemExit # arrays of objects a = array.array('O') a.append(1) print(a[0]) # arrays of pointers a = array.array('P') a.append(1) print(a[0])
try: memoryview(b'a').itemsize except: print("SKIP") raise SystemExit try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit for code in ['b', 'h', 'i', 'l', 'q', 'f', 'd']: print(memoryview(array(code)).itemsize) # shouldn't be able to store to the itemsize attribute try: memoryview(b'a').itemsize = 1 except AttributeError: print('AttributeError')
def makeref(typ, val=0): return uarray.array(typ, [val])
def waitpid(pid, opts): a = array.array('i', [0]) r = waitpid_(pid, a, opts) check_error(r) return (r, a[0])
b(loop_entry) label(loop1) ldrb(r3, [r1, 0]) add(r2, r2, r3) add(r1, r1, 1) sub(r0, r0, 1) label(loop_entry) cmp(r0, 0) bgt(loop1) mov(r0, r2) import uarray as array b = array.array("l", (100, 200, 300, 400)) n = asm_sum_words(len(b), b) print(b, n) b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80)) n = asm_sum_bytes(len(b), b) print(b, n) b = b"\x01\x02\x03\x04" n = asm_sum_bytes(len(b), b) print(b, n)
try: import uarray as array except ImportError: try: import array except ImportError: print("SKIP") raise SystemExit a = array.array('B', [1, 2, 3]) print(a, len(a)) i = array.array('I', [1, 2, 3]) print(i, len(i)) print(a[0]) print(i[-1]) a = array.array('l', [-1]) print(len(a), a[0]) a1 = array.array('l', [1, 2, 3]) a2 = array.array('L', [1, 2, 3]) print(a2[1]) print(a1 == a2) # Empty arrays print(len(array.array('h'))) print(array.array('i')) # bool operator acting on arrays print(bool(array.array('i'))) print(bool(array.array('i', [1]))) # containment, with incorrect type
def pipe(): a = uarray.array("i", [0, 0]) r = _pipe(a) check_error(r) return a[0], a[1]
def do_iter(l): heap_lock() for i in l: print(i) heap_unlock() def gen_func(): yield 1 yield 2 # pre-create collections to iterate over ba = bytearray(b'123') ar = array.array('H', (123, 456)) t = (1, 2, 3) l = [1, 2] d = {1: 2} s = set((1, )) fs = frozenset((1, )) g1 = (100 + x for x in range(2)) g2 = gen_func() # test containment (both success and failure) with the heap locked heap_lock() print(49 in b'123', 255 in b'123') print(1 in t, -1 in t) print(1 in l, -1 in l) print(1 in d, -1 in d) print(1 in s, -1 in s)
# test construction of array from array with float type try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit print(array('f', array('h', [1, 2]))) print(array('d', array('f', [1, 2])))
def waitpid(pid, opts): a = uarray.array("i", [0]) r = _waitpid(pid, a, opts) check_error(r) return r, a[0]
def main(): # set timing variables: timePeriod = 20 # time in milliseconds between each data sending startTiming = 0 stopTiming = 0 # set variables for uosc client microsDelay = 20 * 1000 # time delay in microseconds bonsaiAddress = "192.168.137.255" commPort = 9001 digitalSend = "/digitalInput" digitalReceive = "/digitalOutput" # create osc client object osc = Client(bonsaiAddress, commPort) # set Digital pins # Digital output p0 = Pin(32, Pin.OUT) # currently beehive D0 is IO32 p1 = Pin(33, Pin.OUT) # currently beehive D1 is IO33 p2 = Pin(25, Pin.OUT) # currently beehive D2 is IO25 p3 = Pin(26, Pin.OUT) # currently beehive D3 is IO26 # index of pins set as output pinOutList = [p0, p1, p2, p3] pinOutIndex = [0, 1, 2, 3] # pinOutNum = [0,1,2,3] # digital input # p4 = Pin(27, Pin.IN) # currently beehive D4 is IO27 p5 = Pin(14, Pin.IN) # currently beehive D5 is IO14 # p6 = Pin(12, Pin.IN) # currently beehive D6 is IO12 # p7 = Pin(13, Pin.IN) # currently beehive D7 is IO13 # index of pins set as input pinInList = [p5] # [p4,p5,p6,p7] pinInIndex = [5] # [4,5,6,7] # Analog input # although attenuation allows 3.6V to be the max range, 3.3V should be the MAX send to the board!!! # adc0 = machine.ADC(34) # currently beehive D7 is IO13 # adc0.atten(machine.ADC.ATTN_11DB) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v) # adc1 = machine.ADC(34) # currently beehive D7 is IO13 # adc1.atten(machine.ADC.ATTN_11DB) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v) # adc2 = machine.ADC(34) # currently beehive D7 is IO13 # adc2.atten(machine.ADC.ATTN_11DB) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v) # adc3 = machine.ADC(34) # currently beehive D7 is IO13 # adc3.atten(machine.ADC.ATTN_11DB) # set 11dB input attenuation (voltage range roughly 0.0v - 3.6v) # index of pins set as analog # pinsAnalogInList = [adc0,adc1,adc2,adc3] # analog output (actually PWM): # dac0 = 1 # dac1 = 2 # dac2 = 3 # dac4 = 4 # create bundle b = Bundle() # infinite loop while 1: # receive message from OSC dummie = 0 # if there is a specific message break the scanning loop if dummie != 0: break # temp variable to store digital input values temp = 0 startTiming = time.ticks_us() # get microsecond counter # loop to scan input pins # tic1 = time.ticks_us() for i in range(len(pinInList)): # print(i) # print(pinInList[i].value()) if pinInList[i].value() == 1: temp = temp + (2 ** pinInIndex[i]) # print(temp) # toc1 = time.ticks_us() # print("getting all dig in ports took: "+str(toc1-tic1)+ " microseconds" ) # print(toc1-tic1) # temp = bytes(temp) temp = uarray.array("B", [10, 32, 10, 20, 10, 10]) msg = create_message(digitalSend, ("b", temp)) b.add(msg) tic2 = time.ticks_us() osc.send(b) osc.close() del temp toc2 = time.ticks_us() print("sending took: " + str(toc2 - tic2) + " microseconds") x = 0 while ( stopTiming - startTiming < timePeriod * 1000 ): # convert milliseconds in microseconds # read digital port stopTiming = time.ticks_us() # time.sleep(0.001) # analog input pins # for i in range(len(pinsAnalogInList)): # print(i) # print(pinsAnalogInList[i].adc.read_u16()) # do not forget to actually send the adc read info. # send message out with pins state # listen for message setting pins return
try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit # construct from something with unknown length (requires generators) print(array('i', (i for i in range(10))))
# test construction of bytearray from array with float type try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit print(bytearray(array('f', [1, 2.3])))
try: from uarray import array except ImportError: try: from array import array except ImportError: print("SKIP") raise SystemExit def test(a): print(a) a.append(1.2) print(len(a), "%.3f" % a[0]) a.append(1) a.append(False) print(len(a), "%.3f %.3f" % (a[1], a[2])) a[-1] = 3.45 print("%.3f" % a[-1]) test(array("f")) test(array("d")) print("{:.4f}".format(array("f", b"\xcc\xcc\xcc=")[0]))