-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
87 lines (76 loc) · 2.12 KB
/
main.py
File metadata and controls
87 lines (76 loc) · 2.12 KB
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
86
87
import time
import json
import uasyncio as asyncio
import network
from machine import Pin
import web
def get_config():
try:
with open("config.json", "r") as fp:
d = json.load(fp)
except (ValueError, OSError):
return None, None, None, None, None
else:
try:
return (d["ap"], d["pw"], d["mp"], d["im"], d["om"])
except KeyError:
return None, None, None, None, None
def main():
# Wait before boot, and check GPIO0. If it is pulled down, then
# skip network config and enable AP.
enable_ap = False
led = Pin(2, mode=Pin.OUT)
button = Pin(0, mode=Pin.IN, pull=Pin.PULL_UP)
for i in range(15):
led.value(not led.value())
enable_ap = enable_ap or (button.value() == 0)
time.sleep(0.2)
# Wlan connection details, and maximum power
ap, pw, maxpower, inmod, outmod = get_config()
# Enable AP if config could not be loaded
enable_ap = enable_ap or ap is None
# Start AP if button was pressed or config not done
if enable_ap:
print ("Starting AP mode")
wlan = network.WLAN(network.AP_IF)
else:
print ("Starting STATION mode")
wlan = network.WLAN(network.STA_IF)
# Handle interface already up during a soft-boot
if wlan.active() and wlan.isconnected():
wlan.disconnect()
time.sleep(1)
wlan.active(True)
if enable_ap:
wlan.config(essid="SunspecBridge")
while True:
print("Waiting for AP to come up...")
if wlan.active():
print("AP available as {}".format(wlan.ifconfig()[0]))
break
time.sleep(2)
else:
wlan.connect(ap, pw)
while True:
print("Waiting for WiFi connection...")
if wlan.isconnected():
print("Connected to WiFi as {}".format(wlan.ifconfig()[0]))
break
time.sleep(2)
# Import modules
try:
sunspec = __import__(outmod)
pvinverter = __import__(inmod)
except ImportError:
print ("Error loading conversion layer!")
asyncio.run(web.main())
else:
gc.collect()
print ("Memory free", gc.mem_free())
# Main loop
print ("Starting main loop")
sunspec_service = sunspec.Sunspec()
sunspec_service.set_maxpower(maxpower)
asyncio.run(asyncio.gather(web.main(), sunspec_service.main(), pvinverter.main(sunspec_service)))
if __name__ == "__main__":
main()