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