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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
|
diff --git a/lib/micropython-lib/micropython/requests/manifest.py b/lib/micropython-lib/micropython/requests/manifest.py
new file mode 100644
index 000000000..eb7bb2d42
--- /dev/null
+++ b/lib/micropython-lib/micropython/requests/manifest.py
@@ -0,0 +1,3 @@
+metadata(version="0.10.0", pypi="requests")
+
+package("requests")
diff --git a/lib/micropython-lib/micropython/requests/requests/__init__.py b/lib/micropython-lib/micropython/requests/requests/__init__.py
new file mode 100644
index 000000000..a9a183619
--- /dev/null
+++ b/lib/micropython-lib/micropython/requests/requests/__init__.py
@@ -0,0 +1,217 @@
+import socket
+
+
+class Response:
+ def __init__(self, f):
+ self.raw = f
+ self.encoding = "utf-8"
+ self._cached = None
+
+ def close(self):
+ if self.raw:
+ self.raw.close()
+ self.raw = None
+ self._cached = None
+
+ @property
+ def content(self):
+ if self._cached is None:
+ try:
+ self._cached = self.raw.read()
+ finally:
+ self.raw.close()
+ self.raw = None
+ return self._cached
+
+ @property
+ def text(self):
+ return str(self.content, self.encoding)
+
+ def json(self):
+ import json
+
+ return json.loads(self.content)
+
+
+def request(
+ method,
+ url,
+ data=None,
+ json=None,
+ headers=None,
+ stream=None,
+ auth=None,
+ timeout=None,
+ parse_headers=True,
+):
+ if headers is None:
+ headers = {}
+
+ redirect = None # redirection url, None means no redirection
+ chunked_data = data and getattr(data, "__next__", None) and not getattr(data, "__len__", None)
+
+ if auth is not None:
+ import binascii
+
+ username, password = auth
+ formated = b"{}:{}".format(username, password)
+ formated = str(binascii.b2a_base64(formated)[:-1], "ascii")
+ headers["Authorization"] = "Basic {}".format(formated)
+
+ try:
+ proto, dummy, host, path = url.split("/", 3)
+ except ValueError:
+ proto, dummy, host = url.split("/", 2)
+ path = ""
+ if proto == "http:":
+ port = 80
+ elif proto == "https:":
+ import tls
+
+ port = 443
+ else:
+ raise ValueError("Unsupported protocol: " + proto)
+
+ if ":" in host:
+ host, port = host.split(":", 1)
+ port = int(port)
+
+ ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
+ ai = ai[0]
+
+ resp_d = None
+ if parse_headers is not False:
+ resp_d = {}
+
+ s = socket.socket(ai[0], socket.SOCK_STREAM, ai[2])
+
+ if timeout is not None:
+ # Note: settimeout is not supported on all platforms, will raise
+ # an AttributeError if not available.
+ s.settimeout(timeout)
+
+ try:
+ s.connect(ai[-1])
+ if proto == "https:":
+ context = tls.SSLContext(tls.PROTOCOL_TLS_CLIENT)
+ context.verify_mode = tls.CERT_NONE
+ s = context.wrap_socket(s, server_hostname=host)
+ s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
+
+ if "Host" not in headers:
+ headers["Host"] = host
+
+ if json is not None:
+ assert data is None
+ from json import dumps
+
+ data = dumps(json)
+
+ if "Content-Type" not in headers:
+ headers["Content-Type"] = "application/json"
+
+ if data:
+ if chunked_data:
+ if "Transfer-Encoding" not in headers and "Content-Length" not in headers:
+ headers["Transfer-Encoding"] = "chunked"
+ elif "Content-Length" not in headers:
+ headers["Content-Length"] = str(len(data))
+
+ if "Connection" not in headers:
+ headers["Connection"] = "close"
+
+ # Iterate over keys to avoid tuple alloc
+ for k in headers:
+ s.write(k)
+ s.write(b": ")
+ s.write(headers[k])
+ s.write(b"\r\n")
+
+ s.write(b"\r\n")
+
+ if data:
+ if chunked_data:
+ if headers.get("Transfer-Encoding", None) == "chunked":
+ for chunk in data:
+ s.write(b"%x\r\n" % len(chunk))
+ s.write(chunk)
+ s.write(b"\r\n")
+ s.write("0\r\n\r\n")
+ else:
+ for chunk in data:
+ s.write(chunk)
+ else:
+ s.write(data)
+
+ l = s.readline()
+ # print(l)
+ l = l.split(None, 2)
+ if len(l) < 2:
+ # Invalid response
+ raise ValueError("HTTP error: BadStatusLine:\n%s" % l)
+ status = int(l[1])
+ reason = ""
+ if len(l) > 2:
+ reason = l[2].rstrip()
+ while True:
+ l = s.readline()
+ if not l or l == b"\r\n":
+ break
+ # print(l)
+ if l.startswith(b"Transfer-Encoding:"):
+ if b"chunked" in l:
+ raise ValueError("Unsupported " + str(l, "utf-8"))
+ elif l.startswith(b"Location:") and not 200 <= status <= 299:
+ if status in [301, 302, 303, 307, 308]:
+ redirect = str(l[10:-2], "utf-8")
+ else:
+ raise NotImplementedError("Redirect %d not yet supported" % status)
+ if parse_headers is False:
+ pass
+ elif parse_headers is True:
+ l = str(l, "utf-8")
+ k, v = l.split(":", 1)
+ resp_d[k] = v.strip()
+ else:
+ parse_headers(l, resp_d)
+ except OSError:
+ s.close()
+ raise
+
+ if redirect:
+ s.close()
+ if status in [301, 302, 303]:
+ return request("GET", redirect, None, None, headers, stream)
+ else:
+ return request(method, redirect, data, json, headers, stream)
+ else:
+ resp = Response(s)
+ resp.status_code = status
+ resp.reason = reason
+ if resp_d is not None:
+ resp.headers = resp_d
+ return resp
+
+
+def head(url, **kw):
+ return request("HEAD", url, **kw)
+
+
+def get(url, **kw):
+ return request("GET", url, **kw)
+
+
+def post(url, **kw):
+ return request("POST", url, **kw)
+
+
+def put(url, **kw):
+ return request("PUT", url, **kw)
+
+
+def patch(url, **kw):
+ return request("PATCH", url, **kw)
+
+
+def delete(url, **kw):
+ return request("DELETE", url, **kw)
diff --git a/lib/micropython-lib/python-ecosys/mip/manifest.py b/lib/micropython-lib/python-ecosys/mip/manifest.py
new file mode 100644
index 000000000..88fb08da1
--- /dev/null
+++ b/lib/micropython-lib/python-ecosys/mip/manifest.py
@@ -0,0 +1,5 @@
+metadata(version="0.3.0", description="On-device package installer for network-capable boards")
+
+require("requests")
+
+package("mip", opt=3)
diff --git a/lib/micropython-lib/python-ecosys/mip/mip/__init__.py b/lib/micropython-lib/python-ecosys/mip/mip/__init__.py
new file mode 100644
index 000000000..0c3c6f204
--- /dev/null
+++ b/lib/micropython-lib/python-ecosys/mip/mip/__init__.py
@@ -0,0 +1,186 @@
+# MicroPython package installer
+# MIT license; Copyright (c) 2022 Jim Mussared
+
+from micropython import const
+import requests
+import sys
+
+
+_PACKAGE_INDEX = const("https://micropython.org/pi/v2")
+_CHUNK_SIZE = 128
+
+
+# This implements os.makedirs(os.dirname(path))
+def _ensure_path_exists(path):
+ import os
+
+ split = path.split("/")
+
+ # Handle paths starting with "/".
+ if not split[0]:
+ split.pop(0)
+ split[0] = "/" + split[0]
+
+ prefix = ""
+ for i in range(len(split) - 1):
+ prefix += split[i]
+ try:
+ os.stat(prefix)
+ except:
+ os.mkdir(prefix)
+ prefix += "/"
+
+
+# Copy from src (stream) to dest (function-taking-bytes)
+def _chunk(src, dest):
+ buf = memoryview(bytearray(_CHUNK_SIZE))
+ while True:
+ n = src.readinto(buf)
+ if n == 0:
+ break
+ dest(buf if n == _CHUNK_SIZE else buf[:n])
+
+
+# Check if the specified path exists and matches the hash.
+def _check_exists(path, short_hash):
+ import os
+
+ try:
+ import binascii
+ import hashlib
+
+ with open(path, "rb") as f:
+ hs256 = hashlib.sha256()
+ _chunk(f, hs256.update)
+ existing_hash = str(binascii.hexlify(hs256.digest())[: len(short_hash)], "utf-8")
+ return existing_hash == short_hash
+ except:
+ return False
+
+
+def _rewrite_url(url, branch=None):
+ if not branch:
+ branch = "HEAD"
+ if url.startswith("github:"):
+ url = url[7:].split("/")
+ url = (
+ "https://raw.githubusercontent.com/"
+ + url[0]
+ + "/"
+ + url[1]
+ + "/"
+ + branch
+ + "/"
+ + "/".join(url[2:])
+ )
+ elif url.startswith("gitlab:"):
+ url = url[7:].split("/")
+ url = (
+ "https://gitlab.com/"
+ + url[0]
+ + "/"
+ + url[1]
+ + "/-/raw/"
+ + branch
+ + "/"
+ + "/".join(url[2:])
+ )
+ return url
+
+
+def _download_file(url, dest):
+ response = requests.get(url)
+ try:
+ if response.status_code != 200:
+ print("Error", response.status_code, "requesting", url)
+ return False
+
+ print("Copying:", dest)
+ _ensure_path_exists(dest)
+ with open(dest, "wb") as f:
+ _chunk(response.raw, f.write)
+
+ return True
+ finally:
+ response.close()
+
+
+def _install_json(package_json_url, index, target, version, mpy):
+ response = requests.get(_rewrite_url(package_json_url, version))
+ try:
+ if response.status_code != 200:
+ print("Package not found:", package_json_url)
+ return False
+
+ package_json = response.json()
+ finally:
+ response.close()
+ for target_path, short_hash in package_json.get("hashes", ()):
+ fs_target_path = target + "/" + target_path
+ if _check_exists(fs_target_path, short_hash):
+ print("Exists:", fs_target_path)
+ else:
+ file_url = "{}/file/{}/{}".format(index, short_hash[:2], short_hash)
+ if not _download_file(file_url, fs_target_path):
+ print("File not found: {} {}".format(target_path, short_hash))
+ return False
+ for target_path, url in package_json.get("urls", ()):
+ fs_target_path = target + "/" + target_path
+ if not _download_file(_rewrite_url(url, version), fs_target_path):
+ print("File not found: {} {}".format(target_path, url))
+ return False
+ for dep, dep_version in package_json.get("deps", ()):
+ if not _install_package(dep, index, target, dep_version, mpy):
+ return False
+ return True
+
+
+def _install_package(package, index, target, version, mpy):
+ if (
+ package.startswith("http://")
+ or package.startswith("https://")
+ or package.startswith("github:")
+ or package.startswith("gitlab:")
+ ):
+ if package.endswith(".py") or package.endswith(".mpy"):
+ print("Downloading {} to {}".format(package, target))
+ return _download_file(
+ _rewrite_url(package, version), target + "/" + package.rsplit("/")[-1]
+ )
+ else:
+ if not package.endswith(".json"):
+ if not package.endswith("/"):
+ package += "/"
+ package += "package.json"
+ print("Installing {} to {}".format(package, target))
+ else:
+ if not version:
+ version = "latest"
+ print("Installing {} ({}) from {} to {}".format(package, version, index, target))
+
+ mpy_version = (
+ sys.implementation._mpy & 0xFF if mpy and hasattr(sys.implementation, "_mpy") else "py"
+ )
+
+ package = "{}/package/{}/{}/{}.json".format(index, mpy_version, package, version)
+
+ return _install_json(package, index, target, version, mpy)
+
+
+def install(package, index=None, target=None, version=None, mpy=True):
+ if not target:
+ for p in sys.path:
+ if p.endswith("/lib"):
+ target = p
+ break
+ else:
+ print("Unable to find lib dir in sys.path")
+ return
+
+ if not index:
+ index = _PACKAGE_INDEX
+
+ if _install_package(package, index.rstrip("/"), target, version, mpy):
+ print("Done")
+ else:
+ print("Package may be partially installed")
|