API Reference¶
SimulRPi.GPIO
¶
Module that partly fakes RPi.GPIO and simulates some I/O devices.
It simulates these I/O devices connected to a Raspberry Pi:
push buttons by listening to pressed keyboard keys and
LEDs by displaying red dots blinking in the terminal along with their GPIO channel number.
When a LED is turned on, it is shown as a red dot in the terminal. The pynput package is used to monitor the keyboard for any pressed key.
Example: terminal output
⬤ [9] ⬤ [10] 🔴 [11]
where each dot represents a LED and the number between brackets is the associated GPIO channel number.
Important
This library is not a Raspberry Pi emulator nor a complete mock-up of RPi.GPIO, only the most important functions that I needed for my Darth-Vader-RPi project were added.
If there is enough interest in this library, I will eventually mock more functions from RPi.GPIO.
-
SimulRPi.GPIO.
cleanup
()[source]¶ Clean up any resources (e.g. GPIO channels).
At the end of any program, it is good practice to clean up any resources you might have used. This is no different with RPi.GPIO. By returning all channels you have used back to inputs with no pull up/down, you can avoid accidental damage to your RPi by shorting out the pins. [Ref: RPi.GPIO wiki]
Also, the two threads responsible for displaying LEDs in the terminal and listening for pressed/released keys are stopped.
Note
On an RPi,
cleanup()
will:only clean up GPIO channels that your script has used
also clear the pin numbering system in use (BOARD or BCM)
Ref.: RPi.GPIO wiki
When using the
SimulRPi
package,cleanup()
will:stop the displaying thread
Manager.th_display_leds
stop the listening thread
Manager.th_listener
show the cursor again which was hidden in
display_leds()
reset the
GPIO.manager
’s attributes (an instance ofManager
)
-
SimulRPi.GPIO.
input
(channel)[source]¶ Read the value of a GPIO pin.
The listening thread is also started if possible.
- Parameters
channel (int) – Input channel number based on the numbering system you have specified (BOARD or BCM).
- Returns
state – If no
Pin
could be retrieved based on the given channel number, thenNone
is returned. Otherwise, thePin
’s state is returned: 1 (HIGH) or 0 (LOW).- Return type
- Raises
Exception – If the listening thread caught an exception that occurred in
on_press()
oron_release()
, the said exception will be raised here.
Note
The listening thread (for monitoring pressed keys) is started if there is no exception caught by the thread and if it is not alive, i.e. it is not already running.
Important
The reason for checking if there is no exception already caught by a thread, i.e.
if not manager.th_listener.exc
, is to avoid having another thread calling this function and re-starting the failed thread. Hence, we avoid raising aRuntimeError
on top of the thread’s already caught exception.
-
SimulRPi.GPIO.
output
(channel, state)[source]¶ Set the output state of a GPIO pin.
The displaying thread is also started if possible.
- Parameters
channel (int or list or tuple) –
Output channel number based on the numbering system you have specified (BOARD or BCM).
You can also provide a list or tuple of channel numbers:
chan_list = [11,12]
state (int or list or tuple) –
State of the GPIO channel: 1 (HIGH) or 0 (LOW).
You can also provide a list of states:
chan_list = [11,12] GPIO.output(chan_list, GPIO.LOW) # sets all to LOW GPIO.output(chan_list, (GPIO.HIGH, GPIO.LOW)) # sets 1st HIGH and 2nd LOW.
- Raises
Exception – If the displaying thread caught an exception that occurred in its target function
display_leds()
, the said exception will be raised here.
Note
The displaying thread (for showing “LEDs” on the terminal) is started if there is no exception caught by the thread and if it is not alive, i.e. it is not already running.
See also
input()
Read the Important message about why we need to check if there is an exception caught by the thread when trying to start it.
-
SimulRPi.GPIO.
setchannelnames
(channel_names)[source]¶ Set the channel names for multiple channels
The channel names will be displayed in the terminal along each LED symbol. If no channel name is given, then the channel number will be shown.
-
SimulRPi.GPIO.
setchannels
(gpio_channels)[source]¶ Set the attributes (e.g. channel_name and led_symbols) for multiple channels.
The attributes that can be updated for a given GPIO channel are:
channel_id
: unique identifierchannel_name
: will be shown along the LED symbol in the terminalchannel_number
: GPIO channel number based on the numbering system you have specified (BOARD or BCM).led_symbols
: should only be defined for output channels. It is a dictionary defining the symbols to be used when the LED is turned ON and OFF.key
: keyboard key associated with a channel, e.g. “cmd_r”.
- Parameters
gpio_channels (list) –
A list where each item is a dictionary defining the attributes for a given GPIO channel.
Example:
gpio_channels = [ { "channel_id": "lightsaber_button", "channel_name": "lightsaber_button", "channel_number": 23, "key": "cmd" }, { "channel_id": "lightsaber_led", "channel_name": "lightsaber", "channel_number": 22, "led_symbols": { "ON": "\033[1;31;48m⬤\033[1;37;0m", "OFF": "⬤" } } ]
- Raises
KeyError – Raised if two channels are using the same channel number.
-
SimulRPi.GPIO.
setdefaultsymbols
(default_led_symbols)[source]¶ Set the default LED symbols used by all output channels.
- Parameters
default_led_symbols (str or dict) –
Dictionary that maps each output state (
str
, {‘ON’, ‘OFF’}) to the LED symbol (str
).Example:
default_led_symbols = { 'ON': '🔵', 'OFF': '⚪ ' }
You can also provide the string
default_ascii
to make use of ASCII-based LED symbols for all output channels. Useful if you are still having problems displaying the default LED signs (which make use of special characters) after you have tried the solutions shown here:default_led_symbols = "default_ascii"
-
SimulRPi.GPIO.
setkeymap
(key_to_channel_map)[source]¶ Set the default keymap dictionary with new keys and channels.
The default dictionary default_key_to_channel_map that maps keyboard keys to GPIO channels can be modified by providing your own mapping
key_to_channel_map
containing only the keys and channels that you want to be modified.
-
SimulRPi.GPIO.
setmode
(mode)[source]¶ Set the numbering system used to identify the I/O pins on an RPi within
RPi.GPIO
.There are two ways of numbering the I/O pins on a Raspberry Pi within
RPi.GPIO
:The BOARD numbering system: refers to the pin numbers on the P1 header of the Raspberry Pi board
The BCM numbers: refers to the channel numbers on the Broadcom SOC.
- Parameters
mode (int) – Numbering system used to identify the I/O pins on an RPi: BOARD or BCM.
References
Function description and more info from RPi.GPIO wiki.
-
SimulRPi.GPIO.
setprinting
(enable_printing)[source]¶ Enable or disable printing to the terminal.
If printing is enabled, blinking red dots will be shown in the terminal, simulating LEDs connected to a Raspberry Pi. Otherwise, nothing will be printed in the terminal.
- Parameters
enable_printing (bool) – If True. printing to the terminal is enabled. Otherwise, printing will be disabled.
-
SimulRPi.GPIO.
setup
(channel, channel_type, pull_up_down=None, initial=None)[source]¶ Setup a GPIO channel as an input or output.
To configure a channel as an input:
GPIO.setup(channel, GPIO.IN)
To configure a channel as an output:
GPIO.setup(channel, GPIO.OUT)
You can also specify an initial value for your output channel:
GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH)
- Parameters
channel (int or list or tuple) –
GPIO channel number based on the numbering system you have specified (BOARD or BCM).
You can also provide a list or tuple of channel numbers. All channels will take the same values for the other parameters.
channel_type (int) – Type of a GPIO channel: e.g. 1 (GPIO.IN) or 0 (GPIO.OUT).
pull_up_down (int or None, optional) – Initial value of an input channel, e.g. GPIO.PUP_UP. Default value is
None
.initial (int or None, optional) – Initial value of an output channel, e.g. GPIO.HIGH. Default value is
None
.
References
-
SimulRPi.GPIO.
setwarnings
(show_warnings)[source]¶ Set warnings when configuring a GPIO pin other than the default (input).
It is possible that you have more than one script/circuit on the GPIO of your Raspberry Pi. As a result of this, if
RPi.GPIO
detects that a pin has been configured to something other than the default (input), you get a warning when you try to configure a script. [Ref: RPi.GPIO wiki]- Parameters
show_warnings (bool) – Whether to show warnings when using a pin other than the default GPIO function (input).
-
SimulRPi.GPIO.
wait
(timeout=2)[source]¶ Wait for certain events to complete.
Wait for the displaying and listening threads to do their tasks. If there was an exception caught and saved by one thread, then it is raised here.
If more than
timeout
seconds elapsed without any of the events described previously happening, the function exits.- Parameters
timeout (float) – How long to wait (in seconds) before exiting from this function. By default, we wait for 2 seconds.
- Raises
Exception – If the displaying or listening thread caught an exception, it will be raised here.
Important
This function is not called in
cleanup()
because if a thread exception is raised, it will not be caught in the main program becausecleanup()
should be found in afinally
block:try: do_something_with_gpio_api() GPIO.wait() except Exception as e: # Do something with error print(e) finally: GPIO.cleanup()
SimulRPi.manager
¶
Module that manages the PinDB
database, threads,
and default keymap.
The threads are responsible for displaying LEDs in the terminal and listening to the keyboard.
The default keymap maps keyboard keys to GPIO channel numbers and is defined in default_key_to_channel_map.
-
class
SimulRPi.manager.
DisplayExceptionThread
(*args, **kwargs)[source]¶ Bases:
threading.Thread
A subclass from
threading.Thread
that defines threads that can catch errors if their target functions raise an exception.- Variables
References
-
run
()[source]¶ Method representing the thread’s activity.
Overridden from the base class
threading.Thread
. This method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.It also catches and saves any error that the target function might raise.
Important
The exception is only caught here, not raised. The exception is further raised in
SimulRPi.GPIO.output()
orSimulRPi.GPIO.wait()
. The reason for not raising it here is because the main program won’t catch it. The exception must be raised outside the thread’srun
method so that the thread’s exception can be caught by the main program.The same reasoning applies to the listening thread’s callbacks
Manager.on_press()
andManager.on_release()
.
-
class
SimulRPi.manager.
Manager
[source]¶ Bases:
object
Class that manages the pin database (
SimulRPi.pindb.PinDB
), the threads responsible for displaying “LEDs” in the terminal and listening for pressed/released keys, and the default keymap.The threads are not started right away in
__init__()
but inSimulRPi.GPIO.input()
for the listening thread andSimulRPi.GPIO.output()
for the displaying thread.They are eventually stopped in
SimulRPi.GPIO.cleanup()
.The default keymap maps keyboard keys to GPIO channel numbers and is defined in default_key_to_channel_map.
- Variables
mode (int) – Numbering system used to identify the I/O pins on an RPi: BOARD or BCM. Default value is
None
.warnings (bool) – Whether to show warnings when using a pin other than the default GPIO function (input). Default value is True.
enable_printing (bool) – Whether to enable printing on the terminal. Default value is True.
pin_db (PinDB) – A database of
Pin
s. SeePinDB
on how to access it.default_led_symbols (dict) –
A dictionary that maps each output channel’s state (‘ON’ and ‘OFF’) to a LED symbol. By default, it is set to these LED symbols:
default_led_symbols = { "ON": "🛑", "OFF": "⚪" }
key_to_channel_map (dict) – A dictionary that maps keyboard keys (
string
) to GPIO channel numbers (int
). By default, it takes the keys and values defined in the keymap default_key_to_channel_map.channel_to_key_map (dict) – The reverse dictionary of
key_to_channel_map
. It maps channels to keys.th_display_leds (manager.DisplayExceptionThread) – Thread responsible for displaying blinking red dots in the terminal as to simulate LEDs connected to an RPi.
th_listener (manager.KeyboardExceptionThread) –
Thread responsible for listening on any pressed or released keyboard key as to simulate push buttons connected to an RPi.
If
pynput
couldn’t be imported,th_listener
isNone
. Otherwise, it is instantiated frommanager.KeyboardExceptionThread
.Note
A keyboard listener is a subclass of
threading.Thread
, and all callbacks will be invoked from the thread.Ref.: https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard
Important
If the
pynput.keyboard
module couldn’t be imported, the listening threadth_listener
will not be created and the parts of theSimulRPi
library that monitors the keyboard for any pressed or released key will be ignored. Only the threadth_display_leds
that displays “LEDs” in the terminal will be created.This is necessary for example in the case we are running tests on travis and we don’t want travis to install
pynput
in a headless setup because the following exception will get raised:Xlib.error.DisplayNameError: Bad display name ""
The tests involving
pynput
will be performed with a mock version ofpynput
.-
add_pin
(channel_number, channel_type, pull_up_down=None, initial=None)[source]¶ Add an input or output pin to the pin database.
An instance of
Pin
is created with the given arguments and added to the pin databasePinDB
.- Parameters
channel_number (int) – GPIO channel number associated with the
Pin
to be added in the pin database.channel_type (int) – Type of a GPIO channel: e.g. 1 (GPIO.IN) or 0 (GPIO.OUT).
pull_up_down (int or None, optional) – Initial value of an input channel, e.g. GPIO.PUP_UP. Default value is
None
.initial (int or None, optional) – Initial value of an output channel, e.g. GPIO.HIGH. Default value is
None
.
-
bulk_channel_update
(new_channels_attributes)[source]¶ Update the attributes (e.g. channel_name and led_symbols) for multiple channels.
If a channel number is associated with a not yet created
Pin
, the corresponding attributes will be temporary saved for later when the pin object will be created withadd_pin()
.- Parameters
new_channels_attributes (dict) –
A dictionary mapping channel numbers (
int
) with channels’ attributes (dict
). The accepted attributes are those specified inSimulRPi.GPIO.setchannels()
.Example:
new_channels_attributes = { 1: { 'channel_id': 'channel1', 'channel_name': 'The Channel 1', 'led_symbols': { 'ON': '🔵', 'OFF': '⚪ ' } }. 2: { 'channel_id': 'channel2', 'channel_name': 'The Channel 2', 'key': 'cmd_r' } }
-
display_leds
()[source]¶ Displaying thread’s target function that simulates LEDs connected to an RPi by blinking red dots in a terminal.
Example: terminal output
⬤ [9] ⬤ [10] 🔴 [11]
where each dot represents a LED and the number between brackets is the associated GPIO channel number.
Important
display_leds()
should be run by a thread and eventually stopped from the main program by setting itsdo_run
attribute to False to let the thread exit from its target function.For example:
th = DisplayExceptionThread(target=self.display_leds, args=()) th.start() # Your other code ... # Time to stop thread th.do_run = False th.join()
Note
If
enable_printing
is set to True, the terminal’s cursor will be hidden. It will be eventually shown again inSimulRPi.GPIO.cleanup()
which is called by the main program when it is exiting.The reason is to avoid messing with the display of LEDs done by the displaying thread
th_display_leds
.Note
Since the displaying thread
th_display_leds
is anDisplayExceptionThread
object, it has an attributeexc
which stores the exception raised by this target function.
-
static
get_key_name
(key)[source]¶ Get the name of a keyboard key as a string.
The name of the special or alphanumeric key is given by the pynput package.
- Parameters
key (pynput.keyboard.Key or pynput.keyboard.KeyCode) – The keyboard key (from
pynput.keyboard
) whose name will be returned.- Returns
key_name – Returns the name of the given keyboard key if one was found by pynput. Otherwise, it returns
None
.- Return type
-
on_press
(key)[source]¶ When a valid keyboard key is pressed, set the associated pin’s state to GPIO.LOW.
Callback invoked from the thread
th_listener
.This thread is used to monitor the keyboard for any valid pressed key. Only keys defined in the pin database are treated, i.e. keys that were configured with
SimulRPi.GPIO.setup()
are further processed.Once a valid key is detected as pressed, the associated pin’s state is changed to GPIO.LOW.
- Parameters
key (pynput.keyboard.Key, pynput.keyboard.KeyCode, or None) –
The key parameter passed to callbacks is
a
pynput.keyboard.Key
for special keys,a
pynput.keyboard.KeyCode
for normal alphanumeric keys, orNone
for unknown keys.
Ref.: https://bit.ly/3k4whEs
Note
If an exception is raised, it is caught to be further raised in
SimulRPi.GPIO.input()
orSimulRPi.GPIO.wait()
.See also
DisplayExceptionThread()
Read the Important message that explains why an exception is not raised in a thread’s callback or target function.
-
on_release
(key)[source]¶ When a valid keyboard key is released, set the associated pin’s state to GPIO.HIGH.
Callback invoked from the thread
th_listener
.This thread is used to monitor the keyboard for any valid released key. Only keys defined in the pin database are treated, i.e. keys that were configured with
SimulRPi.GPIO.setup()
are further processed.Once a valid key is detected as released, the associated pin’s state is changed to GPIO.HIGH.
- Parameters
key (pynput.keyboard.Key, pynput.keyboard.KeyCode, or None) –
The key parameter passed to callbacks is
a
pynput.keyboard.Key
for special keys,a
pynput.keyboard.KeyCode
for normal alphanumeric keys, orNone
for unknown keys.
Ref.: https://bit.ly/3k4whEs
Note
If an exception is raised, it is caught to be further raised in
SimulRPi.GPIO.input()
orSimulRPi.GPIO.wait()
.See also
DisplayExceptionThread()
Read the Important message that explains why an exception is not raised in a thread’s callback or target function.
-
update_channel_names
(new_channel_names)[source]¶ Update the channels names for multiple channels.
If a channel number is associated with a not yet created
Pin
, the corresponding channel_name will be temporary saved for later when the pin object will be created withadd_pin()
.
-
update_default_led_symbols
(new_default_led_symbols)[source]¶ Update the default LED symbols used by all output channels.
-
update_keymap
(new_keymap)[source]¶ Update the default dictionary mapping keys and GPIO channels.
new_keymap
is a dictionary mapping some keys to their new GPIO channels, and will be used to update the default keymap default_key_to_channel_map.- Parameters
new_keymap (dict) –
Dictionary that maps keys (
str
) to their new GPIO channels (int
).Example:
new_keymap = { "f": 24, "g": 25, "h": 23 }
- Raises
TypeError – Raised if a given key is invalid: only special and alphanumeric keys recognized by pynput are accepted. See the documentation for
SimulRPi.mapping
for a list of accepted keys.
Note
If the key to be updated is associated to a channel that is already taken by another key, both keys’ channels will be swapped. However, if a key is being linked to a
None
channel, then it will take on the maximum channel number available + 1.
-
update_led_symbols
(new_led_symbols)[source]¶ Update the LED symbols for multiple channels.
If a channel number is associated with a not yet created
Pin
, the corresponding LED symbols will be temporary saved for later when the pin object will be created withadd_pin()
.
-
static
validate_key
(key)[source]¶ Validate if a key is recognized by pynput
A valid key can either be:
a
pynput.keyboard.Key
for special keys (e.g.tab
orup
), ora
pynput.keyboard.KeyCode
for normal alphanumeric keys.
- Parameters
key (str) – The key (e.g. ‘tab’) that will be validated.
- Returns
retval – Returns True if it’s a valid key. Otherwise, it returns False.
- Return type
References
See also
SimulRPi.mapping
for a list of special keys supported by pynput.
SimulRPi.mapping
¶
Module that defines the dictionary that maps keys to GPIO channels.
This module defines the default mapping between keyboard keys and GPIO
channels. It is used by SimulRPi.manager
when monitoring the keyboard
with the package pynput for any pressed/released key as to simulate a push
button connected to a Raspberry Pi.
Notes
In early RPi models, there are 17 GPIO channels and in late RPi models, there are 28 GPIO channels.
By default, 28 GPIO channels (from 0 to 27) are mapped to alphanumeric and special keys. See the content of the default keymap.
Here is the full list of special keys you can use with info about some of them (taken from pynput reference):
alt
alt_gr
alt_l
alt_r
backspace
caps_lock
cmd
: A generic command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key.
cmd_l
: The left command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key.
cmd_r
: The right command button. On PC platforms, this corresponds to the Super key or Windows key, and on Mac it corresponds to the Command key.
ctrl
: A generic Ctrl key.
ctrl_l
ctrl_r
delete
down
end
enter
esc
f1
: The function keys. F1 to F20 are defined.
home
insert
: The Insert key. This may be undefined for some platforms.
left
media_next
media_play_pause
media_previous
media_volume_down
media_volume_mute
media_volume_up
menu
: The Menu key. This may be undefined for some platforms.
num_lock
: The NumLock key. This may be undefined for some platforms.
page_down
page_up
pause
: The Pause/Break key. This may be undefined for some platforms.
print_screen
: The PrintScreen key. This may be undefined for some platforms.
right
scroll_lock
shift
shift_l
shift_r
space
tab
up
References
RPi Header: https://bit.ly/30ZM2Uj
pynput: https://pynput.readthedocs.io/
Important
SimulRPi.GPIO.setkeymap()
allows you to modify the default keymap.
Content of the default keymap dictionary (key: keyboard key as
string
, value: GPIO channel as int
):
default_key_to_channel_map = {
"0": 0, # sudo on mac
"1": 1, # sudo on mac
"2": 2, # sudo on mac
"3": 3, # sudo on mac
"4": 4, # sudo on mac
"5": 5, # sudo on mac
"6": 6, # sudo on mac
"7": 7, # sudo on mac
"8": 8, # sudo on mac
"9": 9, # sudo on mac
"q": 10, # sudo on mac
"alt": 11, # left alt on mac
"alt_l": 12, # not recognized on mac
"alt_r": 13,
"alt_gr": 14,
"cmd": 15, # left cmd on mac
"cmd_l": 16, # not recognized on mac
"cmd_r": 17,
"ctrl": 18, # left ctrl on mac
"ctrl_l": 19, # not recognized on mac
"ctrl_r": 20,
"media_play_pause": 21,
"media_volume_down": 22,
"media_volume_mute": 23,
"media_volume_up": 24,
"shift": 25, # left shift on mac
"shift_l": 26, # not recognized on mac
"shift_r": 27,
}
Important
There are some platform limitations on using some of the keyboard keys with pynput which is used for monitoring the keyboard.
For instance, on macOS, some keyboard keys may require that you run your
script with sudo. All alphanumeric keys and some special keys
(e.g. backspace
and right
) require sudo. In the content of
default_key_to_channel_map shown
previously, I commented those keyboard keys that need sudo on macOS. The
others don’t need sudo on macOS such as cmd_r
and shift
.
For more information about those platform limitations, see pynput documentation.
Warning
If you want to be able to run your python script with sudo in order to use
some keys that require it, you might need to edit /etc/sudoers to add
your PYTHONPATH
if your script makes use of your PYTHONPATH
as
configured in your ~/.bashrc file. However, I don’t recommend editing
/etc/sudoers since you might break your sudo command (e.g.
sudo: /etc/sudoers is owned by uid 501, should be 0
).
Instead, use the keys that don’t requre sudo such as cmd_r
and
shift
on macOS.
Note
On macOS, if the left keys alt_l
, ctrl_l
, cmd_l
, and
shift_l
are not recognized, use their generic counterparts instead:
alt
, ctrl
, cmd
, and shift
.
SimulRPi.pinbdb
¶
Module that defines a database for storing information about GPIO pins.
The database is created as a dictionary mapping channel numbers to objects representing GPIO pins.
The PinDB
class provides an API for accessing this database with
such functions as retrieving or setting pins’ attributes.
-
class
SimulRPi.pindb.
Pin
(channel_number, channel_id, channel_type, channel_name=None, key=None, led_symbols=None, pull_up_down=None, initial=None)[source]¶ Bases:
object
Class that represents a GPIO pin.
- Parameters
channel_number (int) – GPIO channel number based on the numbering system you have specified (BOARD or BCM).
channel_id (str) – Unique identifier.
gpio_type (int) – Type of a GPIO channel: e.g. 1 (GPIO.IN) or 0 (GPIO.OUT).
channel_name (str, optional) – It will be displayed in the terminal along with the LED symbol if it is available. Otherwise, the
channel_number
is shown. By default, its value isNone
.key (str or None, optional) – Keyboard key associated with the GPIO channel, e.g. cmd_r.
led_symbols (dict, optional) –
It should only be defined for output channels. It is a dictionary defining the symbols to be used when the LED is turned ON and OFF. If not found for an ouput channel, then the default LED symbols will be used as specified in
SimulRPi.manager.Manager
.Example:
{ "ON": "🔵", "OFF": "⚪ " }
pull_up_down (int or None, optional) – Initial value of an input channel, e.g. GPIO.PUP_UP. Default value is
None
.initial (int or None, optional) – Initial value of an output channel, e.g. GPIO.HIGH. Default value is
None
.
- Variables
state (int) – State of the GPIO channel: 1 (HIGH) or 0 (LOW).
-
class
SimulRPi.pindb.
PinDB
[source]¶ Bases:
object
Class for storing and modifying
Pin
s.Each instance of
Pin
is saved in a dictionary that maps its channel number to thePin
object.Note
The dictionary (a “database” of
Pin
s) must be accessed through the different methods available inPinDB
, e.g.get_pin_from_channel()
.-
create_pin
(channel_number, channel_id, channel_type, **kwargs)[source]¶ Create an instance of
Pin
and save it in a dictionary.Based on the given arguments, an instance of
Pin
is created and added to a dictionary that acts like a database of pins with the key being the pin’s channel number and the value is an instance ofPin
.- Parameters
channel_number (int) – GPIO channel number based on the numbering system you have specified (BOARD or BCM).
channel_id (str) – Unique identifier.
channel_type (int) – Type of a GPIO channel: e.g. 1 (GPIO.IN) or 0 (GPIO.OUT).
kwargs (dict, optional) – These are the (optional) keyword arguments for
Pin.__init__()
. SeePin
for a list of its parameters which can be included inkwargs
.
- Raises
KeyError – Raised if two channels are using the same channel number.
-
get_pin_state
(channel_number)[source]¶ Get a
Pin
’s state from a given channel.The state associated with a
Pin
can either be 1 (HIGH) or 0 (LOW).
-
set_pin_id_from_channel
(channel_number, channel_id)[source]¶ Set a
Pin
’s channel id from a given channel number.A
Pin
is retrieved based on a given channel, then itschannel_id
is set.- Parameters
- Returns
retval – Returns True if the
Pin
was successfully set with channel_id. Otherwise, it returns False.- Return type
-
set_pin_key_from_channel
(channel_number, key)[source]¶ Set a
Pin
’s key from a given channel.A
Pin
is retrieved based on a given channel, then itskey
is set.
-
set_pin_name_from_channel
(channel_number, channel_name)[source]¶ Set a
Pin
’s channel name from a given channel number.A
Pin
is retrieved based on a given channel, then itschannel_name
is set.- Parameters
- Returns
retval – Returns True if the
Pin
was successfully set with channel_name. Otherwise, it returns False.- Return type
-
set_pin_state_from_channel
(channel_number, state)[source]¶ Set a
Pin
’s state from a given channel.A
Pin
is retrieved based on a given channel, then itsstate
is set.
-
set_pin_state_from_key
(key, state)[source]¶ Set a
Pin
’s state from a given key.A
Pin
is retrieved based on a given key, then itsstate
is set.
-
set_pin_symbols_from_channel
(channel_number, led_symbols)[source]¶ Set a
Pin
’s led symbols from a given channel.A
Pin
is retrieved based on a given key, then itsled_symbols
is set.- Parameters
- Returns
retval – Returns True if the
Pin
was successfully set with led_symbols. Otherwise, it returns False.- Return type
-
SimulRPi.run_examples
¶
Script for executing code examples on a Raspberry Pi or computer (simulation).
This script allows you to run different code examples on your Raspberry Pi (RPi) or computer in which case it will make use of the SimulRPi library which partly fakes RPi.GPIO.
The code examples test different parts of the SimulRPi
library in order to
show what it is capable of simulating from I/O devices connected to an RPi:
Turn on/off LEDs: blink LED symbols in the terminal
Detect pressed button: monitor keyboard with pynput
Usage¶
Once the SimulRPi package is installed, you should have access to
the run_examples
script:
$ run_examples -h
run_examples [-h] [-v] -e EXAMPLE_NUMBER [-m {BOARD,BCM}] [-s]
[-l [LED_CHANNEL [LED_CHANNEL ...]]]
[-b BUTTON_CHANNEL] [-k KEY_NAME]
[-t TOTAL_TIME_BLINKING] [--on TIME_LED_ON]
[--off TIME_LED_OFF] [-a]
Run the code for example 1 on the RPi with default values for the options
-l
(channel 10) and --on
(1 second):
$ run_examples -e 1
Run the code for example 1 on your computer using the simulation module
SimulRPi.GPIO
:
$ run_examples -s -e 1
-
SimulRPi.run_examples.
ex1_turn_on_led
(channel, time_led_on=3)[source]¶ Example 1: Turn ON a LED for some specified time.
A LED will be turned on for
time_led_on
seconds.
-
SimulRPi.run_examples.
ex2_turn_on_many_leds
(channels, time_leds_on=3)[source]¶ Example 2: Turn ON multiple LEDs for some specified time.
All LEDs will be turned on for
time_leds_on
seconds.
Example 3: Detect if a button is pressed.
The function waits for the button to be pressed associated with the given
channel
. As soon as the button is pressed, a message is printed and the function exits.- Parameters
channel (int) – Input channel number based on the numbering system you have specified (BOARD or BCM).
Note
If the simulation mode is enabled (
-s
), the specified keyboard key will be detected if pressed. The keyboard key can be specified through the command line option-b
(button channel) or-k
(the key name, e.g. ‘ctrl’). See script’s usage.
-
SimulRPi.run_examples.
ex4_blink_led
(channel, total_time_blinking=4, time_led_on=0.5, time_led_off=0.5)[source]¶ Example 4: Blink a LED for some specified time.
The led will blink for a total of
total_time_blinking
seconds. The LED will stay turned on fortime_led_on
seconds before turning off fortime_led_off
seconds, and so on untiltotal_time_blinking
seconds elapse.Press
ctrl
+c
to stop the blinking completely and exit from the function.- Parameters
channel (int) – Output channel number based on the numbering system you have specified (BOARD or BCM).
total_time_blinking (float, optional) – Total time in seconds the LED will be blinking. The default value is 4 seconds.
time_led_on (float, optional) – Time in seconds the LED will stay turned ON at a time. The default value is 0.5 second.
time_led_off (float, optional) – Time in seconds the LED will stay turned OFF at a time. The default value is 0.5 second.
Example 5: If a button is pressed, blink a LED for some specified time.
As soon as the button from the given
button_channel
is pressed, the LED will blink for a total oftotal_time_blinking
seconds.The LED will stay turned on for
time_led_on
seconds before turning off fortime_led_off
seconds, and so on untiltotal_time_blinking
seconds elapse.Press
ctrl
+c
to stop the blinking completely and exit from the function.- Parameters
led_channel (int) – Output channel number based on the numbering system you have specified (BOARD or BCM).
button_channel (int) – Input channel number based on the numbering system you have specified (BOARD or BCM).
total_time_blinking (float, optional) – Total time in seconds the LED will be blinking. The default value is 4 seconds.
time_led_on (float, optional) – Time in seconds the LED will stay turned ON at a time. The default value is 0.5 second.
time_led_off (float, optional) – Time in seconds the LED will stay turned OFF at a time. The default value is 0.5 second.
Note
If the simulation mode is enabled (
-s
), the specified keyboard key will be detected if pressed. The keyboard key can be specified through the command line option-b
(button channel) or-k
(the key name, e.g. ‘ctrl’). See script’s usage.
-
SimulRPi.run_examples.
main
()[source]¶ Main entry-point to the script.
According to the user’s choice of action, the script might run one of the specified code examples.
If the simulation flag (-s) is used, then the SimulRPi.GPIO module will be used which partly fakes RPi.GPIO.
Notes
Only one action at a time can be performed.
-
SimulRPi.run_examples.
setup_argparser
()[source]¶ Setup the argument parser for the command-line script.
The script allows you to run a code example on your RPi or on your computer. In the latter case, it will make use of the SimulRPi.GPIO module which partly fakes RPi.GPIO.
- Returns
args – Simple class used by default by
parse_args()
to create an object holding attributes and return it 1.- Return type
References
SimulRPi.utils
¶
Collection of utility functions used for the SimulRPi library.
-
SimulRPi.utils.
blink_led
(channel, time_led_on, time_led_off)[source]¶ Blink LEDs from the given channels.
LEDs on the given
channel
will be turned ON and OFF fortime_led_on
seconds andtime_led_off
seconds, respectively.