Skip to content

Commit a8dd722

Browse files
authored
Merge pull request #78 from arduino/user_task_fix
ucloud: Allow Task to schedule sync or async code.
2 parents 348c337 + 01b5f71 commit a8dd722

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/arduino_iot_cloud/__init__.py

+18-10
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,12 @@
44
# License, v. 2.0. If a copy of the MPL was not distributed with this
55
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
66

7+
import asyncio
8+
import binascii
79
from .ucloud import ArduinoCloudClient # noqa
810
from .ucloud import ArduinoCloudObject
911
from .ucloud import timestamp
1012

11-
try:
12-
import asyncio
13-
import binascii
14-
except ImportError:
15-
import uasyncio as asyncio
16-
import ubinascii as binascii
17-
1813

1914
CADATA = binascii.unhexlify(
2015
b"308201cf30820174a00302010202141f101deba7e125e727c1a391e3ec0d"
@@ -35,6 +30,16 @@
3530
b"8d6444ffe82217304ff2b89aafca8ecf"
3631
)
3732

33+
async def coro(): # noqa
34+
pass
35+
36+
37+
def is_async(obj):
38+
if hasattr(asyncio, "iscoroutinefunction"):
39+
return asyncio.iscoroutinefunction(obj)
40+
else:
41+
return isinstance(obj, type(coro))
42+
3843

3944
class Task(ArduinoCloudObject):
4045
def __init__(self, name, **kwargs):
@@ -45,9 +50,12 @@ def __init__(self, name, **kwargs):
4550
super().__init__(name, **kwargs)
4651

4752
async def run(self, aiot):
48-
while True:
49-
self.on_run(aiot)
50-
await asyncio.sleep(self.interval)
53+
if is_async(self.on_run):
54+
await self.on_run(aiot)
55+
else:
56+
while True:
57+
self.on_run(aiot)
58+
await asyncio.sleep(self.interval)
5159

5260

5361
class Location(ArduinoCloudObject):

0 commit comments

Comments
 (0)