Skip to content

ucloud: Allow Task to schedule sync or async code. #78

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions src/arduino_iot_cloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

import asyncio
import binascii
from .ucloud import ArduinoCloudClient # noqa
from .ucloud import ArduinoCloudObject
from .ucloud import timestamp

try:
import asyncio
import binascii
except ImportError:
import uasyncio as asyncio
import ubinascii as binascii


CADATA = binascii.unhexlify(
b"308201cf30820174a00302010202141f101deba7e125e727c1a391e3ec0d"
Expand All @@ -35,6 +30,16 @@
b"8d6444ffe82217304ff2b89aafca8ecf"
)

async def coro(): # noqa
pass


def is_async(obj):
if hasattr(asyncio, "iscoroutinefunction"):
return asyncio.iscoroutinefunction(obj)
else:
return isinstance(obj, type(coro))


class Task(ArduinoCloudObject):
def __init__(self, name, **kwargs):
Expand All @@ -45,9 +50,12 @@ def __init__(self, name, **kwargs):
super().__init__(name, **kwargs)

async def run(self, aiot):
while True:
self.on_run(aiot)
await asyncio.sleep(self.interval)
if is_async(self.on_run):
await self.on_run(aiot)
else:
while True:
self.on_run(aiot)
await asyncio.sleep(self.interval)


class Location(ArduinoCloudObject):
Expand Down
Loading