code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
# tests meminfo functions in micropython module import micropython # these functions are not always available if not hasattr(micropython, "mem_info"): print("SKIP") else: micropython.mem_info() micropython.mem_info(1) micropython.qstr_info() micropython.qstr_info(1)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/meminfo.py
Python
apache-2.0
289
# tests meminfo functions in micropython module import micropython # these functions are not always available if not hasattr(micropython, "mem_total"): print("SKIP") else: t = micropython.mem_total() c = micropython.mem_current() p = micropython.mem_peak() l = list(range(10000)) print(micropython.mem_total() > t) print(micropython.mem_current() > c) print(micropython.mem_peak() > p)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/memstats.py
Python
apache-2.0
422
# test native emitter can handle closures correctly # basic closure @micropython.native def f(): x = 1 @micropython.native def g(): nonlocal x return x return g print(f()()) # closing over an argument @micropython.native def f(x): @micropython.native def g(): nonlocal x return x return g print(f(2)()) # closing over an argument and a normal local @micropython.native def f(x): y = 2 * x @micropython.native def g(z): return x + y + z return g print(f(2)(3))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_closure.py
Python
apache-2.0
558
# test loading constants in native functions @micropython.native def f(): return b"bytes" print(f()) @micropython.native def f(): @micropython.native def g(): return 123 return g print(f()())
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_const.py
Python
apache-2.0
225
# check loading constants @micropython.native def f(): return 123456789012345678901234567890 print(f())
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_const_intbig.py
Python
apache-2.0
112
# test for native for loops @micropython.native def f1(n): for i in range(n): print(i) f1(4) @micropython.native def f2(r): for i in r: print(i) f2(range(4))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_for.py
Python
apache-2.0
190
# test for native generators # simple generator with yield and return @micropython.native def gen1(x): yield x yield x + 1 return x + 2 g = gen1(3) print(next(g)) print(next(g)) try: next(g) except StopIteration as e: print(e.args[0]) # using yield from @micropython.native def gen2(x): yield from range(x) print(list(gen2(3)))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_gen.py
Python
apache-2.0
358
# tests for natively compiled functions # basic test @micropython.native def native_test(x): print(1, [], x) native_test(2) # check that GC doesn't collect the native function import gc gc.collect() native_test(3) # native with 2 args @micropython.native def f(a, b): print(a + b) f(1, 2) # native with 3 args @micropython.native def f(a, b, c): print(a + b + c) f(1, 2, 3) # check not operator @micropython.native def f(a): print(not a) f(False) f(True) # stack settling in branch @micropython.native def f(a): print(1, 2, 3, 4 if a else 5) f(False) f(True)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_misc.py
Python
apache-2.0
597
# test native try handling # basic try-finally @micropython.native def f(): try: fail finally: print("finally") try: f() except NameError: print("NameError") # nested try-except with try-finally @micropython.native def f(): try: try: fail finally: print("finally") except NameError: print("NameError") f() # check that locals written to in try blocks keep their values @micropython.native def f(): a = 100 try: print(a) a = 200 fail except NameError: print(a) a = 300 print(a) f()
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_try.py
Python
apache-2.0
634
# test native try handling # deeply nested try (9 deep) @micropython.native def f(): try: try: try: try: try: try: try: try: try: raise ValueError finally: print(8) finally: print(7) finally: print(6) finally: print(5) finally: print(4) finally: print(3) finally: print(2) finally: print(1) except ValueError: print("ValueError") f()
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_try_deep.py
Python
apache-2.0
953
# test with handling within a native function class C: def __init__(self): print("__init__") def __enter__(self): print("__enter__") def __exit__(self, a, b, c): print("__exit__", a, b, c) # basic with @micropython.native def f(): with C(): print(1) f() # nested with and try-except @micropython.native def f(): try: with C(): print(1) fail print(2) except NameError: print("NameError") f()
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/native_with.py
Python
apache-2.0
510
import micropython as micropython # check we can get and set the level micropython.opt_level(0) print(micropython.opt_level()) micropython.opt_level(1) print(micropython.opt_level()) # check that the optimisation levels actually differ micropython.opt_level(0) exec("print(__debug__)") micropython.opt_level(1) exec("print(__debug__)") exec("assert 0")
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/opt_level.py
Python
apache-2.0
355
import micropython as micropython # check that level 3 doesn't store line numbers # the expected output is that any line is printed as "line 1" micropython.opt_level(3) exec("try:\n xyz\nexcept NameError as er:\n import usys\n usys.print_exception(er)")
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/opt_level_lineno.py
Python
apache-2.0
255
# test micropython.schedule() function import micropython try: micropython.schedule except AttributeError: print("SKIP") raise SystemExit # Basic test of scheduling a function. def callback(arg): global done print(arg) done = True done = False micropython.schedule(callback, 1) while not done: pass # Test that callbacks can be scheduled from within a callback, but # that they don't execute until the outer callback is finished. def callback_inner(arg): global done print("inner") done += 1 def callback_outer(arg): global done micropython.schedule(callback_inner, 0) # need a loop so that the VM can check for pending events for i in range(2): pass print("outer") done += 1 done = 0 micropython.schedule(callback_outer, 0) while done != 2: pass # Test that scheduling too many callbacks leads to an exception. To do this we # must schedule from within a callback to guarantee that the scheduler is locked. def callback(arg): global done try: for i in range(100): micropython.schedule(lambda x: x, None) except RuntimeError: print("RuntimeError") done = True done = False micropython.schedule(callback, None) while not done: pass
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/schedule.py
Python
apache-2.0
1,275
# tests stack_use function in micropython module import micropython if not hasattr(micropython, "stack_use"): print("SKIP") else: print(type(micropython.stack_use())) # output varies
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/stack_use.py
Python
apache-2.0
193
# test passing addresses to viper @micropython.viper def get_addr(x: ptr) -> ptr: return x @micropython.viper def memset(dest: ptr8, c: int, n: int): for i in range(n): dest[i] = c @micropython.viper def memsum(src: ptr8, n: int) -> int: s = 0 for i in range(n): s += src[i] return s # create array and get its address ar = bytearray("0000") addr = get_addr(ar) print(type(ar)) print(type(addr)) print(ar) # pass array as an object memset(ar, ord("1"), len(ar)) print(ar) # pass direct pointer to array buffer memset(addr, ord("2"), len(ar)) print(ar) # pass direct pointer to array buffer, with offset memset(addr + 2, ord("3"), len(ar) - 2) print(ar) # pass a read-only bytes object in print(memsum(b"\x01\x02\x03\x04", 4))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_addr.py
Python
apache-2.0
774
# test calling viper functions with different number of args @micropython.viper def f0(): print(0) f0() @micropython.viper def f1(x1: int): print(x1) f1(1) @micropython.viper def f2(x1: int, x2: int): print(x1, x2) f2(1, 2) @micropython.viper def f3(x1: int, x2: int, x3: int): print(x1, x2, x3) f3(1, 2, 3) @micropython.viper def f4(x1: int, x2: int, x3: int, x4: int): print(x1, x2, x3, x4) f4(1, 2, 3, 4) @micropython.viper def f5(x1: int, x2: int, x3: int, x4: int, x5: int): print(x1, x2, x3, x4, x5) f5(1, 2, 3, 4, 5) @micropython.viper def f6(x1: int, x2: int, x3: int, x4: int, x5: int, x6: int): print(x1, x2, x3, x4, x5, x6) f6(1, 2, 3, 4, 5, 6) # test compiling *x, **x, * args (currently unsupported at runtime) @micropython.viper def f(*x, **y): pass @micropython.viper def f(*): pass
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_args.py
Python
apache-2.0
865
# test arithmetic operators @micropython.viper def add(x: int, y: int): print(x + y) print(y + x) add(1, 2) add(42, 3) add(-1, 2) add(-42, -3) @micropython.viper def sub(x: int, y: int): print(x - y) print(y - x) sub(1, 2) sub(42, 3) sub(-1, 2) sub(-42, -3) @micropython.viper def mul(x: int, y: int): print(x * y) print(y * x) mul(0, 1) mul(1, -1) mul(1, 2) mul(8, 3) mul(-3, 4) mul(-9, -6) @micropython.viper def shl(x: int, y: int): print(x << y) shl(1, 0) shl(1, 3) shl(1, 30) shl(42, 10) shl(-42, 10) @micropython.viper def shr(x: int, y: int): print(x >> y) shr(1, 0) shr(1, 3) shr(42, 2) shr(-42, 2) @micropython.viper def and_(x: int, y: int): print(x & y, y & x) and_(1, 0) and_(1, 3) and_(0xF0, 0x3F) and_(-42, 6) @micropython.viper def or_(x: int, y: int): print(x | y, y | x) or_(1, 0) or_(1, 2) or_(-42, 5) @micropython.viper def xor(x: int, y: int): print(x ^ y, y ^ x) xor(1, 0) xor(1, 2) xor(-42, 5)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_arith.py
Python
apache-2.0
992
# test arithmetic operators with uint type @micropython.viper def add(x: uint, y: uint): return x + y, y + x print("add") print(*add(1, 2)) print(*(x & 0xFFFFFFFF for x in add(-1, -2))) @micropython.viper def sub(x: uint, y: uint): return x - y, y - x print("sub") print(*(x & 0xFFFFFFFF for x in sub(1, 2))) print(*(x & 0xFFFFFFFF for x in sub(-1, -2))) @micropython.viper def mul(x: uint, y: uint): return x * y, y * x print("mul") print(*mul(2, 3)) print(*(x & 0xFFFFFFFF for x in mul(2, -3))) print(*mul(-2, -3))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_arith_uint.py
Python
apache-2.0
541
# test bitwise operators on uint type @micropython.viper def shl(x: uint, y: uint) -> uint: return x << y print("shl") print(shl(1, 0)) print(shl(1, 30)) print(shl(-1, 10) & 0xFFFFFFFF) @micropython.viper def shr(x: uint, y: uint) -> uint: return x >> y print("shr") print(shr(1, 0)) print(shr(16, 3)) print(shr(-1, 1) in (0x7FFFFFFF, 0x7FFFFFFF_FFFFFFFF)) @micropython.viper def and_(x: uint, y: uint): return x & y, y & x print("and") print(*and_(1, 0)) print(*and_(1, 3)) print(*and_(-1, 2)) print(*(x & 0xFFFFFFFF for x in and_(-1, -2))) @micropython.viper def or_(x: uint, y: uint): return x | y, y | x print("or") print(*or_(1, 0)) print(*or_(1, 2)) print(*(x & 0xFFFFFFFF for x in or_(-1, 2))) @micropython.viper def xor(x: uint, y: uint): return x ^ y, y ^ x print("xor") print(*xor(1, 0)) print(*xor(1, 3)) print(*(x & 0xFFFFFFFF for x in xor(-1, 3))) print(*xor(-1, -3))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_bitwise_uint.py
Python
apache-2.0
921
# test comparison operators @micropython.viper def f(x: int, y: int): if x < y: print(x, "<", y) if x > y: print(x, ">", y) if x == y: print(x, "==", y) if x <= y: print(x, "<=", y) if x >= y: print(x, ">=", y) if x != y: print(x, "!=", y) f(1, 1) f(2, 1) f(1, 2) f(2, -1) f(-2, 1)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_comp.py
Python
apache-2.0
356
# comparisons with immediate boundary values @micropython.viper def f(a: int): print(a == -1, a == -255, a == -256, a == -257) f(-1) f(-255) f(-256) f(-257)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_comp_imm.py
Python
apache-2.0
163
# test comparison operators with uint type @micropython.viper def f(x: uint, y: uint): if x < y: print(" <", end="") if x > y: print(" >", end="") if x == y: print(" ==", end="") if x <= y: print(" <=", end="") if x >= y: print(" >=", end="") if x != y: print(" !=", end="") def test(a, b): print(a, b, end="") f(a, b) print() test(1, 1) test(2, 1) test(1, 2) test(2, -1) test(-2, 1) test(-2, -1)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_comp_uint.py
Python
apache-2.0
487
# test floor-division and modulo operators @micropython.viper def div(x: int, y: int) -> int: return x // y @micropython.viper def mod(x: int, y: int) -> int: return x % y def dm(x, y): print(div(x, y), mod(x, y)) for x in (-6, 6): for y in range(-7, 8): if y == 0: continue dm(x, y)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_divmod.py
Python
apache-2.0
336
# test multi comparison operators @micropython.viper def f(x: int, y: int): if 0 < x < y: print(x, "<", y) if 3 > x > y: print(x, ">", y) if 1 == x == y: print(x, "==", y) if -2 == x <= y: print(x, "<=", y) if 2 == x >= y: print(x, ">=", y) if 2 == x != y: print(x, "!=", y) f(1, 1) f(2, 1) f(1, 2) f(2, -1) f(-2, 1)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_binop_multi_comp.py
Python
apache-2.0
391
# using False as a conditional @micropython.viper def f(): x = False if x: pass else: print("not x", x) f() # using True as a conditional @micropython.viper def f(): x = True if x: print("x", x) f() # using an int as a conditional @micropython.viper def g(): y = 1 if y: print("y", y) g() # using an int as a conditional that has the lower 16-bits clear @micropython.viper def h(): z = 0x10000 if z: print("z", z) h()
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_cond.py
Python
apache-2.0
505
# test loading constants in viper functions @micropython.viper def f(): return b"bytes" print(f()) @micropython.viper def f(): @micropython.viper def g() -> int: return 123 return g print(f()())
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_const.py
Python
apache-2.0
228
# check loading constants @micropython.viper def f(): return 123456789012345678901234567890 print(f())
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_const_intbig.py
Python
apache-2.0
111
# test syntax and type errors specific to viper code generation def test(code): try: exec(code) except (SyntaxError, ViperTypeError, NotImplementedError) as e: print(repr(e)) # viper: annotations must be identifiers test("@micropython.viper\ndef f(a:1): pass") test("@micropython.viper\ndef f() -> 1: pass") # unknown type test("@micropython.viper\ndef f(x:unknown_type): pass") # local used before type known test( """ @micropython.viper def f(): print(x) x = 1 """ ) # type mismatch storing to local test( """ @micropython.viper def f(): x = 1 y = [] x = y """ ) # can't implicitly convert type to bool test( """ @micropython.viper def f(): x = ptr(0) if x: pass """ ) # incorrect return type test("@micropython.viper\ndef f() -> int: return []") # can't do binary op between incompatible types test("@micropython.viper\ndef f(): 1 + []") test("@micropython.viper\ndef f(x:int, y:uint): x < y") # can't load test("@micropython.viper\ndef f(): 1[0]") test("@micropython.viper\ndef f(): 1[x]") # can't store test("@micropython.viper\ndef f(): 1[0] = 1") test("@micropython.viper\ndef f(): 1[x] = 1") test("@micropython.viper\ndef f(x:int): x[0] = x") test("@micropython.viper\ndef f(x:ptr32): x[0] = None") test("@micropython.viper\ndef f(x:ptr32): x[x] = None") # must raise an object test("@micropython.viper\ndef f(): raise 1") # unary ops not implemented test("@micropython.viper\ndef f(x:int): +x") test("@micropython.viper\ndef f(x:int): -x") test("@micropython.viper\ndef f(x:int): ~x") # binary op not implemented test("@micropython.viper\ndef f(x:uint, y:uint): res = x // y") test("@micropython.viper\ndef f(x:uint, y:uint): res = x % y") test("@micropython.viper\ndef f(x:int): res = x in x") # yield (from) not implemented test("@micropython.viper\ndef f(): yield") test("@micropython.viper\ndef f(): yield from f") # passing a ptr to a Python function not implemented test("@micropython.viper\ndef f(): print(ptr(1))") # cast of a casting identifier not implemented test("@micropython.viper\ndef f(): int(int)")
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_error.py
Python
apache-2.0
2,115
# test that viper functions capture their globals context gl = {} exec( """ @micropython.viper def f(): return x """, gl, ) # x is not yet in the globals, f should not see it try: print(gl["f"]()) except NameError: print("NameError") # x is in globals, f should now see it gl["x"] = 123 print(gl["f"]())
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_globals.py
Python
apache-2.0
328
# test import within viper function @micropython.viper def f(): import micropython print(micropython.const(1)) from micropython import const print(const(2)) f()
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_import.py
Python
apache-2.0
184
import micropython # viper function taking and returning ints @micropython.viper def viper_int(x: int, y: int) -> int: return x + y + 3 print(viper_int(1, 2)) # viper function taking and returning objects @micropython.viper def viper_object(x: object, y: object) -> object: return x + y print(viper_object(1, 2)) # return None as non-object (should return 0) @micropython.viper def viper_ret_none() -> int: return None print(viper_ret_none()) # return Ellipsis as object @micropython.viper def viper_ret_ellipsis() -> object: return ... print(viper_ret_ellipsis()) # 3 args @micropython.viper def viper_3args(a: int, b: int, c: int) -> int: return a + b + c print(viper_3args(1, 2, 3)) # 4 args @micropython.viper def viper_4args(a: int, b: int, c: int, d: int) -> int: return a + b + c + d # viper call with 4 args not yet supported # print(viper_4args(1, 2, 3, 4)) # a local (should have automatic type int) @micropython.viper def viper_local(x: int) -> int: y = 4 return x + y print(viper_local(3)) # without type annotation, types should default to object @micropython.viper def viper_no_annotation(x, y): return x * y print(viper_no_annotation(4, 5)) # a for loop @micropython.viper def viper_for(a: int, b: int) -> int: total = 0 for x in range(a, b): total += x return total print(viper_for(10, 10000)) # accessing a global @micropython.viper def viper_access_global(): global gl gl = 1 return gl print(viper_access_global(), gl) # calling print with object and int types @micropython.viper def viper_print(x, y: int): print(x, y + 1) viper_print(1, 2) # convert constants to objects in tuple @micropython.viper def viper_tuple_consts(x): return (x, 1, False, True) print(viper_tuple_consts(0)) # making a tuple from an object and an int @micropython.viper def viper_tuple(x, y: int): return (x, y + 1) print(viper_tuple(1, 2)) # making a list from an object and an int @micropython.viper def viper_list(x, y: int): return [x, y + 1] print(viper_list(1, 2)) # making a set from an object and an int @micropython.viper def viper_set(x, y: int): return {x, y + 1} print(sorted(list(viper_set(1, 2)))) # raising an exception @micropython.viper def viper_raise(x: int): raise OSError(x) try: viper_raise(1) except OSError as e: print(repr(e)) # calling GC after defining the function @micropython.viper def viper_gc() -> int: return 1 print(viper_gc()) import gc gc.collect() print(viper_gc())
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_misc.py
Python
apache-2.0
2,553
# Miscellaneous viper tests # Test correct use of registers in load and store @micropython.viper def expand(dest: ptr8, source: ptr8, length: int): n = 0 for x in range(0, length, 2): c = source[x] d = source[x + 1] dest[n] = (c & 0xE0) | ((c & 0x1C) >> 1) n += 1 dest[n] = ((c & 3) << 6) | ((d & 0xE0) >> 4) n += 1 dest[n] = ((d & 0x1C) << 3) | ((d & 3) << 2) n += 1 source = b"\xaa\xaa\xff\xff" dest = bytearray(len(source) // 2 * 3) expand(dest, source, len(source)) print(dest)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_misc2.py
Python
apache-2.0
557
import micropython # unsigned ints @micropython.viper def viper_uint() -> uint: return uint(-1) import usys print(viper_uint() == (usys.maxsize << 1 | 1))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_misc_intbig.py
Python
apache-2.0
163
# test loading from ptr16 type # only works on little endian machines @micropython.viper def get(src: ptr16) -> int: return src[0] @micropython.viper def get1(src: ptr16) -> int: return src[1] @micropython.viper def memadd(src: ptr16, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum @micropython.viper def memadd2(src_in) -> int: src = ptr16(src_in) n = int(len(src_in)) >> 1 sum = 0 for i in range(n): sum += src[i] return sum b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 2)) print(memadd2(b))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_ptr16_load.py
Python
apache-2.0
607
# test ptr16 type @micropython.viper def set(dest: ptr16, val: int): dest[0] = val @micropython.viper def set1(dest: ptr16, val: int): dest[1] = val @micropython.viper def memset(dest: ptr16, val: int, n: int): for i in range(n): dest[i] = val @micropython.viper def memset2(dest_in, val: int): dest = ptr16(dest_in) n = int(len(dest_in)) >> 1 for i in range(n): dest[i] = val b = bytearray(4) print(b) set(b, 0x4242) print(b) set1(b, 0x4343) print(b) memset(b, 0x4444, len(b) // 2) print(b) memset2(b, 0x4545) print(b)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_ptr16_store.py
Python
apache-2.0
574
# test loading from ptr32 type @micropython.viper def get(src: ptr32) -> int: return src[0] @micropython.viper def get1(src: ptr32) -> int: return src[1] @micropython.viper def memadd(src: ptr32, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum @micropython.viper def memadd2(src_in) -> int: src = ptr32(src_in) n = int(len(src_in)) >> 2 sum = 0 for i in range(n): sum += src[i] return sum b = bytearray(b"\x12\x12\x12\x12\x34\x34\x34\x34") print(b) print(hex(get(b)), hex(get1(b))) print(hex(memadd(b, 2))) print(hex(memadd2(b)))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_ptr32_load.py
Python
apache-2.0
616
# test store to ptr32 type @micropython.viper def set(dest: ptr32, val: int): dest[0] = val @micropython.viper def set1(dest: ptr32, val: int): dest[1] = val @micropython.viper def memset(dest: ptr32, val: int, n: int): for i in range(n): dest[i] = val @micropython.viper def memset2(dest_in, val: int): dest = ptr32(dest_in) n = int(len(dest_in)) >> 2 for i in range(n): dest[i] = val b = bytearray(8) print(b) set(b, 0x42424242) print(b) set1(b, 0x43434343) print(b) memset(b, 0x44444444, len(b) // 4) print(b) memset2(b, 0x45454545) print(b)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_ptr32_store.py
Python
apache-2.0
599
# test loading from ptr8 type @micropython.viper def get(src: ptr8) -> int: return src[0] @micropython.viper def get1(src: ptr8) -> int: return src[1] @micropython.viper def memadd(src: ptr8, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum @micropython.viper def memadd2(src_in) -> int: src = ptr8(src_in) n = int(len(src_in)) sum = 0 for i in range(n): sum += src[i] return sum b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 4)) print(memadd2(b))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_ptr8_load.py
Python
apache-2.0
558
# test ptr8 type @micropython.viper def set(dest: ptr8, val: int): dest[0] = val @micropython.viper def set1(dest: ptr8, val: int): dest[1] = val @micropython.viper def memset(dest: ptr8, val: int, n: int): for i in range(n): dest[i] = val @micropython.viper def memset2(dest_in, val: int): dest = ptr8(dest_in) n = int(len(dest_in)) for i in range(n): dest[i] = val b = bytearray(4) print(b) set(b, 41) print(b) set1(b, 42) print(b) memset(b, 43, len(b)) print(b) memset2(b, 44) print(b)
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_ptr8_store.py
Python
apache-2.0
543
# test standard Python subscr using viper types @micropython.viper def get(dest, i: int): i += 1 return dest[i] @micropython.viper def set(dest, i: int, val: int): i += 1 dest[i] = val + 1 ar = [i for i in range(3)] for i in range(len(ar)): set(ar, i - 1, i) print(ar) for i in range(len(ar)): print(get(ar, i - 1))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_subscr.py
Python
apache-2.0
348
# test try handling within a viper function # basic try-finally @micropython.viper def f(): try: fail finally: print("finally") try: f() except NameError: print("NameError") # nested try-except with try-finally @micropython.viper def f(): try: try: fail finally: print("finally") except NameError: print("NameError") f() # check that locals written to in try blocks keep their values @micropython.viper def f(): a = 100 try: print(a) a = 200 fail except NameError: print(a) a = 300 print(a) f()
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_try.py
Python
apache-2.0
648
# test various type conversions import micropython # converting incoming arg to bool @micropython.viper def f1(x: bool): print(x) f1(0) f1(1) f1([]) f1([1]) # taking and returning a bool @micropython.viper def f2(x: bool) -> bool: return x print(f2([])) print(f2([1])) # converting to bool within function @micropython.viper def f3(x) -> bool: return bool(x) print(f3([])) print(f3(-1))
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_types.py
Python
apache-2.0
409
# test with handling within a viper function class C: def __init__(self): print("__init__") def __enter__(self): print("__enter__") def __exit__(self, a, b, c): print("__exit__", a, b, c) # basic with @micropython.viper def f(): with C(): print(1) f() # nested with and try-except @micropython.viper def f(): try: with C(): print(1) fail print(2) except NameError: print("NameError") f()
YifuLiu/AliOS-Things
components/py_engine/tests/micropython/viper_with.py
Python
apache-2.0
507
try: str.count except AttributeError: print("SKIP") raise SystemExit # mad.py # Alf Clement 27-Mar-2014 # zero = 0 three = 3 print("1") print("2") print(three) print("{}".format(4)) five = 25 // 5 print(int(five)) j = 0 for i in range(4): j += i print(j) print(3 + 4) try: a = 4 // zero except: print(8) print("xxxxxxxxx".count("x")) def ten(): return 10 print(ten()) a = [] for i in range(13): a.append(i) print(a[11]) print(a[-1]) str = "0123456789" print(str[1] + str[3]) def p(s): print(s) p("14") p(15) class A: def __init__(self): self.a = 16 def print(self): print(self.a) def set(self, b): self.a = b a = A() a.print() a.set(17) a.print() b = A() b.set(a.a + 1) b.print() for i in range(20): pass print(i) if 20 > 30: a = "1" else: a = "2" if 0 < 4: print(a + "0") else: print(a + "1") a = [20, 21, 22, 23, 24] for i in a: if i < 21: continue if i > 21: break print(i) b = [a, a, a] print(b[1][2]) print(161 // 7) a = 24 while True: try: def gcheck(): global a print(a) gcheck() class c25: x = 25 x = c25() print(x.x) raise except: print(26) print(27 + zero) break print(28) k = 29 def f(): global k k = yield k print(next(f())) while True: k += 1 if k < 30: continue break print(k) for i in [1, 2, 3]: class A: def __init__(self, c): self.a = i + 10 * c b = A(3) print(b.a) print(34) p = 0 for i in range(35, -1, -1): print(i) p = p + 1 if p > 0: break p = 36 while p == 36: print(p) p = 37 print(p) for i in [38]: print(i) print(int(exec("def foo(): return 38") == None) + foo()) d = {} exec("def bar(): return 40", d) print(d["bar"]()) def fib2(n): result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a + b return result print(fib2(100)[-2] - 14) Answer = {} Answer["ForAll"] = 42 print(Answer["ForAll"]) i = 43 def f(i=i): print(i) i = 44 f() print(i) while True: try: if None != True: print(45) break else: print(0) except: print(0) print(46) print(46 + 1) def u(p): if p > 3: return 3 * p else: return u(2 * p) - 3 * u(p) print(u(16)) def u49(): return 49 print(u49())
YifuLiu/AliOS-Things
components/py_engine/tests/misc/features.py
Python
apache-2.0
2,488
# tests for things that are not implemented, or have non-compliant behaviour try: import uarray as array import ustruct except ImportError: print("SKIP") raise SystemExit # when super can't find self try: exec("def f(): super()") except SyntaxError: print("SyntaxError") # store to exception attribute is not allowed try: ValueError().x = 0 except AttributeError: print("AttributeError") # array deletion not implemented try: a = array.array("b", (1, 2, 3)) del a[1] except TypeError: print("TypeError") # slice with step!=1 not implemented try: a = array.array("b", (1, 2, 3)) print(a[3:2:2]) except NotImplementedError: print("NotImplementedError") # containment, looking for integer not implemented try: print(1 in array.array("B", b"12")) except NotImplementedError: print("NotImplementedError") # uPy raises TypeError, shold be ValueError try: "%c" % b"\x01\x02" except (TypeError, ValueError): print("TypeError, ValueError") # attributes/subscr not implemented try: print("{a[0]}".format(a=[1, 2])) except NotImplementedError: print("NotImplementedError") # str(...) with keywords not implemented try: str(b"abc", encoding="utf8") except NotImplementedError: print("NotImplementedError") # str.rsplit(None, n) not implemented try: "a a a".rsplit(None, 1) except NotImplementedError: print("NotImplementedError") # str.endswith(s, start) not implemented try: "abc".endswith("c", 1) except NotImplementedError: print("NotImplementedError") # str subscr with step!=1 not implemented try: print("abc"[1:2:3]) except NotImplementedError: print("NotImplementedError") # bytes(...) with keywords not implemented try: bytes("abc", encoding="utf8") except NotImplementedError: print("NotImplementedError") # bytes subscr with step!=1 not implemented try: b"123"[0:3:2] except NotImplementedError: print("NotImplementedError") # tuple load with step!=1 not implemented try: ()[2:3:4] except NotImplementedError: print("NotImplementedError") # list store with step!=1 not implemented try: [][2:3:4] = [] except NotImplementedError: print("NotImplementedError") # list delete with step!=1 not implemented try: del [][2:3:4] except NotImplementedError: print("NotImplementedError") # struct pack with too many args, not checked by uPy print(ustruct.pack("bb", 1, 2, 3)) # struct pack with too few args, not checked by uPy print(ustruct.pack("bb", 1)) # array slice assignment with unsupported RHS try: bytearray(4)[0:1] = [1, 2] except NotImplementedError: print("NotImplementedError") # can't assign attributes to a function def f(): pass try: f.x = 1 except AttributeError: print("AttributeError") # can't call a function type (ie make new instances of a function) try: type(f)() except TypeError: print("TypeError") # test when object explicitly listed at not-last position in parent tuple # this is not compliant with CPython because of illegal MRO class A: def foo(self): print("A.foo") class B(object, A): pass B().foo() # can't assign property (or other special accessors) to already-subclassed class class A: pass class B(A): pass try: A.bar = property() except AttributeError: print("AttributeError")
YifuLiu/AliOS-Things
components/py_engine/tests/misc/non_compliant.py
Python
apache-2.0
3,349
# lexer tests for things that are not implemented, or have non-compliant behaviour def test(code): try: exec(code) print("no Error") except SyntaxError: print("SyntaxError") except NotImplementedError: print("NotImplementedError") # uPy requires spaces between literal numbers and keywords, CPy doesn't try: eval("1and 0") except SyntaxError: print("SyntaxError") try: eval("1or 0") except SyntaxError: print("SyntaxError") try: eval("1if 1else 0") except SyntaxError: print("SyntaxError") try: eval("1if 0else 0") except SyntaxError: print("SyntaxError") # unicode name escapes are not implemented test('"\\N{LATIN SMALL LETTER A}"')
YifuLiu/AliOS-Things
components/py_engine/tests/misc/non_compliant_lexer.py
Python
apache-2.0
716
try: try: import uio as io import usys as sys except ImportError: import io import sys except ImportError: print("SKIP") raise SystemExit if hasattr(sys, "print_exception"): print_exception = sys.print_exception else: import traceback print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) def print_exc(e): buf = io.StringIO() print_exception(e, buf) s = buf.getvalue() for l in s.split("\n"): # uPy on pyboard prints <stdin> as file, so remove filename. if l.startswith(" File "): l = l.split('"') print(l[0], l[2]) # uPy and CPy tracebacks differ in that CPy prints a source line for # each traceback entry. In this case, we know that offending line # has 4-space indent, so filter it out. elif not l.startswith(" "): print(l) # basic exception message try: raise Exception("msg") except Exception as e: print("caught") print_exc(e) # exception message with more than 1 source-code line def f(): g() def g(): raise Exception("fail") try: f() except Exception as e: print("caught") print_exc(e) # Test that an exception propagated through a finally doesn't have a traceback added there try: try: f() finally: print("finally") except Exception as e: print("caught") print_exc(e) # Test that re-raising an exception doesn't add traceback info try: try: f() except Exception as e: print("reraise") print_exc(e) raise except Exception as e: print("caught") print_exc(e) # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: f.X}) return 1 try: f() except Exception as e: print_exc(e) # Test non-stream object passed as output object, only valid for uPy if hasattr(sys, "print_exception"): try: sys.print_exception(Exception, 1) had_exception = False except OSError: had_exception = True assert had_exception
YifuLiu/AliOS-Things
components/py_engine/tests/misc/print_exception.py
Python
apache-2.0
2,288
# evolve the RGEs of the standard model from electroweak scale up # by dpgeorge import math class RungeKutta(object): def __init__(self, functions, initConditions, t0, dh, save=True): self.Trajectory, self.save = [[t0] + initConditions], save self.functions = [lambda *args: 1.0] + list(functions) self.N, self.dh = len(self.functions), dh self.coeff = [1.0 / 6.0, 2.0 / 6.0, 2.0 / 6.0, 1.0 / 6.0] self.InArgCoeff = [0.0, 0.5, 0.5, 1.0] def iterate(self): step = self.Trajectory[-1][:] istep, iac = step[:], self.InArgCoeff k, ktmp = self.N * [0.0], self.N * [0.0] for ic, c in enumerate(self.coeff): for if_, f in enumerate(self.functions): arguments = [(x + k[i] * iac[ic]) for i, x in enumerate(istep)] try: feval = f(*arguments) except OverflowError: return False if abs(feval) > 1e2: # stop integrating return False ktmp[if_] = self.dh * feval k = ktmp[:] step = [s + c * k[ik] for ik, s in enumerate(step)] if self.save: self.Trajectory += [step] else: self.Trajectory = [step] return True def solve(self, finishtime): while self.Trajectory[-1][0] < finishtime: if not self.iterate(): break def solveNSteps(self, nSteps): for i in range(nSteps): if not self.iterate(): break def series(self): return zip(*self.Trajectory) # 1-loop RGES for the main parameters of the SM # couplings are: g1, g2, g3 of U(1), SU(2), SU(3); yt (top Yukawa), lambda (Higgs quartic) # see arxiv.org/abs/0812.4950, eqs 10-15 sysSM = ( lambda *a: 41.0 / 96.0 / math.pi ** 2 * a[1] ** 3, # g1 lambda *a: -19.0 / 96.0 / math.pi ** 2 * a[2] ** 3, # g2 lambda *a: -42.0 / 96.0 / math.pi ** 2 * a[3] ** 3, # g3 lambda *a: 1.0 / 16.0 / math.pi ** 2 * ( 9.0 / 2.0 * a[4] ** 3 - 8.0 * a[3] ** 2 * a[4] - 9.0 / 4.0 * a[2] ** 2 * a[4] - 17.0 / 12.0 * a[1] ** 2 * a[4] ), # yt lambda *a: 1.0 / 16.0 / math.pi ** 2 * ( 24.0 * a[5] ** 2 + 12.0 * a[4] ** 2 * a[5] - 9.0 * a[5] * (a[2] ** 2 + 1.0 / 3.0 * a[1] ** 2) - 6.0 * a[4] ** 4 + 9.0 / 8.0 * a[2] ** 4 + 3.0 / 8.0 * a[1] ** 4 + 3.0 / 4.0 * a[2] ** 2 * a[1] ** 2 ), # lambda ) def drange(start, stop, step): r = start while r < stop: yield r r += step def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): tstart = 0.0 for i in drange(0, range, 0.1 * range): for j in drange(0, range, 0.1 * range): rk = RungeKutta(system, trajStart(i, j), tstart, h) rk.solve(tend) # draw the line for tr in rk.Trajectory: x, y = trajPlot(tr) print(x, y) print() # draw the arrow continue l = (len(rk.Trajectory) - 1) / 3 if l > 0 and 2 * l < len(rk.Trajectory): p1 = rk.Trajectory[l] p2 = rk.Trajectory[2 * l] x1, y1 = trajPlot(p1) x2, y2 = trajPlot(p2) dx = -0.5 * (y2 - y1) # orthogonal to line dy = 0.5 * (x2 - x1) # orthogonal to line # l = math.sqrt(dx*dx + dy*dy) # if abs(l) > 1e-3: # l = 0.1 / l # dx *= l # dy *= l print(x1 + dx, y1 + dy) print(x2, y2) print(x1 - dx, y1 - dy) print() def singleTraj(system, trajStart, h=0.02, tend=1.0): tstart = 0.0 # compute the trajectory rk = RungeKutta(system, trajStart, tstart, h) rk.solve(tend) # print out trajectory for i in range(len(rk.Trajectory)): tr = rk.Trajectory[i] print(" ".join(["{:.4f}".format(t) for t in tr])) # phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) # initial conditions at M_Z singleTraj( sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10 ** 17) ) # true values
YifuLiu/AliOS-Things
components/py_engine/tests/misc/rge_sm.py
Python
apache-2.0
4,422
# test sys.atexit() function import usys try: usys.atexit except AttributeError: print("SKIP") raise SystemExit some_var = None def do_at_exit(): print("done at exit:", some_var) usys.atexit(do_at_exit) some_var = "ok" print("done before exit")
YifuLiu/AliOS-Things
components/py_engine/tests/misc/sys_atexit.py
Python
apache-2.0
269
try: import usys as sys except ImportError: import sys try: sys.exc_info except: print("SKIP") raise SystemExit def f(): print(sys.exc_info()[0:2]) try: raise ValueError("value", 123) except: print(sys.exc_info()[0:2]) f() # Outside except block, sys.exc_info() should be back to None's f() # Recursive except blocks are not handled - just don't # use exc_info() at all, use explicit variables in "except".
YifuLiu/AliOS-Things
components/py_engine/tests/misc/sys_exc_info.py
Python
apache-2.0
450
import sys try: sys.settrace except AttributeError: print("SKIP") raise SystemExit def print_stacktrace(frame, level=0): # Ignore CPython specific helpers. if frame.f_globals["__name__"].find("importlib") != -1: print_stacktrace(frame.f_back, level) return print( "%2d: %s@%s:%s => %s:%d" % ( level, " ", frame.f_globals["__name__"], frame.f_code.co_name, # Keep just the filename. "sys_settrace_" + frame.f_code.co_filename.split("sys_settrace_")[-1], frame.f_lineno, ) ) if frame.f_back: print_stacktrace(frame.f_back, level + 1) class _Prof: trace_count = 0 def trace_tick(self, frame, event, arg): self.trace_count += 1 print_stacktrace(frame) __prof__ = _Prof() alice_handler_set = False def trace_tick_handler_alice(frame, event, arg): print("### trace_handler::Alice event:", event) __prof__.trace_tick(frame, event, arg) return trace_tick_handler_alice bob_handler_set = False def trace_tick_handler_bob(frame, event, arg): print("### trace_handler::Bob event:", event) __prof__.trace_tick(frame, event, arg) return trace_tick_handler_bob def trace_tick_handler(frame, event, arg): # Ignore CPython specific helpers. to_ignore = ["importlib", "zipimport", "encodings"] frame_name = frame.f_globals["__name__"] if any(name in frame_name for name in to_ignore): return print("### trace_handler::main event:", event) __prof__.trace_tick(frame, event, arg) if frame.f_code.co_name != "factorial": return trace_tick_handler global alice_handler_set if event == "call" and not alice_handler_set: alice_handler_set = True return trace_tick_handler_alice global bob_handler_set if event == "call" and not bob_handler_set: bob_handler_set = True return trace_tick_handler_bob return trace_tick_handler def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) def do_tests(): # These commands are here to demonstrate some execution being traced. print("Who loves the sun?") print("Not every-", factorial(3)) from sys_settrace_subdir import sys_settrace_generic sys_settrace_generic.run_tests() return sys.settrace(trace_tick_handler) do_tests() sys.settrace(None) print("\n------------------ script exited ------------------") print("Total traces executed: ", __prof__.trace_count)
YifuLiu/AliOS-Things
components/py_engine/tests/misc/sys_settrace_features.py
Python
apache-2.0
2,585
# test sys.settrace with generators import sys try: sys.settrace except AttributeError: print("SKIP") raise SystemExit def print_stacktrace(frame, level=0): print( "%2d: %s@%s:%s => %s:%d" % ( level, " ", frame.f_globals["__name__"], frame.f_code.co_name, # Keep just the filename. "sys_settrace_" + frame.f_code.co_filename.split("sys_settrace_")[-1], frame.f_lineno, ) ) if frame.f_back: print_stacktrace(frame.f_back, level + 1) trace_count = 0 def trace_tick_handler(frame, event, arg): global trace_count print("### trace_handler::main event:", event) trace_count += 1 print_stacktrace(frame) return trace_tick_handler def test_generator(): def make_gen(): yield 1 << 0 yield 1 << 1 yield 1 << 2 return 1 << 3 gen = make_gen() r = 0 try: r += gen.send(None) while True: r += gen.send(None) except StopIteration as e: print("test_generator", r, e) gen = make_gen() r = 0 for i in gen: r += i print(r) sys.settrace(trace_tick_handler) test_generator() sys.settrace(None) print("Total traces executed: ", trace_count)
YifuLiu/AliOS-Things
components/py_engine/tests/misc/sys_settrace_generator.py
Python
apache-2.0
1,312
# test sys.settrace with while and for loops import sys try: sys.settrace except AttributeError: print("SKIP") raise SystemExit def print_stacktrace(frame, level=0): print( "%2d: %s@%s:%s => %s:%d" % ( level, " ", frame.f_globals["__name__"], frame.f_code.co_name, # Keep just the filename. "sys_settrace_" + frame.f_code.co_filename.split("sys_settrace_")[-1], frame.f_lineno, ) ) if frame.f_back: print_stacktrace(frame.f_back, level + 1) trace_count = 0 def trace_tick_handler(frame, event, arg): global trace_count print("### trace_handler::main event:", event) trace_count += 1 print_stacktrace(frame) return trace_tick_handler def test_loop(): # for loop r = 0 for i in range(3): r += i print("test_for_loop", r) # while loop r = 0 i = 0 while i < 3: r += i i += 1 print("test_while_loop", i) sys.settrace(trace_tick_handler) test_loop() sys.settrace(None) print("Total traces executed: ", trace_count)
YifuLiu/AliOS-Things
components/py_engine/tests/misc/sys_settrace_loop.py
Python
apache-2.0
1,144
print("Now comes the language constructions tests.") # function def test_func(): def test_sub_func(): print("test_function") test_sub_func() # closure def test_closure(msg): def make_closure(): print(msg) return make_closure # exception def test_exception(): try: raise Exception("test_exception") except Exception: pass finally: pass # listcomp def test_listcomp(): print("test_listcomp", [x for x in range(3)]) # lambda def test_lambda(): func_obj_1 = lambda a, b: a + b print(func_obj_1(10, 20)) # import def test_import(): from sys_settrace_subdir import sys_settrace_importme sys_settrace_importme.dummy() sys_settrace_importme.saysomething() # class class TLClass: def method(): pass pass def test_class(): class TestClass: __anynum = -9 def method(self): print("test_class_method") self.__anynum += 1 def prprty_getter(self): return self.__anynum def prprty_setter(self, what): self.__anynum = what prprty = property(prprty_getter, prprty_setter) cls = TestClass() cls.method() print("test_class_property", cls.prprty) cls.prprty = 12 print("test_class_property", cls.prprty) def run_tests(): test_func() test_closure_inst = test_closure("test_closure") test_closure_inst() test_exception() test_listcomp() test_lambda() test_class() test_import() print("And it's done!")
YifuLiu/AliOS-Things
components/py_engine/tests/misc/sys_settrace_subdir/sys_settrace_generic.py
Python
apache-2.0
1,561
print("Yep, I got imported.") try: x = const(1) except NameError: print("const not defined") const = lambda x: x _CNT01 = "CONST01" _CNT02 = const(123) A123 = const(123) a123 = const(123) def dummy(): return False def saysomething(): print("There, I said it.") def neverexecuted(): print("Never got here!") print("Yep, got here")
YifuLiu/AliOS-Things
components/py_engine/tests/misc/sys_settrace_subdir/sys_settrace_importme.py
Python
apache-2.0
361
# Test characteristic read/write/notify from both GATTS and GATTC. from micropython import const import time, machine, bluetooth TIMEOUT_MS = 5000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_WRITE = const(3) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_GATTC_READ_DONE = const(16) _IRQ_GATTC_WRITE_DONE = const(17) _IRQ_GATTC_NOTIFY = const(18) _IRQ_GATTC_INDICATE = const(19) _IRQ_GATTS_INDICATE_DONE = const(20) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = ( CHAR_UUID, bluetooth.FLAG_READ | bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY | bluetooth.FLAG_INDICATE, ) SERVICE = ( SERVICE_UUID, (CHAR,), ) SERVICES = (SERVICE,) waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_GATTS_WRITE: print("_IRQ_GATTS_WRITE", ble.gatts_read(data[-1])) elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: # conn_handle, def_handle, value_handle, properties, uuid = data if data[-1] == CHAR_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_READ_RESULT: print("_IRQ_GATTC_READ_RESULT", bytes(data[-1])) elif event == _IRQ_GATTC_READ_DONE: print("_IRQ_GATTC_READ_DONE", data[-1]) elif event == _IRQ_GATTC_WRITE_DONE: print("_IRQ_GATTC_WRITE_DONE", data[-1]) elif event == _IRQ_GATTC_NOTIFY: print("_IRQ_GATTC_NOTIFY", bytes(data[-1])) elif event == _IRQ_GATTC_INDICATE: print("_IRQ_GATTC_INDICATE", bytes(data[-1])) elif event == _IRQ_GATTS_INDICATE_DONE: print("_IRQ_GATTS_INDICATE_DONE", data[-1]) if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services(SERVICES) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Write initial characteristic value. ble.gatts_write(char_handle, "periph0") # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) # A # Wait for a write to the characteristic from the central, # then reply with a notification. wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) print("gatts_write") ble.gatts_write(char_handle, "periph1") print("gatts_notify") ble.gatts_notify(conn_handle, char_handle) # B # Wait for a write to the characteristic from the central, # then reply with value-included notification. wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) print("gatts_notify") ble.gatts_notify(conn_handle, char_handle, "periph2") # C # Wait for a write to the characteristic from the central, # then reply with an indication. wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) print("gatts_write") ble.gatts_write(char_handle, "periph3") print("gatts_indicate") ble.gatts_indicate(conn_handle, char_handle) wait_for_event(_IRQ_GATTS_INDICATE_DONE, TIMEOUT_MS) # Wait for the central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover characteristics. ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Issue read of characteristic, should get initial value. print("gattc_read") ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # Write to the characteristic, which will trigger a notification. print("gattc_write") ble.gattc_write(conn_handle, value_handle, "central0", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # A wait_for_event(_IRQ_GATTC_NOTIFY, TIMEOUT_MS) print("gattc_read") # Read the new value set immediately before notification. ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # Write to the characteristic, which will trigger a value-included notification. print("gattc_write") ble.gattc_write(conn_handle, value_handle, "central1", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # B wait_for_event(_IRQ_GATTC_NOTIFY, TIMEOUT_MS) print("gattc_read") # Read value should be unchanged. ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # Write to the characteristic, which will trigger an indication. print("gattc_write") ble.gattc_write(conn_handle, value_handle, "central2", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # C wait_for_event(_IRQ_GATTC_INDICATE, TIMEOUT_MS) print("gattc_read") # Read the new value set immediately before indication. ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # Disconnect from peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_characteristic.py
Python
apache-2.0
6,885
# Test BLE GAP advertising and scanning from micropython import const import time, machine, bluetooth _IRQ_SCAN_RESULT = const(5) _IRQ_SCAN_DONE = const(6) ADV_TIME_S = 3 def instance0(): multitest.globals(BDADDR=ble.config("mac")) multitest.next() print("gap_advertise(100_000, connectable=False)") ble.gap_advertise(100_000, b"\x02\x01\x06\x04\xffMPY", connectable=False) time.sleep(ADV_TIME_S) print("gap_advertise(20_000, connectable=True)") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY", connectable=True) time.sleep(ADV_TIME_S) print("gap_advertise(None)") ble.gap_advertise(None) ble.active(0) def instance1(): multitest.next() finished = False adv_types = {} adv_data = None def irq(ev, data): nonlocal finished, adv_types, adv_data if ev == _IRQ_SCAN_RESULT: if data[0] == BDADDR[0] and data[1] == BDADDR[1]: adv_types[data[2]] = True if adv_data is None: adv_data = bytes(data[4]) else: if adv_data != data[4]: adv_data = b"MISMATCH" elif ev == _IRQ_SCAN_DONE: finished = True try: ble.config(rxbuf=2000) except: pass ble.irq(irq) ble.gap_scan(2 * ADV_TIME_S * 1000, 10000, 10000) while not finished: machine.idle() ble.active(0) print("adv_types:", sorted(adv_types)) print("adv_data:", adv_data) ble = bluetooth.BLE() ble.active(1)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_gap_advertise.py
Python
apache-2.0
1,546
# Test BLE GAP connect/disconnect from micropython import const import time, machine, bluetooth TIMEOUT_MS = 4000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect, then wait for it to disconnect. wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) # Start advertising again. print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") # Wait for central to connect, then disconnect it. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) # Connect to peripheral and then let the peripheral disconnect us. # Extra scan timeout allows for the peripheral to receive the disconnect # event and start advertising again. print("gap_connect") ble.gap_connect(BDADDR[0], BDADDR[1], 5000) wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_gap_connect.py
Python
apache-2.0
2,787
# Test BLE GAP device name get/set from micropython import const import time, machine, bluetooth TIMEOUT_MS = 5000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_GATTC_READ_DONE = const(16) GAP_DEVICE_NAME_UUID = bluetooth.UUID(0x2A00) waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: if data[-1] == GAP_DEVICE_NAME_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_READ_RESULT: print("_IRQ_GATTC_READ_RESULT", bytes(data[-1])) if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) # Test setting and getting the GAP device name before registering services. ble.config(gap_name="GAP_NAME") print(ble.config("gap_name")) # Create an empty service and start advertising. ble.gatts_register_services([]) print("gap_advertise") multitest.next() try: # Do multiple iterations to test changing the name. for iteration in range(2): # Set the GAP device name and start advertising. ble.config(gap_name="GAP_NAME{}".format(iteration)) print(ble.config("gap_name")) ble.gap_advertise(20_000) # Wait for central to connect, then wait for it to disconnect. wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) wait_for_event(_IRQ_CENTRAL_DISCONNECT, 4 * TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: value_handle = None for iteration in range(2): # Wait for peripheral to start advertising. time.sleep_ms(500) # Connect to peripheral. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) if iteration == 0: # Only do characteristic discovery on the first iteration, # assume value_handle is unchanged on the second. print("gattc_discover_characteristics") ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Read the peripheral's GAP device name. print("gattc_read") ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # Disconnect from peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_gap_device_name.py
Python
apache-2.0
4,006
# Test BLE GAP connect/disconnect with pairing, and read an encrypted characteristic # TODO: add gap_passkey testing from micropython import const import time, machine, bluetooth if not hasattr(bluetooth.BLE, "gap_pair"): print("SKIP") raise SystemExit TIMEOUT_MS = 4000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_READ_REQUEST = const(4) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_ENCRYPTION_UPDATE = const(28) _FLAG_READ = const(0x0002) _FLAG_READ_ENCRYPTED = const(0x0200) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = (CHAR_UUID, _FLAG_READ | _FLAG_READ_ENCRYPTED) SERVICE = (SERVICE_UUID, (CHAR,)) waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_GATTS_READ_REQUEST: print("_IRQ_GATTS_READ_REQUEST") elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: if data[-1] == CHAR_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_READ_RESULT: print("_IRQ_GATTC_READ_RESULT", bytes(data[-1])) elif event == _IRQ_ENCRYPTION_UPDATE: print("_IRQ_ENCRYPTION_UPDATE", data[1], data[2], data[3]) if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services((SERVICE,)) ble.gatts_write(char_handle, "encrypted") print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect. wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) # Wait for pairing event. wait_for_event(_IRQ_ENCRYPTION_UPDATE, TIMEOUT_MS) # Wait for GATTS read request. wait_for_event(_IRQ_GATTS_READ_REQUEST, TIMEOUT_MS) # Wait for central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover characteristics (before pairing, doesn't need to be encrypted). ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Pair with the peripheral. print("gap_pair") ble.gap_pair(conn_handle) # Wait for the pairing event. wait_for_event(_IRQ_ENCRYPTION_UPDATE, TIMEOUT_MS) # Read the peripheral's characteristic, should be encrypted. print("gattc_read") ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # Disconnect from the peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.config(mitm=True, le_secure=True, bond=False) ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_gap_pair.py
Python
apache-2.0
4,353
# Test BLE GAP connect/disconnect with pairing and bonding, and read an encrypted # characteristic # TODO: reconnect after bonding to test that the secrets persist from micropython import const import time, machine, bluetooth if not hasattr(bluetooth.BLE, "gap_pair"): print("SKIP") raise SystemExit TIMEOUT_MS = 4000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_READ_REQUEST = const(4) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_ENCRYPTION_UPDATE = const(28) _IRQ_SET_SECRET = const(30) _FLAG_READ = const(0x0002) _FLAG_READ_ENCRYPTED = const(0x0200) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = (CHAR_UUID, _FLAG_READ | _FLAG_READ_ENCRYPTED) SERVICE = (SERVICE_UUID, (CHAR,)) waiting_events = {} secrets = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_GATTS_READ_REQUEST: print("_IRQ_GATTS_READ_REQUEST") elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: if data[-1] == CHAR_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_READ_RESULT: print("_IRQ_GATTC_READ_RESULT", bytes(data[-1])) elif event == _IRQ_ENCRYPTION_UPDATE: print("_IRQ_ENCRYPTION_UPDATE", data[1], data[2], data[3]) elif event == _IRQ_SET_SECRET: return True if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services((SERVICE,)) ble.gatts_write(char_handle, "encrypted") print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect. wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) # Wait for pairing event. wait_for_event(_IRQ_ENCRYPTION_UPDATE, TIMEOUT_MS) # Wait for GATTS read request. wait_for_event(_IRQ_GATTS_READ_REQUEST, TIMEOUT_MS) # Wait for central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover characteristics (before pairing, doesn't need to be encrypted). ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Pair with the peripheral. print("gap_pair") ble.gap_pair(conn_handle) # Wait for the pairing event. wait_for_event(_IRQ_ENCRYPTION_UPDATE, TIMEOUT_MS) # Read the peripheral's characteristic, should be encrypted. print("gattc_read") ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # Disconnect from the peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.config(mitm=True, le_secure=True, bond=True) ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_gap_pair_bond.py
Python
apache-2.0
4,495
# Test GATTC/S data transfer between peripheral and central, and use of gatts_set_buffer() from micropython import const import time, machine, bluetooth TIMEOUT_MS = 5000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_WRITE = const(3) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_SERVICE_RESULT = const(9) _IRQ_GATTC_SERVICE_DONE = const(10) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_GATTC_READ_DONE = const(16) _IRQ_GATTC_WRITE_DONE = const(17) _IRQ_GATTC_NOTIFY = const(18) SERVICE_UUID = bluetooth.UUID("00000001-1111-2222-3333-444444444444") CHAR_CTRL_UUID = bluetooth.UUID("00000002-1111-2222-3333-444444444444") CHAR_RX_UUID = bluetooth.UUID("00000003-1111-2222-3333-444444444444") CHAR_TX_UUID = bluetooth.UUID("00000004-1111-2222-3333-444444444444") CHAR_CTRL = (CHAR_CTRL_UUID, bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY) CHAR_RX = (CHAR_RX_UUID, bluetooth.FLAG_WRITE | bluetooth.FLAG_WRITE_NO_RESPONSE) CHAR_TX = (CHAR_TX_UUID, bluetooth.FLAG_NOTIFY) SERVICE = (SERVICE_UUID, (CHAR_CTRL, CHAR_RX, CHAR_TX)) SERVICES = (SERVICE,) waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_GATTS_WRITE: print("_IRQ_GATTS_WRITE") waiting_events[(event, data[1])] = None elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: if data[-1] == CHAR_CTRL_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[(event, CHAR_CTRL_UUID)] = data[2] elif data[-1] == CHAR_RX_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[(event, CHAR_RX_UUID)] = data[2] elif data[-1] == CHAR_TX_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[(event, CHAR_TX_UUID)] = data[2] elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_READ_RESULT: print("_IRQ_GATTC_READ_RESULT", data[-1]) elif event == _IRQ_GATTC_READ_DONE: print("_IRQ_GATTC_READ_DONE", data[-1]) elif event == _IRQ_GATTC_WRITE_DONE: print("_IRQ_GATTC_WRITE_DONE", data[-1]) elif event == _IRQ_GATTC_NOTIFY: print("_IRQ_GATTC_NOTIFY", bytes(data[-1])) waiting_events[(event, data[1])] = None if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_ctrl_handle, char_rx_handle, char_tx_handle),) = ble.gatts_register_services(SERVICES) # Increase the size of the rx buffer and enable append mode. ble.gatts_set_buffer(char_rx_handle, 100, True) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) # Wait for the central to signal that it's done with its part of the test. wait_for_event((_IRQ_GATTS_WRITE, char_ctrl_handle), 2 * TIMEOUT_MS) # Read all accumulated data from the central. print("gatts_read:", ble.gatts_read(char_rx_handle)) # Notify the central a few times. for i in range(4): time.sleep_ms(300) ble.gatts_notify(conn_handle, char_tx_handle, "message{}".format(i)) # Notify the central that we are done with our part of the test. time.sleep_ms(300) ble.gatts_notify(conn_handle, char_ctrl_handle, "OK") # Wait for the central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover characteristics. ble.gattc_discover_characteristics(conn_handle, 1, 65535) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) ctrl_value_handle = waiting_events[(_IRQ_GATTC_CHARACTERISTIC_RESULT, CHAR_CTRL_UUID)] rx_value_handle = waiting_events[(_IRQ_GATTC_CHARACTERISTIC_RESULT, CHAR_RX_UUID)] tx_value_handle = waiting_events[(_IRQ_GATTC_CHARACTERISTIC_RESULT, CHAR_TX_UUID)] # Write to the characteristic a few times, with and without response. for i in range(4): print("gattc_write") ble.gattc_write(conn_handle, rx_value_handle, "central{}".format(i), i & 1) if i & 1: wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) time.sleep_ms(400) # Write to say that we are done with our part of the test. ble.gattc_write(conn_handle, ctrl_value_handle, "OK", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Wait for notification that peripheral is done with its part of the test. wait_for_event((_IRQ_GATTC_NOTIFY, ctrl_value_handle), TIMEOUT_MS) # Disconnect from peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_gatt_data_transfer.py
Python
apache-2.0
6,161
# Test BLE GAP connect/disconnect from micropython import const import time, machine, bluetooth TIMEOUT_MS = 5000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_SERVICE_RESULT = const(9) _IRQ_GATTC_SERVICE_DONE = const(10) UUID_A = bluetooth.UUID(0x180D) UUID_B = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") SERVICE_A = ( UUID_A, (), ) SERVICE_B = ( UUID_B, (), ) SERVICES = (SERVICE_A, SERVICE_B) waiting_events = {} num_service_result = 0 def irq(event, data): global num_service_result if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_SERVICE_RESULT: if data[3] == UUID_A or data[3] == UUID_B: print("_IRQ_GATTC_SERVICE_RESULT", data[3]) num_service_result += 1 elif event == _IRQ_GATTC_SERVICE_DONE: print("_IRQ_GATTC_SERVICE_DONE") if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ble.gatts_register_services(SERVICES) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover services. ble.gattc_discover_services(conn_handle) wait_for_event(_IRQ_GATTC_SERVICE_DONE, TIMEOUT_MS) print("discovered:", num_service_result) # Disconnect from peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_gattc_discover_services.py
Python
apache-2.0
2,795
# Test L2CAP COC send/recv. # Sends a sequence of varying-sized payloads from central->peripheral, and # verifies that the other device sees the same data, then does the same thing # peripheral->central. from micropython import const import time, machine, bluetooth, random if not hasattr(bluetooth.BLE, "l2cap_connect"): print("SKIP") raise SystemExit TIMEOUT_MS = 1000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_L2CAP_ACCEPT = const(22) _IRQ_L2CAP_CONNECT = const(23) _IRQ_L2CAP_DISCONNECT = const(24) _IRQ_L2CAP_RECV = const(25) _IRQ_L2CAP_SEND_READY = const(26) _L2CAP_MTU = const(450) _L2CAP_PSM = const(22) _PAYLOAD_LEN = const(_L2CAP_MTU - 50) _PAYLOAD_LEN_STEP = -23 _NUM_PAYLOADS = const(16) _RANDOM_SEED = 22 waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: conn_handle, addr_type, addr = data print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = conn_handle elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_PERIPHERAL_CONNECT: conn_handle, addr_type, addr = data print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = conn_handle elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_L2CAP_ACCEPT: conn_handle, cid, psm, our_mtu, peer_mtu = data print("_IRQ_L2CAP_ACCEPT", psm, our_mtu, peer_mtu) waiting_events[event] = (conn_handle, cid, psm) elif event == _IRQ_L2CAP_CONNECT: conn_handle, cid, psm, our_mtu, peer_mtu = data print("_IRQ_L2CAP_CONNECT", psm, our_mtu, peer_mtu) waiting_events[event] = (conn_handle, cid, psm, our_mtu, peer_mtu) elif event == _IRQ_L2CAP_DISCONNECT: conn_handle, cid, psm, status = data print("_IRQ_L2CAP_DISCONNECT", psm, status) elif event == _IRQ_L2CAP_RECV: conn_handle, cid = data elif event == _IRQ_L2CAP_SEND_READY: conn_handle, cid, status = data if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) def send_data(ble, conn_handle, cid): buf = bytearray(_PAYLOAD_LEN) mv = memoryview(buf) print("l2cap_send", _NUM_PAYLOADS, _PAYLOAD_LEN) for i in range(_NUM_PAYLOADS): n = _PAYLOAD_LEN + i * _PAYLOAD_LEN_STEP for j in range(n): buf[j] = random.randint(0, 255) if not ble.l2cap_send(conn_handle, cid, mv[:n]): wait_for_event(_IRQ_L2CAP_SEND_READY, TIMEOUT_MS) def recv_data(ble, conn_handle, cid): buf = bytearray(_PAYLOAD_LEN) recv_bytes = 0 recv_correct = 0 expected_bytes = ( _PAYLOAD_LEN * _NUM_PAYLOADS + _PAYLOAD_LEN_STEP * _NUM_PAYLOADS * (_NUM_PAYLOADS - 1) // 2 ) print("l2cap_recvinto", expected_bytes) while recv_bytes < expected_bytes: wait_for_event(_IRQ_L2CAP_RECV, TIMEOUT_MS) while True: n = ble.l2cap_recvinto(conn_handle, cid, buf) if n == 0: break recv_bytes += n for i in range(n): if buf[i] == random.randint(0, 255): recv_correct += 1 return recv_bytes, recv_correct # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) print("l2cap_listen") ble.l2cap_listen(_L2CAP_PSM, _L2CAP_MTU) conn_handle, cid, psm = wait_for_event(_IRQ_L2CAP_ACCEPT, TIMEOUT_MS) conn_handle, cid, psm, our_mtu, peer_mtu = wait_for_event(_IRQ_L2CAP_CONNECT, TIMEOUT_MS) random.seed(_RANDOM_SEED) recv_bytes, recv_correct = recv_data(ble, conn_handle, cid) send_data(ble, conn_handle, cid) wait_for_event(_IRQ_L2CAP_DISCONNECT, TIMEOUT_MS) print("received", recv_bytes, recv_correct) # Wait for the central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) print("l2cap_connect") ble.l2cap_connect(conn_handle, _L2CAP_PSM, _L2CAP_MTU) conn_handle, cid, psm, our_mtu, peer_mtu = wait_for_event(_IRQ_L2CAP_CONNECT, TIMEOUT_MS) random.seed(_RANDOM_SEED) send_data(ble, conn_handle, cid) recv_bytes, recv_correct = recv_data(ble, conn_handle, cid) # Disconnect channel. print("l2cap_disconnect") ble.l2cap_disconnect(conn_handle, cid) wait_for_event(_IRQ_L2CAP_DISCONNECT, TIMEOUT_MS) print("received", recv_bytes, recv_correct) # Disconnect from peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_l2cap.py
Python
apache-2.0
5,657
# Test MTU exchange (initiated by both central and peripheral) and the effect on # notify and write size. # Seven connections are made (four central->peripheral, three peripheral->central). # # Test | Requested | Preferred | Result | Notes # 0 | 300 (C) | 256 (P) | 256 | # 1 | 300 (C) | 200 (P) | 200 | # 2 | 300 (C) | 400 (P) | 300 | # 3 | 300 (C) | 50 (P) | 50 | Shorter than 64 so the notification is truncated. # 4 | 290 (P) | 256 (C) | 256 | # 5 | 290 (P) | 190 (C) | 190 | # 6 | 290 (P) | 350 (C) | 290 | # # For each connection a notification is sent by the server (peripheral) and a characteristic # is written by the client (central) to ensure that the expected size is transmitted. # # Note: This currently fails on btstack for two reasons: # - btstack doesn't truncate writes to the MTU (it fails instead) # - btstack (in central mode) doesn't handle the peripheral initiating the MTU exchange from micropython import const import time, machine, bluetooth TIMEOUT_MS = 5000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_WRITE = const(3) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_WRITE_DONE = const(17) _IRQ_GATTC_NOTIFY = const(18) _IRQ_MTU_EXCHANGED = const(21) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = ( CHAR_UUID, bluetooth.FLAG_READ | bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY, ) SERVICE = ( SERVICE_UUID, (CHAR,), ) SERVICES = (SERVICE,) waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_GATTS_WRITE: print("_IRQ_GATTS_WRITE") elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: if data[-1] == CHAR_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_WRITE_DONE: print("_IRQ_GATTC_WRITE_DONE") elif event == _IRQ_GATTC_NOTIFY: print("_IRQ_GATTC_NOTIFY", len(data[-1]), chr(data[-1][0])) elif event == _IRQ_MTU_EXCHANGED: print("_IRQ_MTU_EXCHANGED", data[-1]) waiting_events[event] = data[-1] if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services(SERVICES) ble.gatts_set_buffer(char_handle, 500, False) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: for i in range(7): if i == 1: ble.config(mtu=200) elif i == 2: ble.config(mtu=400) elif i == 3: ble.config(mtu=50) elif i >= 4: ble.config(mtu=290) else: # This is the NimBLE default. ble.config(mtu=256) # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) if i >= 4: print("gattc_exchange_mtu") ble.gattc_exchange_mtu(conn_handle) mtu = wait_for_event(_IRQ_MTU_EXCHANGED, TIMEOUT_MS) print("gatts_notify") ble.gatts_notify(conn_handle, char_handle, str(i) * 64) # Extra timeout while client does service discovery. wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS * 2) print("gatts_read") data = ble.gatts_read(char_handle) print("characteristic len:", len(data), chr(data[0])) # Wait for the central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: for i in range(7): if i < 4: ble.config(mtu=300) elif i == 5: ble.config(mtu=190) elif i == 6: ble.config(mtu=350) else: ble.config(mtu=256) # Connect to peripheral and then disconnect. # Extra scan timeout allows for the peripheral to receive the previous disconnect # event and start advertising again. print("gap_connect") ble.gap_connect(BDADDR[0], BDADDR[1], 5000) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) if i < 4: print("gattc_exchange_mtu") ble.gattc_exchange_mtu(conn_handle) mtu = wait_for_event(_IRQ_MTU_EXCHANGED, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_NOTIFY, TIMEOUT_MS) print("gattc_discover_characteristics") ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Write 20 more than the MTU to test truncation. print("gattc_write") ble.gattc_write(conn_handle, value_handle, chr(ord("a") + i) * (mtu + 20), 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Disconnect from peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_mtu.py
Python
apache-2.0
6,620
# Test for sending notifications to subscribed clients. from micropython import const import time, machine, bluetooth TIMEOUT_MS = 5000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_WRITE = const(3) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_DESCRIPTOR_RESULT = const(13) _IRQ_GATTC_DESCRIPTOR_DONE = const(14) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_GATTC_READ_DONE = const(16) _IRQ_GATTC_WRITE_DONE = const(17) _IRQ_GATTC_NOTIFY = const(18) _IRQ_GATTC_INDICATE = const(19) _CCCD_UUID = bluetooth.UUID(const(0x2902)) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = ( CHAR_UUID, bluetooth.FLAG_READ | bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY | bluetooth.FLAG_INDICATE, ) SERVICE = ( SERVICE_UUID, (CHAR,), ) SERVICES = (SERVICE,) waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_GATTS_WRITE: print("_IRQ_GATTS_WRITE", ble.gatts_read(data[-1])) elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: # conn_handle, def_handle, value_handle, properties, uuid = data if data[-1] == CHAR_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_DESCRIPTOR_RESULT: # conn_handle, dsc_handle, uuid = data if data[-1] == _CCCD_UUID: print("_IRQ_GATTC_DESCRIPTOR_RESULT", data[-1]) waiting_events[event] = data[1] else: return elif event == _IRQ_GATTC_DESCRIPTOR_DONE: print("_IRQ_GATTC_DESCRIPTOR_DONE") elif event == _IRQ_GATTC_READ_RESULT: print("_IRQ_GATTC_READ_RESULT", bytes(data[-1])) elif event == _IRQ_GATTC_READ_DONE: print("_IRQ_GATTC_READ_DONE", data[-1]) elif event == _IRQ_GATTC_WRITE_DONE: print("_IRQ_GATTC_WRITE_DONE", data[-1]) elif event == _IRQ_GATTC_NOTIFY: print("_IRQ_GATTC_NOTIFY", bytes(data[-1])) elif event == _IRQ_GATTC_INDICATE: print("_IRQ_GATTC_NOTIFY", bytes(data[-1])) if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services(SERVICES) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") # \x04\x09MPY multitest.next() try: # Write initial characteristic value (will be read by client). ble.gatts_write(char_handle, "periph0") ### # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS * 10) # A # Wait for a write to the characteristic from the central (to synchronise). wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) print("sync A") # This should be local-only. ble.gatts_write(char_handle, "periph1") time.sleep_ms(100) # Update local-only, then force notify. ble.gatts_write(char_handle, "periph2") ble.gatts_notify(conn_handle, char_handle) ### time.sleep_ms(100) # Update local and notify subscribers. No notification should be sent. ble.gatts_write(char_handle, "periph3", True) time.sleep_ms(100) multitest.broadcast("A") # B # Synchronise with the client (which should now be subscribed for notify). wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) print("sync B") # This should be local-only (send_update=False). ble.gatts_write(char_handle, "periph4", False) time.sleep_ms(100) # This should notify the subscribed client. ble.gatts_write(char_handle, "periph5", True) ### time.sleep_ms(100) multitest.broadcast("B") # C # Synchronise with the client (which should now be subscribed for indicate). wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) print("sync C") # This should be local-only (send_update=False). ble.gatts_write(char_handle, "periph6", False) time.sleep_ms(100) # This should indicate the subscribed client. ble.gatts_write(char_handle, "periph7", True) ### time.sleep_ms(100) multitest.broadcast("C") # D # Synchronise with the client (which should now be unsubscribed). wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) print("sync D") # This should be local-only (send_update=False). ble.gatts_write(char_handle, "periph8", False) time.sleep_ms(100) # This should be local-only (no more subscribers). ble.gatts_write(char_handle, "periph9", True) time.sleep_ms(100) # Update local-only, then another force notify. ble.gatts_write(char_handle, "periph10") ble.gatts_notify(conn_handle, char_handle) ### time.sleep_ms(100) multitest.broadcast("D") # Wait for the central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover characteristics. ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Discover CCCD. ble.gattc_discover_descriptors(conn_handle, value_handle, value_handle + 5) cccd_handle = wait_for_event(_IRQ_GATTC_DESCRIPTOR_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_DESCRIPTOR_DONE, TIMEOUT_MS) # Issue read of characteristic, should get initial value. print("gattc_read") ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) # While the four states are active, all incoming notifications # and indications will be printed by the event handler. We # should only expect to see certain ones. # Start unsubscribed. # Write to the characteristic (triggers A). print("gattc_write") ble.gattc_write(conn_handle, value_handle, "central0", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Wait for A to complete. multitest.wait("A") # Subscribe for notify. ble.gattc_write(conn_handle, cccd_handle, b"\x01\x00", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Write to the characteristic (triggers B). print("gattc_write") ble.gattc_write(conn_handle, value_handle, "central1", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Wait for B to complete. multitest.wait("B") # Subscribe for indicate. ble.gattc_write(conn_handle, cccd_handle, b"\x02\x00", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Write to the characteristic (triggers C). print("gattc_write") ble.gattc_write(conn_handle, value_handle, "central2", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Wait for C to complete. multitest.wait("C") # Unsubscribe. ble.gattc_write(conn_handle, cccd_handle, b"\x00\x00", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Write to the characteristic (triggers D). print("gattc_write") ble.gattc_write(conn_handle, value_handle, "central3", 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Wait for D to complete. multitest.wait("D") # Disconnect from peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/ble_subscribe.py
Python
apache-2.0
9,093
# Write characteristic from central to peripheral and time data rate. from micropython import const import time, machine, bluetooth TIMEOUT_MS = 2000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_WRITE = const(3) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_WRITE_DONE = const(17) _IRQ_MTU_EXCHANGED = const(21) # How long to run the test for. _NUM_NOTIFICATIONS = const(40) _MTU_SIZE = const(131) _CHAR_SIZE = const(_MTU_SIZE - 3) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = (CHAR_UUID, bluetooth.FLAG_WRITE | bluetooth.FLAG_WRITE_NO_RESPONSE) SERVICE = (SERVICE_UUID, (CHAR,)) SERVICES = (SERVICE,) packet_sequence = 0 waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_CONNECT: waiting_events[event] = data[0] elif event == _IRQ_GATTS_WRITE: global packet_sequence conn_handle, attr_handle = data data = ble.gatts_read(attr_handle) if not (data[0] == packet_sequence and data[-1] == (256 - packet_sequence) & 0xFF): print("_IRQ_GATTS_WRITE data invalid:", packet_sequence, data) elif packet_sequence % 10 == 0: print("_IRQ_GATTS_WRITE", packet_sequence) packet_sequence += 1 elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: # conn_handle, def_handle, value_handle, properties, uuid = data if data[-1] == CHAR_UUID: waiting_events[event] = data[2] else: return elif event == _IRQ_MTU_EXCHANGED: # ATT MTU exchange complete (either initiated by us or the remote device). conn_handle, mtu = data print("_IRQ_MTU_EXCHANGED:", mtu) if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services(SERVICES) ble.gatts_set_buffer(char_handle, _CHAR_SIZE) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) # Wait for central to disconnect us. wait_for_event(_IRQ_CENTRAL_DISCONNECT, 30000) print("final packet_sequence:", packet_sequence) finally: ble.active(0) # Acting in central role. def instance1(): global packet_sequence ((char_handle,),) = ble.gatts_register_services(SERVICES) multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.config(mtu=_MTU_SIZE) ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) ble.gattc_exchange_mtu(conn_handle) # Discover characteristics. ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Send data! data = bytearray(ord("A") + (i % 64) for i in range(_CHAR_SIZE)) for mode in (0, 1): ticks_start = time.ticks_ms() for i in range(_NUM_NOTIFICATIONS): data[0] = packet_sequence data[-1] = 256 - packet_sequence if packet_sequence % 10 == 0: print("gattc_write", packet_sequence) if mode == 0: while True: try: ble.gattc_write(conn_handle, value_handle, data, mode) break except OSError: pass else: ble.gattc_write(conn_handle, value_handle, data, mode) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) packet_sequence += 1 ticks_end = time.ticks_ms() ticks_total = time.ticks_diff(ticks_end, ticks_start) print( "Did {} writes in {} ms. {} ms/write, {} bytes/sec".format( _NUM_NOTIFICATIONS, ticks_total, ticks_total / _NUM_NOTIFICATIONS, _NUM_NOTIFICATIONS * len(data) * 1000 // ticks_total, ) ) time.sleep_ms(100) # DIsconnect the peripheral. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, 20000) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/perf_gatt_char_write.py
Python
apache-2.0
5,254
# Ping-pong GATT notifications between two devices. from micropython import const import time, machine, bluetooth TIMEOUT_MS = 2000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_NOTIFY = const(18) # How long to run the test for. _NUM_NOTIFICATIONS = const(50) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = ( CHAR_UUID, bluetooth.FLAG_NOTIFY, ) SERVICE = ( SERVICE_UUID, (CHAR,), ) SERVICES = (SERVICE,) is_central = False waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_CONNECT: waiting_events[event] = data[0] elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: # conn_handle, def_handle, value_handle, properties, uuid = data if data[-1] == CHAR_UUID: waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_NOTIFY: if is_central: conn_handle, value_handle, notify_data = data ble.gatts_notify(conn_handle, value_handle, b"central" + notify_data) if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services(SERVICES) print("gap_advertise") ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) # Discover characteristics. ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # Give the central enough time to discover chars. time.sleep_ms(500) ticks_start = time.ticks_ms() for i in range(_NUM_NOTIFICATIONS): # Send a notification and wait for a response. ble.gatts_notify(conn_handle, value_handle, "peripheral" + str(i)) wait_for_event(_IRQ_GATTC_NOTIFY, TIMEOUT_MS) ticks_end = time.ticks_ms() ticks_total = time.ticks_diff(ticks_end, ticks_start) print( "Acknowledged {} notifications in {} ms. {} ms/notification.".format( _NUM_NOTIFICATIONS, ticks_total, ticks_total // _NUM_NOTIFICATIONS ) ) # Disconnect the central. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): global is_central is_central = True ((char_handle,),) = ble.gatts_register_services(SERVICES) multitest.next() try: # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover characteristics. ble.gattc_discover_characteristics(conn_handle, 1, 65535) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) # The IRQ handler will respond to each notification. # Wait for the peripheral to disconnect us. wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, 20000) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/perf_gatt_notify.py
Python
apache-2.0
4,134
# Send L2CAP data as fast as possible and time it. from micropython import const import time, machine, bluetooth, random if not hasattr(bluetooth.BLE, "l2cap_connect"): print("SKIP") raise SystemExit TIMEOUT_MS = 1000 _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_L2CAP_ACCEPT = const(22) _IRQ_L2CAP_CONNECT = const(23) _IRQ_L2CAP_DISCONNECT = const(24) _IRQ_L2CAP_RECV = const(25) _IRQ_L2CAP_SEND_READY = const(26) _L2CAP_PSM = const(22) _L2CAP_MTU = const(512) _PAYLOAD_LEN = const(_L2CAP_MTU) _NUM_PAYLOADS = const(20) _RANDOM_SEED = 22 waiting_events = {} def irq(event, data): if event == _IRQ_CENTRAL_CONNECT: conn_handle, addr_type, addr = data waiting_events[event] = conn_handle elif event == _IRQ_PERIPHERAL_CONNECT: conn_handle, addr_type, addr = data waiting_events[event] = conn_handle elif event == _IRQ_L2CAP_ACCEPT: conn_handle, cid, psm, our_mtu, peer_mtu = data waiting_events[event] = (conn_handle, cid, psm) elif event == _IRQ_L2CAP_CONNECT: conn_handle, cid, psm, our_mtu, peer_mtu = data waiting_events[event] = (conn_handle, cid, psm, our_mtu, peer_mtu) if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) def send_data(ble, conn_handle, cid): buf = bytearray(_PAYLOAD_LEN) for i in range(_NUM_PAYLOADS): for j in range(_PAYLOAD_LEN): buf[j] = random.randint(0, 255) if not ble.l2cap_send(conn_handle, cid, buf): wait_for_event(_IRQ_L2CAP_SEND_READY, TIMEOUT_MS) def recv_data(ble, conn_handle, cid): buf = bytearray(_PAYLOAD_LEN) recv_bytes = 0 recv_correct = 0 expected_bytes = _PAYLOAD_LEN * _NUM_PAYLOADS ticks_first_byte = 0 while recv_bytes < expected_bytes: wait_for_event(_IRQ_L2CAP_RECV, TIMEOUT_MS) if not ticks_first_byte: ticks_first_byte = time.ticks_ms() while True: n = ble.l2cap_recvinto(conn_handle, cid, buf) if n == 0: break recv_bytes += n for i in range(n): if buf[i] == random.randint(0, 255): recv_correct += 1 ticks_end = time.ticks_ms() return recv_bytes, recv_correct, time.ticks_diff(ticks_end, ticks_first_byte) # Acting in peripheral role. def instance0(): multitest.globals(BDADDR=ble.config("mac")) ble.gap_advertise(20_000, b"\x02\x01\x06\x04\xffMPY") multitest.next() try: # Wait for central to connect to us. conn_handle = wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) ble.l2cap_listen(_L2CAP_PSM, _L2CAP_MTU) conn_handle, cid, psm = wait_for_event(_IRQ_L2CAP_ACCEPT, TIMEOUT_MS) conn_handle, cid, psm, our_mtu, peer_mtu = wait_for_event(_IRQ_L2CAP_CONNECT, TIMEOUT_MS) random.seed(_RANDOM_SEED) send_data(ble, conn_handle, cid) wait_for_event(_IRQ_L2CAP_DISCONNECT, TIMEOUT_MS) # Wait for the central to disconnect. wait_for_event(_IRQ_CENTRAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) # Acting in central role. def instance1(): multitest.next() try: # Connect to peripheral and then disconnect. ble.gap_connect(*BDADDR) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) ble.l2cap_connect(conn_handle, _L2CAP_PSM, _L2CAP_MTU) conn_handle, cid, psm, our_mtu, peer_mtu = wait_for_event(_IRQ_L2CAP_CONNECT, TIMEOUT_MS) random.seed(_RANDOM_SEED) recv_bytes, recv_correct, total_ticks = recv_data(ble, conn_handle, cid) # Disconnect channel. ble.l2cap_disconnect(conn_handle, cid) wait_for_event(_IRQ_L2CAP_DISCONNECT, TIMEOUT_MS) print( "Received {}/{} bytes in {} ms. {} B/s".format( recv_bytes, recv_correct, total_ticks, recv_bytes * 1000 // total_ticks ) ) # Disconnect from peripheral. ble.gap_disconnect(conn_handle) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, TIMEOUT_MS) finally: ble.active(0) ble = bluetooth.BLE() ble.active(1) ble.irq(irq)
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/perf_l2cap.py
Python
apache-2.0
4,566
# Test concurrency between filesystem access and BLE host. This is # particularly relevant on STM32WB where the second core is stalled while # flash operations are in progress. from micropython import const import time, machine, bluetooth, os TIMEOUT_MS = 10000 LOG_PATH_INSTANCE0 = "stress_log_filesystem_0.log" LOG_PATH_INSTANCE1 = "stress_log_filesystem_1.log" _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_WRITE = const(3) _IRQ_GATTS_READ_REQUEST = const(4) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_SERVICE_RESULT = const(9) _IRQ_GATTC_SERVICE_DONE = const(10) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_GATTC_READ_DONE = const(16) _IRQ_GATTC_WRITE_DONE = const(17) SERVICE_UUID = bluetooth.UUID("A5A5A5A5-FFFF-9999-1111-5A5A5A5A5A5A") CHAR_UUID = bluetooth.UUID("00000000-1111-2222-3333-444444444444") CHAR = ( CHAR_UUID, bluetooth.FLAG_READ | bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY | bluetooth.FLAG_INDICATE, ) SERVICE = ( SERVICE_UUID, (CHAR,), ) SERVICES = (SERVICE,) waiting_events = {} log_file = None def write_log(*args): if log_file: print(*args, file=log_file) log_file.flush() last_file_write = 0 def periodic_log_write(): global last_file_write t = time.ticks_ms() if time.ticks_diff(t, last_file_write) > 50: write_log("tick") last_file_write = t def irq(event, data): write_log("event", event) if event == _IRQ_CENTRAL_CONNECT: print("_IRQ_CENTRAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_CENTRAL_DISCONNECT: print("_IRQ_CENTRAL_DISCONNECT") elif event == _IRQ_PERIPHERAL_CONNECT: print("_IRQ_PERIPHERAL_CONNECT") waiting_events[event] = data[0] elif event == _IRQ_PERIPHERAL_DISCONNECT: print("_IRQ_PERIPHERAL_DISCONNECT") elif event == _IRQ_GATTC_SERVICE_RESULT: # conn_handle, start_handle, end_handle, uuid = data if data[-1] == SERVICE_UUID: print("_IRQ_GATTC_SERVICE_RESULT", data[3]) waiting_events[event] = (data[1], data[2]) else: return elif event == _IRQ_GATTC_SERVICE_DONE: print("_IRQ_GATTC_SERVICE_DONE") elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT: # conn_handle, def_handle, value_handle, properties, uuid = data if data[-1] == CHAR_UUID: print("_IRQ_GATTC_CHARACTERISTIC_RESULT", data[-1]) waiting_events[event] = data[2] else: return elif event == _IRQ_GATTC_CHARACTERISTIC_DONE: print("_IRQ_GATTC_CHARACTERISTIC_DONE") elif event == _IRQ_GATTC_READ_RESULT: print("_IRQ_GATTC_READ_RESULT", bytes(data[-1])) elif event == _IRQ_GATTC_READ_DONE: print("_IRQ_GATTC_READ_DONE", data[-1]) elif event == _IRQ_GATTC_WRITE_DONE: print("_IRQ_GATTC_WRITE_DONE", data[-1]) elif event == _IRQ_GATTS_WRITE: print("_IRQ_GATTS_WRITE") elif event == _IRQ_GATTS_READ_REQUEST: print("_IRQ_GATTS_READ_REQUEST") if event not in waiting_events: waiting_events[event] = None def wait_for_event(event, timeout_ms): t0 = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), t0) < timeout_ms: periodic_log_write() if event in waiting_events: return waiting_events.pop(event) machine.idle() raise ValueError("Timeout waiting for {}".format(event)) # Acting in peripheral role. def instance0(): global log_file log_file = open(LOG_PATH_INSTANCE0, "w") write_log("start") ble.active(1) ble.irq(irq) multitest.globals(BDADDR=ble.config("mac")) ((char_handle,),) = ble.gatts_register_services(SERVICES) multitest.next() try: for repeat in range(2): print("gap_advertise") ble.gap_advertise(50_000, b"\x02\x01\x06\x04\xffMPY") # Wait for central to connect, do a sequence of read/write, then disconnect. wait_for_event(_IRQ_CENTRAL_CONNECT, TIMEOUT_MS) for op in range(4): wait_for_event(_IRQ_GATTS_READ_REQUEST, TIMEOUT_MS) wait_for_event(_IRQ_GATTS_WRITE, TIMEOUT_MS) wait_for_event(_IRQ_CENTRAL_DISCONNECT, 2 * TIMEOUT_MS) finally: ble.active(0) log_file.close() os.unlink(LOG_PATH_INSTANCE0) # Acting in central role. def instance1(): global log_file log_file = open(LOG_PATH_INSTANCE1, "w") write_log("start") ble.active(1) ble.irq(irq) multitest.next() try: for repeat in range(2): # Connect to peripheral and then disconnect. print("gap_connect") ble.gap_connect(BDADDR[0], BDADDR[1], 5000) conn_handle = wait_for_event(_IRQ_PERIPHERAL_CONNECT, TIMEOUT_MS) # Discover services. print("gattc_discover_services") ble.gattc_discover_services(conn_handle) start_handle, end_handle = wait_for_event(_IRQ_GATTC_SERVICE_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_SERVICE_DONE, TIMEOUT_MS) # Discover characteristics. print("gattc_discover_characteristics") ble.gattc_discover_characteristics(conn_handle, start_handle, end_handle) value_handle = wait_for_event(_IRQ_GATTC_CHARACTERISTIC_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_CHARACTERISTIC_DONE, TIMEOUT_MS) for op in range(4): print("gattc_read") ble.gattc_read(conn_handle, value_handle) wait_for_event(_IRQ_GATTC_READ_RESULT, TIMEOUT_MS) wait_for_event(_IRQ_GATTC_READ_DONE, TIMEOUT_MS) print("gattc_write") ble.gattc_write(conn_handle, value_handle, "{}".format(op), 1) wait_for_event(_IRQ_GATTC_WRITE_DONE, TIMEOUT_MS) # Disconnect. print("gap_disconnect:", ble.gap_disconnect(conn_handle)) wait_for_event(_IRQ_PERIPHERAL_DISCONNECT, 2 * TIMEOUT_MS) finally: ble.active(0) log_file.close() os.unlink(LOG_PATH_INSTANCE1) ble = bluetooth.BLE()
YifuLiu/AliOS-Things
components/py_engine/tests/multi_bluetooth/stress_log_filesystem.py
Python
apache-2.0
6,304
# Simple test creating an SSL connection and transferring some data # This test won't run under CPython because it requires key/cert import usocket as socket, ussl as ssl PORT = 8000 # Server def instance0(): multitest.globals(IP=multitest.get_network_ip()) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(socket.getaddrinfo("0.0.0.0", PORT)[0][-1]) s.listen(1) multitest.next() s2, _ = s.accept() s2 = ssl.wrap_socket(s2, server_side=True) print(s2.read(16)) s2.write(b"server to client") s.close() # Client def instance1(): multitest.next() s = socket.socket() s.connect(socket.getaddrinfo(IP, PORT)[0][-1]) s = ssl.wrap_socket(s) s.write(b"client to server") print(s.read(16)) s.close()
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/ssl_data.py
Python
apache-2.0
803
# Test recv on socket that just accepted a connection import socket PORT = 8000 # Server def instance0(): multitest.globals(IP=multitest.get_network_ip()) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(socket.getaddrinfo("0.0.0.0", PORT)[0][-1]) s.listen(1) multitest.next() s.accept() try: print("recv", s.recv(10)) # should raise Errno 107 ENOTCONN except OSError as er: print(er.errno) s.close() # Client def instance1(): multitest.next() s = socket.socket() s.connect(socket.getaddrinfo(IP, PORT)[0][-1]) s.send(b"GET / HTTP/1.0\r\n\r\n") s.close()
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/tcp_accept_recv.py
Python
apache-2.0
672
# Test when client does a TCP RST on an open connection import struct, time, socket, select PORT = 8000 def convert_poll_list(l): # To be compatible across all ports/targets return [ev for _, ev in l] # Server def instance0(): multitest.globals(IP=multitest.get_network_ip()) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(socket.getaddrinfo("0.0.0.0", PORT)[0][-1]) s.listen(1) multitest.next() s2, _ = s.accept() s2.setblocking(False) poll = select.poll() poll.register(s2, select.POLLIN) time.sleep(0.4) print(convert_poll_list(poll.poll(1000))) # TODO: the following recv don't work with lwip, it abandons data upon TCP RST try: print(s2.recv(10)) print(convert_poll_list(poll.poll(1000))) print(s2.recv(10)) print(convert_poll_list(poll.poll(1000))) print(s2.recv(10)) print(convert_poll_list(poll.poll(1000))) except OSError as er: print(er.errno) print(convert_poll_list(poll.poll(1000))) # TODO lwip raises here but apparently it shouldn't print(s2.recv(10)) print(convert_poll_list(poll.poll(1000))) s.close() # Client def instance1(): if not hasattr(socket, "SO_LINGER"): multitest.skip() multitest.next() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.connect(socket.getaddrinfo(IP, PORT)[0][-1]) lgr_onoff = 1 lgr_linger = 0 s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", lgr_onoff, lgr_linger)) s.send(b"GET / HTTP/1.0\r\n\r\n") time.sleep(0.2) s.close() # This issues a TCP RST since we've set the linger option
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/tcp_client_rst.py
Python
apache-2.0
1,696
# Simple test of a TCP server and client transferring data import socket PORT = 8000 # Server def instance0(): multitest.globals(IP=multitest.get_network_ip()) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(socket.getaddrinfo("0.0.0.0", PORT)[0][-1]) s.listen(1) multitest.next() s2, _ = s.accept() print(s2.recv(16)) s2.send(b"server to client") s.close() # Client def instance1(): multitest.next() s = socket.socket() s.connect(socket.getaddrinfo(IP, PORT)[0][-1]) s.send(b"client to server") print(s.recv(16)) s.close()
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/tcp_data.py
Python
apache-2.0
628
# Test TCP server with client issuing TCP RST part way through read try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit import struct, time, socket PORT = 8000 async def handle_connection(reader, writer): data = await reader.read(10) # should succeed print(data) await asyncio.sleep(0.2) # wait for client to drop connection try: data = await reader.read(100) print(data) writer.close() await writer.wait_closed() except OSError as er: print("OSError", er.errno) ev.set() async def main(): global ev ev = asyncio.Event() server = await asyncio.start_server(handle_connection, "0.0.0.0", PORT) multitest.next() async with server: await asyncio.wait_for(ev.wait(), 10) def instance0(): multitest.globals(IP=multitest.get_network_ip()) asyncio.run(main()) def instance1(): if not hasattr(socket, "SO_LINGER"): multitest.skip() multitest.next() s = socket.socket() s.connect(socket.getaddrinfo(IP, PORT)[0][-1]) lgr_onoff = 1 lgr_linger = 0 s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", lgr_onoff, lgr_linger)) s.send(b"GET / HTTP/1.0\r\n\r\n") time.sleep(0.1) s.close() # This issues a TCP RST since we've set the linger option
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/uasyncio_tcp_client_rst.py
Python
apache-2.0
1,416
# Test uasyncio TCP stream closing then writing try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit PORT = 8000 async def handle_connection(reader, writer): # Write data to ensure connection writer.write(b"x") await writer.drain() # Read, should return nothing print("read:", await reader.read(100)) # Close connection print("close") writer.close() await writer.wait_closed() print("done") ev.set() async def tcp_server(): global ev ev = asyncio.Event() server = await asyncio.start_server(handle_connection, "0.0.0.0", PORT) print("server running") multitest.next() async with server: await asyncio.wait_for(ev.wait(), 5) async def tcp_client(): reader, writer = await asyncio.open_connection(IP, PORT) # Read data to ensure connection print("read:", await reader.read(1)) # Close connection print("close") writer.close() await writer.wait_closed() # Try writing data to the closed connection print("write") try: writer.write(b"x") await writer.drain() except OSError: print("OSError") def instance0(): multitest.globals(IP=multitest.get_network_ip()) asyncio.run(tcp_server()) def instance1(): multitest.next() asyncio.run(tcp_client())
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/uasyncio_tcp_close_write.py
Python
apache-2.0
1,424
# Test uasyncio stream readexactly() method using TCP server/client try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit PORT = 8000 async def handle_connection(reader, writer): writer.write(b"a") await writer.drain() # Split the first 2 bytes up so the client must wait for the second one await asyncio.sleep(0.1) writer.write(b"b") await writer.drain() writer.write(b"c") await writer.drain() writer.write(b"d") await writer.drain() print("close") writer.close() await writer.wait_closed() print("done") ev.set() async def tcp_server(): global ev ev = asyncio.Event() server = await asyncio.start_server(handle_connection, "0.0.0.0", PORT) print("server running") multitest.next() async with server: await asyncio.wait_for(ev.wait(), 10) async def tcp_client(): reader, writer = await asyncio.open_connection(IP, PORT) print(await reader.readexactly(2)) print(await reader.readexactly(0)) print(await reader.readexactly(1)) try: print(await reader.readexactly(2)) except EOFError as er: print("EOFError") print(await reader.readexactly(0)) def instance0(): multitest.globals(IP=multitest.get_network_ip()) asyncio.run(tcp_server()) def instance1(): multitest.next() asyncio.run(tcp_client())
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/uasyncio_tcp_readexactly.py
Python
apache-2.0
1,470
# Test uasyncio stream readinto() method using TCP server/client try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit try: import uarray as array except ImportError: try: import array except ImportError: print("SKIP") raise SystemExit PORT = 8000 async def handle_connection(reader, writer): writer.write(b"ab") await writer.drain() writer.write(b"c") await writer.drain() print("close") writer.close() await writer.wait_closed() print("done") ev.set() async def tcp_server(): global ev ev = asyncio.Event() server = await asyncio.start_server(handle_connection, "0.0.0.0", PORT) print("server running") multitest.next() async with server: await asyncio.wait_for(ev.wait(), 10) 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 instance0(): multitest.globals(IP=multitest.get_network_ip()) asyncio.run(tcp_server()) def instance1(): multitest.next() asyncio.run(tcp_client())
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/uasyncio_tcp_readinto.py
Python
apache-2.0
1,545
# Test uasyncio TCP server and client using start_server() and open_connection() try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit PORT = 8000 async def handle_connection(reader, writer): # Test that peername exists (but don't check its value, it changes) writer.get_extra_info("peername") data = await reader.read(100) print("echo:", data) writer.write(data) await writer.drain() print("close") writer.close() await writer.wait_closed() print("done") ev.set() async def tcp_server(): global ev ev = asyncio.Event() server = await asyncio.start_server(handle_connection, "0.0.0.0", PORT) print("server running") multitest.next() async with server: await asyncio.wait_for(ev.wait(), 10) async def tcp_client(message): reader, writer = await asyncio.open_connection(IP, PORT) print("write:", message) writer.write(message) await writer.drain() data = await reader.read(100) print("read:", data) def instance0(): multitest.globals(IP=multitest.get_network_ip()) asyncio.run(tcp_server()) def instance1(): multitest.next() asyncio.run(tcp_client(b"client data"))
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/uasyncio_tcp_server_client.py
Python
apache-2.0
1,299
# Simple test of a UDP server and client transferring data import socket NUM_NEW_SOCKETS = 4 NUM_TRANSFERS = 4 PORT = 8000 # Server def instance0(): multitest.globals(IP=multitest.get_network_ip()) multitest.next() for i in range(NUM_NEW_SOCKETS): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(socket.getaddrinfo("0.0.0.0", PORT)[0][-1]) multitest.broadcast("server ready") for j in range(NUM_TRANSFERS): data, addr = s.recvfrom(1000) print(data) s.sendto(b"server to client %d %d" % (i, j), addr) s.close() # Client def instance1(): multitest.next() ai = socket.getaddrinfo(IP, PORT)[0][-1] for i in range(NUM_NEW_SOCKETS): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) multitest.wait("server ready") for j in range(NUM_TRANSFERS): s.sendto(b"client to server %d %d" % (i, j), ai) data, addr = s.recvfrom(1000) print(data) s.close()
YifuLiu/AliOS-Things
components/py_engine/tests/multi_net/udp_data.py
Python
apache-2.0
1,028
# test that socket.accept() on a non-blocking socket raises EAGAIN try: import usocket as socket except: import socket s = socket.socket() s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.setblocking(False) s.listen(1) try: s.accept() except OSError as er: print(er.errno == 11) # 11 is EAGAIN s.close()
YifuLiu/AliOS-Things
components/py_engine/tests/net_hosted/accept_nonblock.py
Python
apache-2.0
329
# test that socket.accept() on a socket with timeout raises ETIMEDOUT try: import uerrno as errno, usocket as socket except: import errno, socket try: socket.socket.settimeout except AttributeError: print("SKIP") raise SystemExit s = socket.socket() s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.settimeout(1) s.listen(1) try: s.accept() except OSError as er: print(er.errno in (errno.ETIMEDOUT, "timed out")) # CPython uses a string instead of errno s.close()
YifuLiu/AliOS-Things
components/py_engine/tests/net_hosted/accept_timeout.py
Python
apache-2.0
502
# test that socket.connect() on a non-blocking socket raises EINPROGRESS try: import usocket as socket import uerrno as errno except: import socket, errno def test(peer_addr): s = socket.socket() s.setblocking(False) try: s.connect(peer_addr) except OSError as er: print(er.errno == errno.EINPROGRESS) s.close() if __name__ == "__main__": test(socket.getaddrinfo("micropython.org", 80)[0][-1])
YifuLiu/AliOS-Things
components/py_engine/tests/net_hosted/connect_nonblock.py
Python
apache-2.0
451
# test that socket.connect() on a non-blocking socket raises EINPROGRESS # and that an immediate write/send/read/recv does the right thing try: import sys, time import uerrno as errno, usocket as socket, ussl as ssl except: import socket, errno, ssl isMP = sys.implementation.name == "micropython" def dp(e): # uncomment next line for development and testing, to print the actual exceptions # print(repr(e)) pass # do_connect establishes the socket and wraps it if tls is True. # If handshake is true, the initial connect (and TLS handshake) is # allowed to be performed before returning. def do_connect(peer_addr, tls, handshake): s = socket.socket() s.setblocking(False) try: # print("Connecting to", peer_addr) s.connect(peer_addr) except OSError as er: print("connect:", er.errno == errno.EINPROGRESS) if er.errno != errno.EINPROGRESS: print(" got", er.errno) # wrap with ssl/tls if desired if tls: try: if sys.implementation.name == "micropython": s = ssl.wrap_socket(s, do_handshake=handshake) else: s = ssl.wrap_socket(s, do_handshake_on_connect=handshake) print("wrap: True") except Exception as e: dp(e) print("wrap:", e) elif handshake: # just sleep a little bit, this allows any connect() errors to happen time.sleep(0.2) return s # test runs the test against a specific peer address. def test(peer_addr, tls=False, handshake=False): # MicroPython plain sockets have read/write, but CPython's don't # MicroPython TLS sockets and CPython's have read/write # hasRW captures this wonderful state of affairs hasRW = isMP or tls # MicroPython plain sockets and CPython's have send/recv # MicroPython TLS sockets don't have send/recv, but CPython's do # hasSR captures this wonderful state of affairs hasSR = not (isMP and tls) # connect + send if hasSR: s = do_connect(peer_addr, tls, handshake) # send -> 4 or EAGAIN try: ret = s.send(b"1234") print("send:", handshake and ret == 4) except OSError as er: # dp(er) print("send:", er.errno in (errno.EAGAIN, errno.EINPROGRESS)) s.close() else: # fake it... print("connect:", True) if tls: print("wrap:", True) print("send:", True) # connect + write if hasRW: s = do_connect(peer_addr, tls, handshake) # write -> None try: ret = s.write(b"1234") print("write:", ret in (4, None)) # SSL may accept 4 into buffer except OSError as er: dp(er) print("write:", False) # should not raise except ValueError as er: # CPython dp(er) print("write:", er.args[0] == "Write on closed or unwrapped SSL socket.") s.close() else: # fake it... print("connect:", True) if tls: print("wrap:", True) print("write:", True) if hasSR: # connect + recv s = do_connect(peer_addr, tls, handshake) # recv -> EAGAIN try: print("recv:", s.recv(10)) except OSError as er: dp(er) print("recv:", er.errno == errno.EAGAIN) s.close() else: # fake it... print("connect:", True) if tls: print("wrap:", True) print("recv:", True) # connect + read if hasRW: s = do_connect(peer_addr, tls, handshake) # read -> None try: ret = s.read(10) print("read:", ret is None) except OSError as er: dp(er) print("read:", False) # should not raise except ValueError as er: # CPython dp(er) print("read:", er.args[0] == "Read on closed or unwrapped SSL socket.") s.close() else: # fake it... print("connect:", True) if tls: print("wrap:", True) print("read:", True) if __name__ == "__main__": # these tests use a non-existent test IP address, this way the connect takes forever and # we can see EAGAIN/None (https://tools.ietf.org/html/rfc5737) print("--- Plain sockets to nowhere ---") test(socket.getaddrinfo("192.0.2.1", 80)[0][-1], False, False) print("--- SSL sockets to nowhere ---") # this test fails with AXTLS because do_handshake=False blocks on first read/write and # there it times out until the connect is aborted test(socket.getaddrinfo("192.0.2.1", 443)[0][-1], True, False) print("--- Plain sockets ---") test(socket.getaddrinfo("micropython.org", 80)[0][-1], False, True) print("--- SSL sockets ---") test(socket.getaddrinfo("micropython.org", 443)[0][-1], True, True)
YifuLiu/AliOS-Things
components/py_engine/tests/net_hosted/connect_nonblock_xfer.py
Python
apache-2.0
4,928
# test that socket.connect() has correct polling behaviour before, during and after try: import usocket as socket, uselect as select except: import socket, select def test(peer_addr): s = socket.socket() poller = select.poll() poller.register(s) # test poll before connect p = poller.poll(0) print(len(p), p[0][-1]) s.connect(peer_addr) # test poll during connection print(len(poller.poll(0))) # test poll after connection is established p = poller.poll(1000) print(len(p), p[0][-1]) s.close() if __name__ == "__main__": test(socket.getaddrinfo("micropython.org", 80)[0][-1])
YifuLiu/AliOS-Things
components/py_engine/tests/net_hosted/connect_poll.py
Python
apache-2.0
650
# test ssl.getpeercert() method try: import usocket as socket import ussl as ssl except: import socket import ssl def test(peer_addr): s = socket.socket() s.connect(peer_addr) s = ssl.wrap_socket(s) cert = s.getpeercert(True) print(type(cert), len(cert) > 100) s.close() if __name__ == "__main__": test(socket.getaddrinfo("micropython.org", 443)[0][-1])
YifuLiu/AliOS-Things
components/py_engine/tests/net_hosted/ssl_getpeercert.py
Python
apache-2.0
403
# Test basic behaviour of uasyncio.start_server() try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit async def test(): # Test creating 2 servers using the same address print("create server1") server1 = await asyncio.start_server(None, "0.0.0.0", 8000) try: print("create server2") await asyncio.start_server(None, "0.0.0.0", 8000) except OSError as er: print("OSError") # Wait for server to close. async with server1: print("sleep") await asyncio.sleep(0) print("done") asyncio.run(test())
YifuLiu/AliOS-Things
components/py_engine/tests/net_hosted/uasyncio_start_server.py
Python
apache-2.0
677
try: import usocket as socket, sys except: import socket, sys def test_non_existent(): try: res = socket.getaddrinfo("nonexistent.example.com", 80) print("getaddrinfo returned", res) except OSError as e: print("getaddrinfo raised") def test_bogus(): try: res = socket.getaddrinfo("hey.!!$$", 80) print("getaddrinfo returned", res) except OSError as e: print("getaddrinfo raised") except Exception as e: print("getaddrinfo raised") # CPython raises UnicodeError!? def test_ip_addr(): try: res = socket.getaddrinfo("10.10.10.10", 80) print("getaddrinfo returned resolutions") except Exception as e: print("getaddrinfo raised", e) def test_0_0_0_0(): try: res = socket.getaddrinfo("0.0.0.0", 80) print("getaddrinfo returned resolutions") except Exception as e: print("getaddrinfo raised", e) def test_valid(): try: res = socket.getaddrinfo("micropython.org", 80) print("getaddrinfo returned resolutions") except Exception as e: print("getaddrinfo raised", e) test_funs = [n for n in dir() if n.startswith("test_")] for f in sorted(test_funs): print("--", f, end=": ") eval(f + "()")
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/getaddrinfo.py
Python
apache-2.0
1,281
# test that socket.connect() on a non-blocking socket raises EINPROGRESS # and that an immediate write/send/read/recv does the right thing import sys try: import uerrno as errno, usocket as socket, ussl as ssl except: import errno, socket, ssl def test(addr, hostname, block=True): print("---", hostname or addr) s = socket.socket() s.setblocking(block) try: s.connect(addr) print("connected") except OSError as e: if e.errno != errno.EINPROGRESS: raise print("EINPROGRESS") try: if sys.implementation.name == "micropython": s = ssl.wrap_socket(s, do_handshake=block) else: s = ssl.wrap_socket(s, do_handshake_on_connect=block) print("wrap: True") except OSError: print("wrap: error") if not block: try: while s.write(b"0") is None: pass except (ValueError, OSError): # CPython raises ValueError, MicroPython raises OSError print("write: error") s.close() if __name__ == "__main__": # connect to plain HTTP port, oops! addr = socket.getaddrinfo("micropython.org", 80)[0][-1] test(addr, None) # connect to plain HTTP port, oops! addr = socket.getaddrinfo("micropython.org", 80)[0][-1] test(addr, None, False) # connect to server with self-signed cert, oops! addr = socket.getaddrinfo("test.mosquitto.org", 8883)[0][-1] test(addr, "test.mosquitto.org")
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/ssl_errors.py
Python
apache-2.0
1,496
try: import usocket as socket, ussl as ssl, uerrno as errno, sys except: import socket, ssl, errno, sys, time, select def test_one(site, opts): ai = socket.getaddrinfo(site, 443) addr = ai[0][-1] print(addr) # Connect the raw socket s = socket.socket() s.setblocking(False) try: s.connect(addr) raise OSError(-1, "connect blocks") except OSError as e: if e.errno != errno.EINPROGRESS: raise if sys.implementation.name != "micropython": # in CPython we have to wait, otherwise wrap_socket is not happy select.select([], [s], []) try: # Wrap with SSL try: if sys.implementation.name == "micropython": s = ssl.wrap_socket(s, do_handshake=False) else: s = ssl.wrap_socket(s, do_handshake_on_connect=False) except OSError as e: if e.errno != errno.EINPROGRESS: raise print("wrapped") # CPython needs to be told to do the handshake if sys.implementation.name != "micropython": while True: try: s.do_handshake() break except ssl.SSLError as err: if err.args[0] == ssl.SSL_ERROR_WANT_READ: select.select([s], [], []) elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE: select.select([], [s], []) else: raise time.sleep(0.1) # print("shook hands") # Write HTTP request out = b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, "latin") while len(out) > 0: n = s.write(out) if n is None: continue if n > 0: out = out[n:] elif n == 0: raise OSError(-1, "unexpected EOF in write") print("wrote") # Read response resp = b"" while True: try: b = s.read(128) except OSError as err: if err.errno == 2: # 2=ssl.SSL_ERROR_WANT_READ: continue raise if b is None: continue if len(b) > 0: if len(resp) < 1024: resp += b elif len(b) == 0: break print("read") if resp[:7] != b"HTTP/1.": raise ValueError("response doesn't start with HTTP/1.") # print(resp) finally: s.close() SITES = [ "google.com", {"host": "www.google.com"}, "micropython.org", "pypi.org", "api.telegram.org", {"host": "api.pushbullet.com", "sni": True}, ] def main(): for site in SITES: opts = {} if isinstance(site, dict): opts = site site = opts["host"] try: test_one(site, opts) print(site, "ok") except Exception as e: print(site, "error") print("DONE") main()
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/test_tls_nonblock.py
Python
apache-2.0
3,119
try: import usocket as _socket except: import _socket try: import ussl as ssl except: import ssl # CPython only supports server_hostname with SSLContext ssl = ssl.SSLContext() def test_one(site, opts): ai = _socket.getaddrinfo(site, 443) addr = ai[0][-1] s = _socket.socket() try: s.connect(addr) if "sni" in opts: s = ssl.wrap_socket(s, server_hostname=opts["host"]) else: s = ssl.wrap_socket(s) s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, "latin")) resp = s.read(4096) if resp[:7] != b"HTTP/1.": raise ValueError("response doesn't start with HTTP/1.") # print(resp) finally: s.close() SITES = [ "google.com", "www.google.com", "micropython.org", "pypi.org", "api.telegram.org", {"host": "api.pushbullet.com", "sni": True}, ] def main(): for site in SITES: opts = {} if isinstance(site, dict): opts = site site = opts["host"] try: test_one(site, opts) print(site, "ok") except Exception as e: print(site, e) main()
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/test_tls_sites.py
Python
apache-2.0
1,211
# test that modtls produces a numerical error message when out of heap try: import usocket as socket, ussl as ssl, sys except: import socket, ssl, sys try: from micropython import alloc_emergency_exception_buf, heap_lock, heap_unlock except: print("SKIP") raise SystemExit # test with heap locked to see it switch to number-only error message def test(addr): alloc_emergency_exception_buf(256) s = socket.socket() s.connect(addr) try: s.setblocking(False) s = ssl.wrap_socket(s, do_handshake=False) heap_lock() print("heap is locked") while True: ret = s.write("foo") if ret: break heap_unlock() print("wrap: no exception") except OSError as e: heap_unlock() # mbedtls produces "-29184" # axtls produces "RECORD_OVERFLOW" ok = "-29184" in str(e) or "RECORD_OVERFLOW" in str(e) print("wrap:", ok) if not ok: print("got exception:", e) s.close() if __name__ == "__main__": # connect to plain HTTP port, oops! addr = socket.getaddrinfo("micropython.org", 80)[0][-1] test(addr)
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/tls_num_errors.py
Python
apache-2.0
1,191
# test that modtls produces a text error message try: import usocket as socket, ussl as ssl, sys except: import socket, ssl, sys def test(addr): s = socket.socket() s.connect(addr) try: s = ssl.wrap_socket(s) print("wrap: no exception") except OSError as e: # mbedtls produces "mbedtls -0x7200: SSL - An invalid SSL record was received" # axtls produces "RECORD_OVERFLOW" but also prints "TLS buffer overflow,..." # CPython produces "[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1108)" ok = ( "SSL_INVALID_RECORD" in str(e) or "RECORD_OVERFLOW" in str(e) or "wrong version" in str(e) ) print("wrap:", ok) if not ok: print("got exception:", e) s.close() if __name__ == "__main__": # connect to plain HTTP port, oops! addr = socket.getaddrinfo("micropython.org", 80)[0][-1] test(addr)
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/tls_text_errors.py
Python
apache-2.0
960
# Test cancelling a task waiting on stream IO try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit async def get(reader): print("start") try: await reader.read(10) print("fail") except asyncio.CancelledError: print("cancelled") async def main(url): reader, writer = await asyncio.open_connection(url, 80) task = asyncio.create_task(get(reader)) await asyncio.sleep(0) print("cancelling") task.cancel() print("waiting") await task print("done") writer.close() await writer.wait_closed() asyncio.run(main("micropython.org"))
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/uasyncio_cancel_stream.py
Python
apache-2.0
712
# Test simple HTTP request with uasyncio.open_connection() try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit async def http_get(url): reader, writer = await asyncio.open_connection(url, 80) print("write GET") writer.write(b"GET / HTTP/1.0\r\n\r\n") await writer.drain() print("read response") data = await reader.read(100) print("read:", data.split(b"\r\n")[0]) print("close") writer.close() await writer.wait_closed() print("done") asyncio.run(http_get("micropython.org"))
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/uasyncio_open_connection.py
Python
apache-2.0
635
# Test uasyncio.open_connection() and stream readline() try: import uasyncio as asyncio except ImportError: try: import asyncio except ImportError: print("SKIP") raise SystemExit async def http_get_headers(url): reader, writer = await asyncio.open_connection(url, 80) print("write GET") writer.write(b"GET / HTTP/1.0\r\n\r\n") await writer.drain() while True: line = await reader.readline() line = line.strip() if not line: break if ( line.find(b"Date") == -1 and line.find(b"Modified") == -1 and line.find(b"Server") == -1 ): print(line) print("close") writer.close() await writer.wait_closed() print("done") asyncio.run(http_get_headers("micropython.org"))
YifuLiu/AliOS-Things
components/py_engine/tests/net_inet/uasyncio_tcp_read_headers.py
Python
apache-2.0
839
def bm_run(N, M): try: from utime import ticks_us, ticks_diff except ImportError: import time ticks_us = lambda: int(time.perf_counter() * 1000000) ticks_diff = lambda a, b: a - b # Pick sensible parameters given N, M cur_nm = (0, 0) param = None for nm, p in bm_params.items(): if 10 * nm[0] <= 12 * N and nm[1] <= M and nm > cur_nm: cur_nm = nm param = p if param is None: print(-1, -1, "no matching params") return # Run and time benchmark run, result = bm_setup(param) t0 = ticks_us() run() t1 = ticks_us() norm, out = result() print(ticks_diff(t1, t0), norm, out)
YifuLiu/AliOS-Things
components/py_engine/tests/perf_bench/benchrun.py
Python
apache-2.0
708
# Source: https://github.com/python/pyperformance # License: MIT # create chaosgame-like fractals # Copyright (C) 2005 Carl Friedrich Bolz import math import random class GVector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def Mag(self): return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) def dist(self, other): return math.sqrt( (self.x - other.x) ** 2 + (self.y - other.y) ** 2 + (self.z - other.z) ** 2 ) def __add__(self, other): if not isinstance(other, GVector): raise ValueError("Can't add GVector to " + str(type(other))) v = GVector(self.x + other.x, self.y + other.y, self.z + other.z) return v def __sub__(self, other): return self + other * -1 def __mul__(self, other): v = GVector(self.x * other, self.y * other, self.z * other) return v __rmul__ = __mul__ def linear_combination(self, other, l1, l2=None): if l2 is None: l2 = 1 - l1 v = GVector( self.x * l1 + other.x * l2, self.y * l1 + other.y * l2, self.z * l1 + other.z * l2 ) return v def __str__(self): return "<%f, %f, %f>" % (self.x, self.y, self.z) def __repr__(self): return "GVector(%f, %f, %f)" % (self.x, self.y, self.z) class Spline(object): """Class for representing B-Splines and NURBS of arbitrary degree""" def __init__(self, points, degree, knots): """Creates a Spline. points is a list of GVector, degree is the degree of the Spline. """ if len(points) > len(knots) - degree + 1: raise ValueError("too many control points") elif len(points) < len(knots) - degree + 1: raise ValueError("not enough control points") last = knots[0] for cur in knots[1:]: if cur < last: raise ValueError("knots not strictly increasing") last = cur self.knots = knots self.points = points self.degree = degree def GetDomain(self): """Returns the domain of the B-Spline""" return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree]) def __call__(self, u): """Calculates a point of the B-Spline using de Boors Algorithm""" dom = self.GetDomain() if u < dom[0] or u > dom[1]: raise ValueError("Function value not in domain") if u == dom[0]: return self.points[0] if u == dom[1]: return self.points[-1] I = self.GetIndex(u) d = [self.points[I - self.degree + 1 + ii] for ii in range(self.degree + 1)] U = self.knots for ik in range(1, self.degree + 1): for ii in range(I - self.degree + ik + 1, I + 2): ua = U[ii + self.degree - ik] ub = U[ii - 1] co1 = (ua - u) / (ua - ub) co2 = (u - ub) / (ua - ub) index = ii - I + self.degree - ik - 1 d[index] = d[index].linear_combination(d[index + 1], co1, co2) return d[0] def GetIndex(self, u): dom = self.GetDomain() for ii in range(self.degree - 1, len(self.knots) - self.degree): if u >= self.knots[ii] and u < self.knots[ii + 1]: I = ii break else: I = dom[1] - 1 return I def __len__(self): return len(self.points) def __repr__(self): return "Spline(%r, %r, %r)" % (self.points, self.degree, self.knots) def write_ppm(im, w, h, filename): with open(filename, "wb") as f: f.write(b"P6\n%i %i\n255\n" % (w, h)) for j in range(h): for i in range(w): val = im[j * w + i] c = val * 255 f.write(b"%c%c%c" % (c, c, c)) class Chaosgame(object): def __init__(self, splines, thickness, subdivs): self.splines = splines self.thickness = thickness self.minx = min([p.x for spl in splines for p in spl.points]) self.miny = min([p.y for spl in splines for p in spl.points]) self.maxx = max([p.x for spl in splines for p in spl.points]) self.maxy = max([p.y for spl in splines for p in spl.points]) self.height = self.maxy - self.miny self.width = self.maxx - self.minx self.num_trafos = [] maxlength = thickness * self.width / self.height for spl in splines: length = 0 curr = spl(0) for i in range(1, subdivs + 1): last = curr t = 1 / subdivs * i curr = spl(t) length += curr.dist(last) self.num_trafos.append(max(1, int(length / maxlength * 1.5))) self.num_total = sum(self.num_trafos) def get_random_trafo(self): r = random.randrange(int(self.num_total) + 1) l = 0 for i in range(len(self.num_trafos)): if r >= l and r < l + self.num_trafos[i]: return i, random.randrange(self.num_trafos[i]) l += self.num_trafos[i] return len(self.num_trafos) - 1, random.randrange(self.num_trafos[-1]) def transform_point(self, point, trafo=None): x = (point.x - self.minx) / self.width y = (point.y - self.miny) / self.height if trafo is None: trafo = self.get_random_trafo() start, end = self.splines[trafo[0]].GetDomain() length = end - start seg_length = length / self.num_trafos[trafo[0]] t = start + seg_length * trafo[1] + seg_length * x basepoint = self.splines[trafo[0]](t) if t + 1 / 50000 > end: neighbour = self.splines[trafo[0]](t - 1 / 50000) derivative = neighbour - basepoint else: neighbour = self.splines[trafo[0]](t + 1 / 50000) derivative = basepoint - neighbour if derivative.Mag() != 0: basepoint.x += derivative.y / derivative.Mag() * (y - 0.5) * self.thickness basepoint.y += -derivative.x / derivative.Mag() * (y - 0.5) * self.thickness else: # can happen, especially with single precision float pass self.truncate(basepoint) return basepoint def truncate(self, point): if point.x >= self.maxx: point.x = self.maxx if point.y >= self.maxy: point.y = self.maxy if point.x < self.minx: point.x = self.minx if point.y < self.miny: point.y = self.miny def create_image_chaos(self, w, h, iterations, rng_seed): # Always use the same sequence of random numbers # to get reproductible benchmark random.seed(rng_seed) im = bytearray(w * h) point = GVector((self.maxx + self.minx) / 2, (self.maxy + self.miny) / 2, 0) for _ in range(iterations): point = self.transform_point(point) x = (point.x - self.minx) / self.width * w y = (point.y - self.miny) / self.height * h x = int(x) y = int(y) if x == w: x -= 1 if y == h: y -= 1 im[(h - y - 1) * w + x] = 1 return im ########################################################################### # Benchmark interface bm_params = { (100, 50): (0.25, 100, 50, 50, 50, 1234), (1000, 1000): (0.25, 200, 400, 400, 1000, 1234), (5000, 1000): (0.25, 400, 500, 500, 7000, 1234), } def bm_setup(params): splines = [ Spline( [ GVector(1.597, 3.304, 0.0), GVector(1.576, 4.123, 0.0), GVector(1.313, 5.288, 0.0), GVector(1.619, 5.330, 0.0), GVector(2.890, 5.503, 0.0), GVector(2.373, 4.382, 0.0), GVector(1.662, 4.360, 0.0), ], 3, [0, 0, 0, 1, 1, 1, 2, 2, 2], ), Spline( [ GVector(2.805, 4.017, 0.0), GVector(2.551, 3.525, 0.0), GVector(1.979, 2.620, 0.0), GVector(1.979, 2.620, 0.0), ], 3, [0, 0, 0, 1, 1, 1], ), Spline( [ GVector(2.002, 4.011, 0.0), GVector(2.335, 3.313, 0.0), GVector(2.367, 3.233, 0.0), GVector(2.367, 3.233, 0.0), ], 3, [0, 0, 0, 1, 1, 1], ), ] chaos = Chaosgame(splines, params[0], params[1]) image = None def run(): nonlocal image _, _, width, height, iter, rng_seed = params image = chaos.create_image_chaos(width, height, iter, rng_seed) def result(): norm = params[4] # Images are not the same when floating point behaviour is different, # so return percentage of pixels that are set (rounded to int). # write_ppm(image, params[2], params[3], 'out-.ppm') pix = int(100 * sum(image) / len(image)) return norm, pix return run, result
YifuLiu/AliOS-Things
components/py_engine/tests/perf_bench/bm_chaos.py
Python
apache-2.0
9,247
# Source: https://github.com/python/pyperformance # License: MIT # The Computer Language Benchmarks Game # http://benchmarksgame.alioth.debian.org/ # Contributed by Sokolov Yura, modified by Tupteq. def fannkuch(n): count = list(range(1, n + 1)) max_flips = 0 m = n - 1 r = n check = 0 perm1 = list(range(n)) perm = list(range(n)) perm1_ins = perm1.insert perm1_pop = perm1.pop while 1: if check < 30: check += 1 while r != 1: count[r - 1] = r r -= 1 if perm1[0] != 0 and perm1[m] != m: perm = perm1[:] flips_count = 0 k = perm[0] while k: perm[: k + 1] = perm[k::-1] flips_count += 1 k = perm[0] if flips_count > max_flips: max_flips = flips_count while r != n: perm1_ins(r, perm1_pop(0)) count[r] -= 1 if count[r] > 0: break r += 1 else: return max_flips ########################################################################### # Benchmark interface bm_params = { (50, 10): (5,), (100, 10): (6,), (500, 10): (7,), (1000, 10): (8,), (5000, 10): (9,), } def bm_setup(params): state = None def run(): nonlocal state state = fannkuch(params[0]) def result(): return params[0], state return run, result
YifuLiu/AliOS-Things
components/py_engine/tests/perf_bench/bm_fannkuch.py
Python
apache-2.0
1,495