]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/__init__.py
Added GENERIX_X86 branch
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / __init__.py
1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4 """
5 `adafruit_blinka` - Runtime utility objects for re-implementation of CircuitPython API
6 ======================================================================================
7
8 * Author(s): cefn
9 """
10
11
12 class Enum:
13     """
14     Object supporting CircuitPython-style of static symbols
15     as seen with Direction.OUTPUT, Pull.UP
16     """
17
18     def __repr__(self):
19         """
20         Assumes instance will be found as attribute of own class.
21         Returns dot-subscripted path to instance
22         (assuming absolute import of containing package)
23         """
24         cls = type(self)
25         for key in dir(cls):
26             if getattr(cls, key) is self:
27                 return "{}.{}.{}".format(cls.__module__, cls.__qualname__, key)
28         return repr(self)
29
30     @classmethod
31     def iteritems(cls):
32         """
33         Inspects attributes of the class for instances of the class
34         and returns as key,value pairs mirroring dict#iteritems
35         """
36         for key in dir(cls):
37             val = getattr(cls, key)
38             if isinstance(cls, val):
39                 yield (key, val)
40
41
42 class ContextManaged:
43     """An object that automatically deinitializes hardware with a context manager."""
44
45     def __enter__(self):
46         return self
47
48     def __exit__(self, exc_type, exc_value, traceback):
49         self.deinit()
50
51     # pylint: disable=no-self-use
52     def deinit(self):
53         """Free any hardware used by the object."""
54         return
55
56     # pylint: enable=no-self-use
57
58
59 class Lockable(ContextManaged):
60     """An object that must be locked to prevent collisions on a microcontroller resource."""
61
62     _locked = False
63
64     def try_lock(self):
65         """Attempt to grab the lock. Return True on success, False if the lock is already taken."""
66         if self._locked:
67             return False
68         self._locked = True
69         return True
70
71     def unlock(self):
72         """Release the lock so others may use the resource."""
73         if self._locked:
74             self._locked = False
75         else:
76             raise ValueError("Not locked")
77
78
79 def patch_system():
80     """Patch modules that may be different due to the platform."""
81     # pylint: disable=import-outside-toplevel
82     import sys
83     from adafruit_blinka.agnostic import time
84
85     # pylint: enable=import-outside-toplevel
86
87     sys.modules["time"] = time