forked from adafruit/Adafruit_Blinka
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimporting.py
More file actions
139 lines (120 loc) · 5.1 KB
/
Copy pathimporting.py
File metadata and controls
139 lines (120 loc) · 5.1 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
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
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_blinka.importing` - Import utilities that run on Linux and MicroPython
======================================================================================
* Author(s): Melissa LeBlanc-Williams
"""
try:
from importlib import import_module
except ImportError as e:
def import_module(module_name: str, package: str = None):
"""importlib not available, define an alternate import_module function"""
package_list = []
if package is not None:
package_list.append(package)
return __import__(module_name, globals(), locals(), package_list)
from adafruit_blinka.agnostic import detector
PLATFORM_DEPENDENCY_INSTALLS = {
"Adafruit_BBIO": "pip install Adafruit_BBIO",
"Jetson": "pip install Jetson.GPIO",
"RPi": "pip install RPi.GPIO",
"_rpi_ws281x": "pip install rpi_ws281x",
"adafruit_raspberry_pi5_neopixel_write": (
"pip install Adafruit-Blinka-Raspberry-Pi5-Neopixel"
),
"lgpio": (
"pip install lgpio --find-links "
"https://github.com/adafruit/lgpio-python-wheels/raw/main/wheels/"
),
}
def raise_for_missing_platform_dependency(error: ModuleNotFoundError):
"""Raise a helpful message for known optional platform dependencies."""
install_command = PLATFORM_DEPENDENCY_INSTALLS.get(error.name)
if install_command is None:
raise error
message = (
f"The platform library '{error.name}' was not found. "
f"To install, try typing: {install_command}"
)
if error.name == "lgpio":
message += (
"\nOn Raspberry Pi OS, you can also try: "
"sudo apt-get install -y python3-lgpio"
)
raise RuntimeError(message) from error
def get_import_file(json_file_name, script_file_location):
"""Get the full path to the microcontroller imports file."""
try:
from pathlib import Path
script_folder = Path(script_file_location).parent.absolute()
return script_folder / json_file_name
except ImportError:
# MicroPython doesn't have pathlib, so we have to do it manually
if script_file_location.startswith("/"):
script_folder = "/".join(script_file_location.split("/")[:-1])
else:
script_folder = "."
return f"{script_folder}/{json_file_name}"
def import_mod(caller_globals, module_name: str, package_name: str = "*"):
"""Function to allow importing with * or specific package name."""
try:
if package_name == "*":
module = import_module(module_name)
caller_globals.update(
{name: getattr(module, name) for name in module.__all__}
if hasattr(module, "__all__")
else {
key: value
for (key, value) in module.__dict__.items()
if not key.startswith("_")
}
)
else:
module = import_module(module_name, package=package_name)
caller_globals[package_name] = getattr(module, package_name)
except ModuleNotFoundError as error:
raise_for_missing_platform_dependency(error)
def import_microcontroller(
caller_globals,
microcontroller_imports,
module_extension: str = "",
package_name: str = "*",
):
"""Detect and import the microcontroller module and package based on detected hardware"""
if module_extension[0:1] != "." and module_extension != "":
# Make sure the module extension starts with a dot if it's not empty
module_extension = f".{module_extension}"
for chip_key, chip_module in microcontroller_imports.items():
if getattr(detector.chip, chip_key):
if isinstance(chip_module, dict):
# Loop through the children and import the first one that matches
for board_key, board_chip_module in chip_module.items():
if board_key.startswith("any_") and getattr(
detector.board, board_key
):
# import Pin from the microcontroller module
import_mod(
caller_globals,
f"{board_chip_module}{module_extension}",
package_name,
)
return True
if board_key == getattr(detector.board, board_key):
print(f"Detected board: {board_key}")
import_mod(
caller_globals,
f"{board_chip_module}{module_extension}",
package_name,
)
return True
import_mod(
caller_globals,
f"{chip_module['default']}{module_extension}",
package_name,
)
return True
import_mod(caller_globals, f"{chip_module}{module_extension}", package_name)
return True
return False