1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
5 `adafruit_blinka` - Runtime utility objects for re-implementation of CircuitPython API
6 ======================================================================================
16 import toml as tomllib
21 Object supporting CircuitPython-style of static symbols
22 as seen with Direction.OUTPUT, Pull.UP
27 Assumes instance will be found as attribute of own class.
28 Returns dot-subscripted path to instance
29 (assuming absolute import of containing package)
33 if getattr(cls, key) is self:
34 return "{}.{}.{}".format(cls.__module__, cls.__qualname__, key)
40 Inspects attributes of the class for instances of the class
41 and returns as key,value pairs mirroring dict#iteritems
44 val = getattr(cls, key)
45 if isinstance(cls, val):
50 """An object that automatically deinitializes hardware with a context manager."""
55 def __exit__(self, exc_type, exc_value, traceback):
58 # pylint: disable=no-self-use
60 """Free any hardware used by the object."""
63 # pylint: enable=no-self-use
66 class Lockable(ContextManaged):
67 """An object that must be locked to prevent collisions on a microcontroller resource."""
72 """Attempt to grab the lock. Return True on success, False if the lock is already taken."""
79 """Release the lock so others may use the resource."""
84 def load_settings_toml(*, return_toml=False):
85 """Load values from settings.toml into os.environ, so that os.getenv returns them."""
86 if not os.path.isfile("settings.toml"):
87 raise FileNotFoundError("settings.toml not cound in current directory.")
89 print("settings.toml found. Updating environment variables:")
90 with open("settings.toml", "rb") as toml_file:
92 settings = tomllib.load(toml_file)
93 except tomllib.TOMLDecodeError as e:
94 raise tomllib.TOMLDecodeError("Error with settings.toml file.") from e
97 for key, value in settings.items():
98 if not isinstance(value, (bool, int, float, str)):
99 invalid_types.add(type(value).__name__)
101 invalid_types_string = ", ".join(invalid_types)
103 f"The types: '{invalid_types_string}' are not supported in settings.toml."
106 for key, value in settings.items():
108 if key in os.environ:
109 print(f" - {key} already exists in environment")
111 os.environ[key] = str(value)
112 print(f" - {key} added")
120 """Patch modules that may be different due to the platform."""
121 # pylint: disable=import-outside-toplevel
123 from adafruit_blinka.agnostic import time
125 # pylint: enable=import-outside-toplevel
127 sys.modules["time"] = time