diff --git a/src/arduino_iot_cloud/__init__.py b/src/arduino_iot_cloud/__init__.py index 7fba1ea..3555b05 100644 --- a/src/arduino_iot_cloud/__init__.py +++ b/src/arduino_iot_cloud/__init__.py @@ -165,4 +165,44 @@ class Television(ArduinoCloudObject): INPUT_XBOX = 60 def __init__(self, name, **kwargs): - super().__init__(name, keys={"swi", "vol", "mut", "pbc", "inp", "cha"}, **kwargs) + super().__init__( + name, keys={"swi", "vol", "mut", "pbc", "inp", "cha"}, **kwargs + ) + + +def async_wifi_connection(client=None, connecting=[False]): + import time + import network + import logging + + try: + from secrets import WIFI_SSID + from secrets import WIFI_PASS + except Exception: + raise ( + Exception("Network is not configured. Set SSID and passwords in secrets.py") + ) + + wlan = network.WLAN(network.STA_IF) + + if wlan.isconnected(): + if connecting[0]: + connecting[0] = False + logging.info(f"WiFi connected {wlan.ifconfig()}") + if client is not None: + client.update_systime() + elif connecting[0]: + logging.info("WiFi is down. Trying to reconnect.") + else: + wlan.active(True) + wlan.connect(WIFI_SSID, WIFI_PASS) + connecting[0] = True + logging.info("WiFi is down. Trying to reconnect.") + + # Running in sync mode, block until WiFi is connected. + if client is None: + while not wlan.isconnected(): + logging.info("Trying to connect to WiFi.") + time.sleep(1.0) + connecting[0] = False + logging.info(f"WiFi Connected {wlan.ifconfig()}") diff --git a/src/arduino_iot_cloud/ucloud.py b/src/arduino_iot_cloud/ucloud.py index 78213d8..cff1933 100644 --- a/src/arduino_iot_cloud/ucloud.py +++ b/src/arduino_iot_cloud/ucloud.py @@ -180,6 +180,8 @@ def __init__( self.last_ping = timestamp() self.senmlpack = SenmlPack("", self.senml_generic_callback) self.started = False + self.ntp_server = ntp_server + self.ntp_timeout = ntp_timeout if "pin" in ssl_params: try: @@ -200,7 +202,7 @@ def __init__( self.device_topic = b"/a/d/" + device_id + b"/e/i" # Update RTC from NTP server on MicroPython. - self.update_systime(ntp_server, ntp_timeout) + self.update_systime() # If no server/port were passed in args, set the default server/port # based on authentication type. @@ -234,11 +236,11 @@ def get(self, key, default=None): return self[key] return default - def update_systime(self, server, timeout): + def update_systime(self, server=None, timeout=None): try: import ntptime - ntptime.host = server - ntptime.timeout = timeout + ntptime.host = self.ntp_server if server is None else server + ntptime.timeout = self.ntp_timeout if timeout is None else timeout ntptime.settime() logging.info("RTC time set from NTP.") except ImportError: