Abstract away platform-dependent pin references

Quote taken straight from the docstring of get_pin:

>Cross-platform method to find a pin by string.
>
>The pin definitions are platform-dependent, but this provides
>a way to say "I'm using pin D20" without rolling a D20 and
>having to actually learn MicroPython/CircuitPython and the
>differences in how they handle pinouts.
>
>This also makes the keymap sanity checker actually work for
>CircuitPython boards, since it's not possible in CPY to
>define a module stub for `board` that uses Passthrough
>natively (which is how the MicroPython stub worked originally)
This commit is contained in:
Josh Klar
2018-10-07 01:40:09 -07:00
parent ec9591ad8a
commit 392f8d7e51
6 changed files with 68 additions and 19 deletions

40
kmk/common/pins.py Normal file
View File

@@ -0,0 +1,40 @@
try:
import board
PLATFORM = 'CircuitPython'
PIN_SOURCE = board
except ImportError:
import machine
PLATFORM = 'MicroPython'
PIN_SOURCE = machine.Pin.board
except ImportError:
from kmk.common.types import Passthrough
PLATFORM = 'Unit Testing'
PIN_SOURCE = Passthrough()
def get_pin(pin):
'''
Cross-platform method to find a pin by string.
The pin definitions are platform-dependent, but this provides
a way to say "I'm using pin D20" without rolling a D20 and
having to actually learn MicroPython/CircuitPython and the
differences in how they handle pinouts.
This also makes the keymap sanity checker actually work for
CircuitPython boards, since it's not possible in CPY to
define a module stub for `board` that uses Passthrough
natively (which is how the MicroPython stub worked originally)
'''
return getattr(PIN_SOURCE, pin)
class PinLookup:
def __getattr__(self, attr):
return get_pin(attr)
Pin = PinLookup()

View File

@@ -8,3 +8,19 @@ class AttrDict(dict):
'''
def __getattr__(self, key):
return self[key]
class Anything:
'''
A stub class which will repr as a provided name
'''
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Anything<{}>'.format(self.name)
class Passthrough:
def __getattr__(self, attr):
return Anything(attr)