Skip to content

Commit de53378

Browse files
committed
ucloud: Add support for a sync mode.
Signed-off-by: iabdalkader <[email protected]>
1 parent 30f8598 commit de53378

File tree

4 files changed

+171
-125
lines changed

4 files changed

+171
-125
lines changed

examples/example.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ def user_task(client):
4444
# Parse command line args.
4545
parser = argparse.ArgumentParser(description="arduino_iot_cloud.py")
4646
parser.add_argument("-d", "--debug", action="store_true", help="Enable debugging messages")
47+
parser.add_argument("-s", "--sync", action="store_true", help="Run in synchronous mode")
4748
args = parser.parse_args()
4849

4950
# Assume the host has an active Internet connection.
@@ -60,7 +61,7 @@ def user_task(client):
6061
# Create a client object to connect to the Arduino IoT cloud.
6162
# The most basic authentication method uses a username and password. The username is the device
6263
# ID, and the password is the secret key obtained from the IoT cloud when provisioning a device.
63-
client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=SECRET_KEY)
64+
client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=SECRET_KEY, sync_mode=args.sync)
6465

6566
# Alternatively, the client also supports key and certificate-based authentication. To use this
6667
# mode, set "keyfile" and "certfile", and the CA certificate (if any) in "ssl_params".
@@ -73,6 +74,7 @@ def user_task(client):
7374
# "keyfile": KEY_PATH, "certfile": CERT_PATH, "cafile": CA_PATH,
7475
# "verify_mode": ssl.CERT_REQUIRED, "server_hostname" : "iot.arduino.cc"
7576
# },
77+
# sync_mode=args.sync,
7678
# )
7779

7880
# Register cloud objects.
@@ -107,5 +109,11 @@ def user_task(client):
107109
# to client.register().
108110
client.register(Task("user_task", on_run=user_task, interval=1.0))
109111

110-
# Start the Arduino IoT cloud client.
112+
# Start the Arduino IoT cloud client. In synchronous mode, this function returns immediately
113+
# after connecting to the cloud.
111114
client.start()
115+
116+
# In sync mode, start returns after connecting, and the client must be polled periodically.
117+
while True:
118+
client.update()
119+
time.sleep(0.100)

examples/micropython_basic.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def wifi_connect():
6666
logging.basicConfig(
6767
datefmt="%H:%M:%S",
6868
format="%(asctime)s.%(msecs)03d %(message)s",
69-
level=logging.INFO,
69+
level=logging.DEBUG,
7070
)
7171

7272
# NOTE: Add networking code here or in boot.py
@@ -75,7 +75,7 @@ def wifi_connect():
7575
# Create a client object to connect to the Arduino IoT cloud.
7676
# The most basic authentication method uses a username and password. The username is the device
7777
# ID, and the password is the secret key obtained from the IoT cloud when provisioning a device.
78-
client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=SECRET_KEY)
78+
client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=SECRET_KEY, sync_mode=False)
7979

8080
# Alternatively, the client also supports key and certificate-based authentication. To use this
8181
# mode, set "keyfile" and "certfile", and the CA certificate (if any) in "ssl_params".
@@ -86,6 +86,7 @@ def wifi_connect():
8686
# "keyfile": KEY_PATH, "certfile": CERT_PATH, "cadata": CADATA,
8787
# "verify_mode": ssl.CERT_REQUIRED, "server_hostname" : "iot.arduino.cc"
8888
# },
89+
# sync_mode=False,
8990
# )
9091

9192
# Register cloud objects.
@@ -133,5 +134,11 @@ def wifi_connect():
133134
except (ImportError, AttributeError):
134135
pass
135136

136-
# Start the Arduino IoT cloud client.
137+
# Start the Arduino IoT cloud client. In synchronous mode, this function returns immediately
138+
# after connecting to the cloud.
137139
client.start()
140+
141+
# In sync mode, start returns after connecting, and the client must be polled periodically.
142+
while True:
143+
client.update()
144+
time.sleep(0.100)

src/arduino_iot_cloud/__init__.py

+11-40
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
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
87
import binascii
98
from .ucloud import ArduinoCloudClient # noqa
109
from .ucloud import ArduinoCloudObject
10+
from .ucloud import ArduinoCloudObject as Task # noqa
1111
from .ucloud import timestamp
1212

1313

@@ -30,33 +30,6 @@
3030
b"8d6444ffe82217304ff2b89aafca8ecf"
3131
)
3232

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-
43-
44-
class Task(ArduinoCloudObject):
45-
def __init__(self, name, **kwargs):
46-
kwargs.update({("runnable", True)}) # Force task creation.
47-
self.on_run = kwargs.pop("on_run", None)
48-
if not callable(self.on_run):
49-
raise TypeError("Expected a callable object")
50-
super().__init__(name, **kwargs)
51-
52-
async def run(self, aiot):
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)
59-
6033

6134
class Location(ArduinoCloudObject):
6235
def __init__(self, name, **kwargs):
@@ -80,24 +53,22 @@ def __init__(self, name, **kwargs):
8053

8154
class Schedule(ArduinoCloudObject):
8255
def __init__(self, name, **kwargs):
83-
kwargs.update({("runnable", True)}) # Force task creation.
56+
kwargs.update({("on_run", self.on_run)})
8457
self.on_active = kwargs.pop("on_active", None)
8558
# Uncomment to allow the schedule to change in runtime.
8659
# kwargs["on_write"] = kwargs.get("on_write", lambda aiot, value: None)
8760
self.active = False
8861
super().__init__(name, keys={"frm", "to", "len", "msk"}, **kwargs)
8962

90-
async def run(self, aiot):
91-
while True:
92-
if self.initialized:
93-
ts = timestamp() + aiot.get("tz_offset", 0)
94-
if ts > self.frm and ts < (self.frm + self.len):
95-
if not self.active and self.on_active is not None:
96-
self.on_active(aiot, self.value)
97-
self.active = True
98-
else:
99-
self.active = False
100-
await asyncio.sleep(self.interval)
63+
def on_run(self, aiot):
64+
if self.initialized:
65+
ts = timestamp() + aiot.get("tz_offset", 0)
66+
if ts > self.frm and ts < (self.frm + self.len):
67+
if not self.active and self.on_active is not None:
68+
self.on_active(aiot, self.value)
69+
self.active = True
70+
else:
71+
self.active = False
10172

10273

10374
class Television(ArduinoCloudObject):

0 commit comments

Comments
 (0)