-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.py
193 lines (158 loc) · 5.6 KB
/
tasks.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import ast
import os
import subprocess
import time
from pathlib import Path
import yaml
from PIL import Image
from invoke import task, Context
BASE_DIR = Path(__file__).parent.resolve(strict=True)
SRC_DIR = BASE_DIR / "src"
TESTS_DIR = BASE_DIR / "test"
MICROPYTHON_DEPENDENCIES = [
# "github:miguelgrinberg/microdot/src/microdot.py",
# "github:miguelgrinberg/microdot/src/microdot_asyncio.py",
]
@task
def test(c: Context) -> None:
"""Run tests."""
with c.cd(BASE_DIR):
path = os.getenv("PYTHONPATH", "")
c.run(
"pytest",
pty=True,
echo=True,
env={"PYTHONPATH": f"{SRC_DIR}:{path}"},
)
@task(name="list")
def list_boards(c: Context) -> None:
"""List connected boards with mpremote."""
c.run("mpremote devs", pty=True, echo=True)
@task
def provision_all(c: Context, *, initial: bool = True) -> None:
"""Provision all connected boards sequentially."""
ids = get_all_board_ids()
for board_id in ids:
provision(c, board_id, initial=initial)
@task
def provision(c: Context, board_id: str, *, initial: bool = True) -> None:
"""Install dependencies and copy project files to the board."""
prepare(board_id)
download_image(c, board_id)
if initial:
wipe(c, board_id)
with c.cd(SRC_DIR):
if MICROPYTHON_DEPENDENCIES:
deps = " ".join(MICROPYTHON_DEPENDENCIES)
c.run(
f"mpremote connect id:{board_id} " f"mip install {deps}",
pty=True,
echo=True,
)
update_code(c, board_id)
@task
def download_image(c: Context, board_id: str) -> None:
"""Download and prepare the proper plant picture for the board."""
provisioning = get_provisioning(board_id)
plant_id = provisioning["HA_PLANT_ID"]
data = query_ha_state(plant_id)
image_url = data["attributes"]["entity_picture"]
image_path = SRC_DIR / "images" / "plant.jpg"
c.run(f"curl -o {image_path} {image_url}", pty=True, echo=True)
# resize image_path to 128x128 with Pillow
image = Image.open(image_path)
image = image.resize((128, 128))
# crop image to 104x128, centered
left = int((image.width - 104) / 2)
top = 0
right = left + 104
bottom = top + 128
image = image.crop((left, top, right, bottom))
# convert image to grayscale
image = image.convert("L")
image.save(image_path)
def query_ha_state(entity_id):
import requests
import sys
sys.path.insert(0, str(SRC_DIR))
from secrets import HA_ACCESS_TOKEN, HA_BASE_URL
url = HA_BASE_URL + "/states/" + entity_id
headers = {"Authorization": "Bearer " + HA_ACCESS_TOKEN}
res = requests.get(url, headers=headers)
data = res.json()
return data
@task
def wipe(c: Context, board_id: str) -> None:
"""Wipe the board with mpremote."""
c.run(
f'mpremote connect id:{board_id} exec --no-follow "'
"import os, machine, rp2;"
"os.umount('/');"
"bdev = rp2.Flash();"
"os.VfsLfs2.mkfs(bdev, progsize=256);"
"vfs = os.VfsLfs2(bdev, progsize=256);"
"os.mount(vfs, '/');"
'machine.reset()"',
pty=True,
echo=True,
)
print("Board wiped, waiting for it to reboot...")
time.sleep(3)
print("Done!")
@task
def update_code(c: Context, board_id: str) -> None:
"""Update code on the board."""
with c.cd(SRC_DIR):
c.run("find . -name '.DS_Store' -delete", pty=True, echo=True)
c.run(
"find . -name '.pytest_cache' -type d -exec rm -r {} +", pty=True, echo=True
)
c.run(
"find . -name '__pycache__' -type d -exec rm -r {} +", pty=True, echo=True
)
c.run(
f"mpremote connect id:{board_id} cp -r . : + reset",
pty=True,
echo=True,
)
def prepare(board_id: str) -> None:
"""Update secrets.py with the correct values for the board."""
provisioning = get_provisioning(board_id)
with (SRC_DIR / "secrets.py").open() as f:
secrets = f.read()
secrets = ast.parse(secrets)
for node in secrets.body:
if isinstance(node, ast.Assign):
for target in node.targets:
var_name = target.id
if var_name in provisioning:
node.value = ast.Constant(provisioning[var_name])
elif var_name.lower() in provisioning:
state = query_ha_state(provisioning[var_name.lower()])
value = int(state.get("state", -1))
node.value = ast.Constant(value)
with (SRC_DIR / "secrets.py").open("w") as f:
f.write(ast.unparse(secrets))
def get_all_board_ids():
# Here's an example output of `mpremote devs`:
# /dev/cu.Bluetooth-Incoming-Port None 0000:0000 None None
# /dev/cu.usbmodem101 e6614864d35f9934 2e8a:0005 MicroPython Board in FS mode
# /dev/cu.usbmodem112201 e6614864d3417f36 2e8a:0005 MicroPython Board in FS mode
output = subprocess.run(["mpremote", "devs"], stdout=subprocess.PIPE).stdout.decode(
"utf-8"
)
lines = output.splitlines()
ids = []
for line in lines:
if "Bluetooth" not in line:
ids.append(line.split()[1])
return ids
def get_provisioning(board_id: str) -> dict[str, str]:
# load provisioning.yaml
with (BASE_DIR / "provisioning.yaml").open() as f:
provisioning = yaml.safe_load(f)
provisioning = provisioning.get(board_id)
if not provisioning:
msg = "Couldn't find board %s in provisioning.yaml" % board_id
raise ValueError(msg)
return provisioning