-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsystem.py
85 lines (69 loc) · 2.16 KB
/
system.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from axp202c import PMU
from machine import RTC
from micropython import const
from network import WLAN, STA_IF
from ntptime import settime
from time import sleep as sleep_delay
from config import WIFI_CONNECTIONS
from exceptions import (
FailedToConnectToNetworkException,
FailedCurrentTimeRequestException,
)
# Number of attempts of each saved network to
# connect before attempting a new one
NETWORK_RETRIES = const(5)
def connect_to_network():
sta_if = WLAN(STA_IF)
sta_if.active(True)
for essid, password in WIFI_CONNECTIONS:
sta_if.connect(essid, password)
current_try = 0
while current_try < NETWORK_RETRIES:
sleep_delay(2)
if sta_if.isconnected():
return sta_if
current_try += 1
if not sta_if.isconnected():
raise FailedToConnectToNetworkException(
'Unable to connect to any available network'
)
class SystemManager:
"""
Manager to store and update state of the system.
"""
def __init__(self):
self.wifi_connection = None
self.power_manager = None
def update_system(self):
"""
High level task to re-trigger checks to keep system up to date.
checks wifi connection, establishes system time etc.
:return: None
"""
self.reconnect_wifi_connection()
self.update_system_time()
self.power_manager = PMU()
def reconnect_wifi_connection(self):
"""
Attempt to connect and reconnect a wifi connection on
nonexistence/connection failure.
:return: None
"""
if not self.wifi_connection or not self.wifi_connection.isconnected():
try:
self.wlan_connection = connect_to_network()
except FailedToConnectToNetworkException:
pass
@staticmethod
def update_system_time():
"""
Pull down the latest NTP backed time and caches it locally.
:return: None
"""
try:
settime()
except FailedCurrentTimeRequestException:
pass
@property
def system_time(self):
return RTC().datetime()