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 Object supporting CircuitPython-style of static symbols
17 as seen with Direction.OUTPUT, Pull.UP
22 Assumes instance will be found as attribute of own class.
23 Returns dot-subscripted path to instance
24 (assuming absolute import of containing package)
28 if getattr(cls, key) is self:
29 return "{}.{}.{}".format(cls.__module__, cls.__qualname__, key)
35 Inspects attributes of the class for instances of the class
36 and returns as key,value pairs mirroring dict#iteritems
39 val = getattr(cls, key)
40 if isinstance(cls, val):
45 """An object that automatically deinitializes hardware with a context manager."""
50 def __exit__(self, exc_type, exc_value, traceback):
53 # pylint: disable=no-self-use
55 """Free any hardware used by the object."""
58 # pylint: enable=no-self-use
61 class Lockable(ContextManaged):
62 """An object that must be locked to prevent collisions on a microcontroller resource."""
67 """Attempt to grab the lock. Return True on success, False if the lock is already taken."""
74 """Release the lock so others may use the resource."""
79 def load_settings_toml():
80 """Load values from settings.toml into os.environ, so that os.getenv returns them.
81 Note: This does not work in MicroPython because of the tomllib module not being available.
86 import toml as tomllib
88 if not os.path.isfile("settings.toml"):
89 raise FileNotFoundError("settings.toml not found in current directory.")
91 print("settings.toml found. Updating environment variables:")
92 with open("settings.toml", "rb") as toml_file:
94 settings = tomllib.load(toml_file)
95 except tomllib.TOMLDecodeError as e:
96 raise tomllib.TOMLDecodeError("Error with settings.toml file.") from e
99 for key, value in settings.items():
100 if not isinstance(value, (bool, int, float, str)):
101 invalid_types.add(type(value).__name__)
103 invalid_types_string = ", ".join(invalid_types)
105 f"The types: '{invalid_types_string}' are not supported in settings.toml."
108 for key, value in settings.items():
110 if key in os.environ:
111 print(f" - {key} already exists in environment")
113 os.environ[key] = str(value)
114 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