Skip to content

Commit 0fb2f22

Browse files
committed
Docs and code: Remove all references to uasyncio.
1 parent 6549e81 commit 0fb2f22

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+1566
-1155
lines changed

v3/as_demos/aledflash.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,35 @@
55
# Run on MicroPython board bare hardware
66

77
import pyb
8-
import uasyncio as asyncio
8+
import asyncio
9+
910

1011
async def toggle(objLED, time_ms):
1112
while True:
1213
await asyncio.sleep_ms(time_ms)
1314
objLED.toggle()
1415

16+
1517
# TEST FUNCTION
1618

19+
1720
async def main(duration):
1821
print("Flash LED's for {} seconds".format(duration))
19-
leds = [pyb.LED(x) for x in range(1,4)] # Initialise three on board LED's
22+
leds = [pyb.LED(x) for x in range(1, 4)] # Initialise three on board LED's
2023
for x, led in enumerate(leds): # Create a task for each LED
21-
t = int((0.2 + x/2) * 1000)
24+
t = int((0.2 + x / 2) * 1000)
2225
asyncio.create_task(toggle(leds[x], t))
2326
await asyncio.sleep(duration)
2427

28+
2529
def test(duration=10):
2630
try:
2731
asyncio.run(main(duration))
2832
except KeyboardInterrupt:
29-
print('Interrupted')
33+
print("Interrupted")
3034
finally:
3135
asyncio.new_event_loop()
32-
print('as_demos.aledflash.test() to run again.')
36+
print("as_demos.aledflash.test() to run again.")
37+
3338

3439
test()

v3/as_demos/apoll.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,24 @@
55
# Author: Peter Hinch
66
# Copyright Peter Hinch 2017 Released under the MIT license
77

8-
import uasyncio as asyncio
8+
import asyncio
99
import pyb
1010
import utime as time
1111

12+
1213
class Accelerometer(object):
1314
threshold_squared = 16
15+
1416
def __init__(self, accelhw, timeout):
1517
self.accelhw = accelhw
1618
self.timeout = timeout
1719
self.last_change = time.ticks_ms()
1820
self.coords = [accelhw.x(), accelhw.y(), accelhw.z()]
1921

20-
def dsquared(self, xyz): # Return the square of the distance between this and a passed
21-
return sum(map(lambda p, q : (p-q)**2, self.coords, xyz)) # acceleration vector
22+
def dsquared(self, xyz): # Return the square of the distance between this and a passed
23+
return sum(map(lambda p, q: (p - q) ** 2, self.coords, xyz)) # acceleration vector
2224

23-
def poll(self): # Device is noisy. Only update if change exceeds a threshold
25+
def poll(self): # Device is noisy. Only update if change exceeds a threshold
2426
xyz = [self.accelhw.x(), self.accelhw.y(), self.accelhw.z()]
2527
if self.dsquared(xyz) > Accelerometer.threshold_squared:
2628
self.coords = xyz
@@ -31,31 +33,33 @@ def poll(self): # Device is noisy. Only update if change exc
3133
def vector(self):
3234
return self.coords
3335

34-
def timed_out(self): # Time since last change or last timeout report
36+
def timed_out(self): # Time since last change or last timeout report
3537
if time.ticks_diff(time.ticks_ms(), self.last_change) > self.timeout:
3638
self.last_change = time.ticks_ms()
3739
return True
3840
return False
3941

42+
4043
async def accel_coro(timeout=2000):
41-
accelhw = pyb.Accel() # Instantiate accelerometer hardware
42-
await asyncio.sleep_ms(30) # Allow it to settle
44+
accelhw = pyb.Accel() # Instantiate accelerometer hardware
45+
await asyncio.sleep_ms(30) # Allow it to settle
4346
accel = Accelerometer(accelhw, timeout)
4447
while True:
4548
result = accel.poll()
46-
if result == 0: # Value has changed
49+
if result == 0: # Value has changed
4750
x, y, z = accel.vector()
4851
print("Value x:{:3d} y:{:3d} z:{:3d}".format(x, y, z))
49-
elif accel.timed_out(): # Report every 2 secs
52+
elif accel.timed_out(): # Report every 2 secs
5053
print("Timeout waiting for accelerometer change")
51-
await asyncio.sleep_ms(100) # Poll every 100ms
54+
await asyncio.sleep_ms(100) # Poll every 100ms
5255

5356

5457
async def main(delay):
55-
print('Testing accelerometer for {} secs. Move the Pyboard!'.format(delay))
56-
print('Test runs for {}s.'.format(delay))
58+
print("Testing accelerometer for {} secs. Move the Pyboard!".format(delay))
59+
print("Test runs for {}s.".format(delay))
5760
asyncio.create_task(accel_coro())
5861
await asyncio.sleep(delay)
59-
print('Test complete!')
62+
print("Test complete!")
63+
6064

6165
asyncio.run(main(20))

v3/as_demos/auart.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# Link X1 and X2 to test.
55

66
# We run with no UART timeout: UART read never blocks.
7-
import uasyncio as asyncio
7+
import asyncio
88
from machine import UART
99

1010
uart = UART(4, 9600, timeout=0)

v3/as_demos/auart_hd.py

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,35 +13,36 @@
1313
# To test link X1-X4 and X2-X3
1414

1515
from pyb import UART
16-
import uasyncio as asyncio
16+
import asyncio
1717
from primitives.delay_ms import Delay_ms
1818

1919
# Dummy device waits for any incoming line and responds with 4 lines at 1 second
2020
# intervals.
21-
class Device():
22-
def __init__(self, uart_no = 4):
21+
class Device:
22+
def __init__(self, uart_no=4):
2323
self.uart = UART(uart_no, 9600)
2424
self.swriter = asyncio.StreamWriter(self.uart, {})
2525
self.sreader = asyncio.StreamReader(self.uart)
2626
asyncio.create_task(self._run())
2727

2828
async def _run(self):
29-
responses = ['Line 1', 'Line 2', 'Line 3', 'Goodbye']
29+
responses = ["Line 1", "Line 2", "Line 3", "Goodbye"]
3030
while True:
3131
res = await self.sreader.readline()
3232
for response in responses:
3333
await self.swriter.awrite("{}\r\n".format(response))
3434
# Demo the fact that the master tolerates slow response.
3535
await asyncio.sleep_ms(300)
3636

37+
3738
# The master's send_command() method sends a command and waits for a number of
3839
# lines from the device. The end of the process is signified by a timeout, when
3940
# a list of lines is returned. This allows line-by-line processing.
4041
# A special test mode demonstrates the behaviour with a non-responding device. If
4142
# None is passed, no commend is sent. The master waits for a response which never
4243
# arrives and returns an empty list.
43-
class Master():
44-
def __init__(self, uart_no = 2, timeout=4000):
44+
class Master:
45+
def __init__(self, uart_no=2, timeout=4000):
4546
self.uart = UART(uart_no, 9600)
4647
self.timeout = timeout
4748
self.swriter = asyncio.StreamWriter(self.uart, {})
@@ -59,32 +60,34 @@ async def _recv(self):
5960
async def send_command(self, command):
6061
self.response = [] # Discard any pending messages
6162
if command is None:
62-
print('Timeout test.')
63+
print("Timeout test.")
6364
else:
6465
await self.swriter.awrite("{}\r\n".format(command))
65-
print('Command sent:', command)
66+
print("Command sent:", command)
6667
self.delay.trigger(self.timeout) # Re-initialise timer
6768
while self.delay.running():
6869
await asyncio.sleep(1) # Wait for 4s after last msg received
6970
return self.response
7071

72+
7173
async def main():
72-
print('This test takes 10s to complete.')
74+
print("This test takes 10s to complete.")
7375
master = Master()
7476
device = Device()
75-
for cmd in ['Run', None]:
77+
for cmd in ["Run", None]:
7678
print()
7779
res = await master.send_command(cmd)
7880
# can use b''.join(res) if a single string is required.
7981
if res:
80-
print('Result is:')
82+
print("Result is:")
8183
for line in res:
82-
print(line.decode('UTF8'), end='')
84+
print(line.decode("UTF8"), end="")
8385
else:
84-
print('Timed out waiting for result.')
86+
print("Timed out waiting for result.")
87+
8588

8689
def printexp():
87-
st = '''Expected output:
90+
st = """Expected output:
8891
This test takes 10s to complete.
8992
9093
Command sent: Run
@@ -96,19 +99,21 @@ def printexp():
9699
97100
Timeout test.
98101
Timed out waiting for result.
99-
'''
100-
print('\x1b[32m')
102+
"""
103+
print("\x1b[32m")
101104
print(st)
102-
print('\x1b[39m')
105+
print("\x1b[39m")
106+
103107

104108
def test():
105109
printexp()
106110
try:
107111
asyncio.run(main())
108112
except KeyboardInterrupt:
109-
print('Interrupted')
113+
print("Interrupted")
110114
finally:
111115
asyncio.new_event_loop()
112-
print('as_demos.auart_hd.test() to run again.')
116+
print("as_demos.auart_hd.test() to run again.")
117+
113118

114119
test()

v3/as_demos/gather.py

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,42 +3,47 @@
33
# 2. A coro with a timeout
44
# 3. A cancellable coro
55

6-
import uasyncio as asyncio
6+
import asyncio
7+
78

89
async def barking(n):
9-
print('Start normal coro barking()')
10+
print("Start normal coro barking()")
1011
for _ in range(6):
1112
await asyncio.sleep(1)
12-
print('Done barking.')
13+
print("Done barking.")
1314
return 2 * n
1415

16+
1517
async def foo(n):
16-
print('Start timeout coro foo()')
18+
print("Start timeout coro foo()")
1719
try:
1820
while True:
1921
await asyncio.sleep(1)
2022
n += 1
2123
except asyncio.CancelledError:
22-
print('Trapped foo timeout.')
24+
print("Trapped foo timeout.")
2325
raise
2426
return n
2527

28+
2629
async def bar(n):
27-
print('Start cancellable bar()')
30+
print("Start cancellable bar()")
2831
try:
2932
while True:
3033
await asyncio.sleep(1)
3134
n += 1
3235
except asyncio.CancelledError: # Demo of trapping
33-
print('Trapped bar cancellation.')
36+
print("Trapped bar cancellation.")
3437
raise
3538
return n
3639

40+
3741
async def do_cancel(task):
3842
await asyncio.sleep(5)
39-
print('About to cancel bar')
43+
print("About to cancel bar")
4044
task.cancel()
4145

46+
4247
async def main(rex):
4348
bar_task = asyncio.create_task(bar(70)) # Note args here
4449
tasks = []
@@ -48,12 +53,12 @@ async def main(rex):
4853
try:
4954
res = await asyncio.gather(*tasks, return_exceptions=rex)
5055
except asyncio.TimeoutError:
51-
print('foo timed out.')
52-
res = 'No result'
53-
print('Result: ', res)
56+
print("foo timed out.")
57+
res = "No result"
58+
print("Result: ", res)
5459

5560

56-
exp_false = '''Test runs for 10s. Expected output:
61+
exp_false = """Test runs for 10s. Expected output:
5762
5863
Start cancellable bar()
5964
Start normal coro barking()
@@ -65,8 +70,8 @@ async def main(rex):
6570
foo timed out.
6671
Result: No result
6772
68-
'''
69-
exp_true = '''Test runs for 10s. Expected output:
73+
"""
74+
exp_true = """Test runs for 10s. Expected output:
7075
7176
Start cancellable bar()
7277
Start normal coro barking()
@@ -77,24 +82,27 @@ async def main(rex):
7782
Trapped foo timeout.
7883
Result: [42, TimeoutError()]
7984
80-
'''
85+
"""
86+
8187

8288
def printexp(st):
83-
print('\x1b[32m')
89+
print("\x1b[32m")
8490
print(st)
85-
print('\x1b[39m')
91+
print("\x1b[39m")
92+
8693

8794
def test(rex):
8895
st = exp_true if rex else exp_false
8996
printexp(st)
9097
try:
9198
asyncio.run(main(rex))
9299
except KeyboardInterrupt:
93-
print('Interrupted')
100+
print("Interrupted")
94101
finally:
95102
asyncio.new_event_loop()
96103
print()
97-
print('as_demos.gather.test() to run again.')
98-
print('as_demos.gather.test(True) to see effect of return_exceptions.')
104+
print("as_demos.gather.test() to run again.")
105+
print("as_demos.gather.test(True) to see effect of return_exceptions.")
106+
99107

100108
test(rex=False)

0 commit comments

Comments
 (0)