API Reference¶
darth_vader_rpi.start_dv¶
Script to turn on LEDs and play sound effects on a Raspberry Pi (RPi).
The LEDs illuminate a Darth Vader action figure’s lightsaber and the three slots in the chest control box. 3 push buttons control the following sounds and LEDs:
Some of his famous quotes
The Imperial march theme song
The lightsaber drawing, hum and retraction sounds
The lightsaber illumination (3 LEDs)
His iconic breathing sound plays in the background indefinitely almost as soon as the RPi is run with the script.
The script allows you also to edit the main config file to setup among other things the RPi’s GPIO pins connected to LEDs and push buttons.
By default the RPi.GPIO module is used, but if the simulation option (-s)
is used with the start_dv script, then the SimulRPi.GPIO module will
be used instead which simulates RPi.GPIO for those that don’t have an RPi to
test on.
Usage¶
Once the darth_vader_rpi package is installed, you should have access to
the start_dv script:
start_dv [-h] [--version] [-q] [-s] [-v] [-e {log,main}] [-a APP]
Run the script on the RPi with default values for the GPIO channels and other settings:
$ start_dv
Run the script on your computer using SimulRPi.GPIO which simulates
RPi.GPIO:
$ start_dv -s
Edit the main config file with TextEdit (e.g. on macOS):
$ start_dv -e main -a TextEdit
Edit the logging config file with a default application (e.g. atom):
$ start_dv -e log
Notes
More information is available at:
Note
In darth_vader, ledutils, and start_dv, the default
value for GPIO is None and will be eventually set to one of the
two modules (RPi.GPIO or SimulRPi.GPIO) depending on the user’s
settings.
RPi.GPIO provides a class to control the GPIO pins on a Raspberry Pi.
If the simulation option (-s) is used with the start_dv script,
the SimulRPi.GPIO module will be used instead.
-
start_dv.edit_config(cfg_type, app=None)[source]¶ Edit a configuration file.
The user chooses what type of config file (cfg_type) to edit: ‘log’ for the logging config file and ‘main’ for the main config file.
The configuration file can be opened by a user-specified application (app) or a default program associated with this type of file (when app is
None).- Parameters
cfg_type (str, {'log', 'main'}) – The type of configuration file we want to edit. ‘log’ refers to the logging config file, and ‘main’ to the main config file used to setup the Darth-Vader-RPi project such as specifying the sound effects or the GPIO channels.
app (str, optional) – Name of the application to use for opening the config file, e.g. TextEdit (the default value is
Nonewhich implies that the default application will be used to open the config file).
- Returns
retcode – If there is a subprocess -related error, the return code is non-zero. Otherwise, it is 0 if the file can be successfully opened with an external program.
- Return type
-
start_dv.main()[source]¶ Main entry-point to the script.
According to the user’s choice of action, the script might:
activate a Darth Vader figurine (turn on LEDs and play sound effects)
edit a configuration file
- Raises
ValueError – Raised if an invalid configuration name is given to the command-line argument edit.
Notes
Only one action at a time can be performed.
darth_vader_rpi.darth_vader¶
Module for activating a Darth Vader figurine by turning on LEDs on his suit and playing sounds, all done via a Raspberry Pi (RPi).
The LEDs illuminate Darth Vader’s lightsaber and the three slots in the chest control box. 3 push buttons control the following sounds and LEDs:
Some of his famous quotes
The Imperial march theme song
The lightsaber drawing, hum and retraction sounds
The lightsaber illumination (3 LEDs)
His iconic breathing sound plays in the background indefinitely almost as soon as the RPi is run with the script.
-
class
darth_vader.DarthVader(main_cfg)[source]¶ Bases:
objectClass for activating a Darth Vader figurine by turning on LEDs on his suit and playing sounds, all done via a Raspberry Pi (RPi).
The main config file is used to setup the
start_dvscript, such as the GPIO pins and the sound files.- Parameters
main_cfg (dict) – Dictionary containing the configuration data to setup the
start_dvscript, such as the GPIO pins and the sound files. See main config file for a detailed look into its content.- Variables
th_slot_leds (start_dv.ExceptionThread) –
Thread responsible for turning on the three slot LEDs in a precise sequence.
Its target function is
ledutils.turn_on_slot_leds().
-
activate()[source]¶ Activate a Darth Vader figurine by turning on LEDs on his suit and playing sounds, all done via an RPi.
While the method waits for a pressed button, you can exit by pressing
ctr+c.
-
cleanup(gpio_channels)[source]¶ Clean up any resources such as threads and GPIO channels.
The cleanup consists in the following actions:
turn off each LED
stop the thread
th_slot_ledsstop each audio channel
call
RPi.GPIO.cleanup()which will return all GPIO channels back to inputs with no pull up/downIf in simulation mode,
SimulRPi.GPIO.cleanupis called to stop the threads among other things
- Parameters
gpio_channels (dict) –
Dictionary mapping channel id (
str) to channel attributes (dict). The channel attributes consist in the following:channel_numberchannel_namekeyled_symbols
Note
These channel attributes are those found in the setting gpio_channels from the main configuration file.
-
class
darth_vader.ExceptionThread(verbose=False, *args, **kwargs)[source]¶ Bases:
threading.ThreadA subclass from
threading.Threadthat defines threads that can catch errors if their target functions raise an exception.- Parameters
verbose (bool, optional) – If True, print the traceback when there is an exception. Otherwise, print just a one-line error message, e.g.
KeyError: 'test'args (tuple, optional) – Positional arguments given to the thread’s target function.
kwargs (dict, optional) – Keyword arguments given to the thread’s target function.
- Variables
exc (
Exception) – Represents the exception raised by the target function.
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 saves and logs any error that the target function might raise.
darth_vader_rpi.ledutils¶
Collection of LEDs-related utilities for the Darth-Vader-RPi project.
-
ledutils.turn_off_led(channel)[source]¶ Turn off a LED from a given channel.
- Parameters
channel (int) – Channel number associated with a LED which will be turned off.
-
ledutils.turn_on_led(channel)[source]¶ Turn on a LED from a given channel.
- Parameters
channel (int) – Channel number associated with a LED which will be turned on.
-
ledutils.turn_on_slot_leds(top_led, middle_led, bottom_led, leds_sequence='action', delay_between_steps=0.5, time_per_step=0.5)[source]¶ A thread’s target function that turn on/off the three slot LEDs in a precise sequence.
These three LEDs are associated with Darth Vader’s three slots located on his chest control box. These LEDs are labeled as ‘top’, ‘middle’, and ‘bottom’, respectively.
The three LEDs are turned on according to a default or custom sequence which repeats itself. The accepted values for
leds_sequenceare ‘action’ and ‘calm’ which represent Darth Vader’s physiological state as a sequence of LEDs blinking in a particular order.The user can also provide its own
leds_sequenceby using a list of LED labels {‘top’, ‘midddle’, ‘bottom’} arranged in a sequence specifying the order the slot LEDs should turn on/off, e.g.[['top', 'bottom'], [], ['middle'], []]will turn on/off the slot LEDs in this order:1. top + bottom LEDs turned on 2. All LEDs turned off 3. middle LED turned on 4. All LEDs turned off
Each step in the sequence will last for
time_per_stepseconds.There will be a delay of
delay_between_stepsseconds between each step in the previous example.The default sequences of slot LEDs were obtained from this YouTube video.
- Parameters
top_led (int) – Channel number associated with the Top slot LED.
middle_led (int) – Channel number associated with the Middle slot LED.
bottom_led (int) – Channel number associated with the Bottom slot LED.
leds_sequence (str or list, optional) –
Sequence of slot LEDs on Darth Vader’s chest box.
If
leds_sequenceis a string, then it takes on one of these values which represent Darth Vader’s physiological state: {‘action’, ‘calm’}.If
leds_sequenceis a list, then it must be a list of slot LED labels {‘top’, ‘middle’, ‘bottom’} arranged in a sequence as to specify the order the slot LEDs should turn on/off, e.g.[['top', 'bottom'], [], ['middle'], []]will turn on/off the slot LEDs in this order:1. top + bottom LEDs turn on 2. All LEDs turn off 3. middle LED turn on 4. All LEDs turn off
delay_between_steps (float, optional) – Delay in seconds between each step in the sequence. The default value is 0.5 second.
time_per_step (float, optional) –
Time in seconds each step in the sequence will last. The default value is 0.5 second.
Important
This also affects the time all LEDs will remain turned off if a step in
leds_sequenceis an empty list.
Important
turn_on_slot_leds()should be run by a thread and eventually stopped from the main program by setting itsdo_runattribute to False to let the thread exit from its target function.For example:
th = threading.Thread(target=turn_on_slot_leds, args=(leds_channels)) th.start() # Your other code ... # Time to stop thread th.do_run = False th.join()
darth_vader_rpi.utils¶
Collection of utilities for the Darth-Vader-RPi project.
-
class
utils.SoundWrapper(sound_id, sound_name, sound_filepath, channel_id, mute=False)[source]¶ Bases:
objectClass that wraps around
pygame.mixer.Channelandpygame.mixer.Sound.The
__init__method takes care of automatically loading the sound file. The sound file can then be played or stopped from the specified channelchannel_idwith theplay()orstop()method, respectively.- Parameters
sound_id (str) – A unique identifier.
sound_name (str) – Name of the sound file that will be displayed in the terminal.
sound_filepath (str) – Path to the sound file.
channel_id (int) – Channel id associated with an instance of
pygame.mixer.Channelfor controlling playback. It must take anintvalue starting from 0.mute (bool, optional) – If set to True, the sound will not be played. The default value is False.
Note
It is a wrapper with a very minimal interface to
pygame.mixer.Channelwhere only two methodsplay()andstop()are provided for the sake of the project.-
play(loops=0)[source]¶ Play a sound on the specified Channel
channel_id.- Parameters
loops (int) –
Controls how many times the sample will be repeated after being played the first time. The default value (zero) means the sound is not repeated, and so is only played once. If
loopsis set to -1 the sound will loop indefinitely (though you can still callstop()to stop it).Reference:
pygame.mixer.Sound.play()
-
utils.dumps_json(filepath, data, encoding='utf8', ensure_ascii=False, indent=None, sort_keys=False)[source]¶ Write data to a JSON file.
The data is first serialized to a JSON formatted string and then saved to disk.
- Parameters
filepath (str) – Path to the JSON file where the data will be saved.
data – Data to be written to the JSON file.
encoding (str, optional) – Encoding to be used for opening the JSON file in write mode (the default value is ‘utf8’).
ensure_ascii (bool, optional) – If
ensure_asciiis False, then the return value can contain non-ASCII characters if they appear in strings contained indata. Otherwise, all such characters are escaped in JSON strings. See thejson.dumpsdocstring description (the default value is False).indent (int or None, optional) – If
indentis a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines.Noneis the most compact representation. See thejson.dumps()docstring description. (the default value isNone).sort_keys (bool, optional) – If
sort_keysis True, then the output of dictionaries will be sorted by key. See thejson.dumpsdocstring description. (the default value is False).
- Raises
OSError – Raised if any I/O related error occurs while writing the data to disk, e.g. the file doesn’t exist.
-
utils.get_cfg_dirpath()[source]¶ Get the path to the directory containing the config files.
- Returns
dirpath – The path to the directory containing the config files.
- Return type
-
utils.get_cfg_filepath(file_type)[source]¶ Get the path to a config file used by the script
start_dv.file_typeaccepts the following values:default_log: refers to the default logging configuration file used to setup the logging for all custom modules.
default_main: refers to the default main configuration file used to setup the script
start_dv.log: refers to the user-defined logging configuration file which is used to setup the logging for all custom modules.
main: refers to the user-defined main configuration file used to setup the script
start_dv.
- Parameters
file_type (str, {‘default_log’, ‘default_main’, ‘log’, ‘main’}) – The type of config file for which we want the path.
- Returns
filepath – The path to the config file.
- Return type
- Raises
AssertionError – Raised if the wrong type of config file is given to the function. Only {‘default_log’, ‘default_main’, ‘log’, ‘main’} are accepted for
file_type.
-
utils.load_json(filepath, encoding='utf8')[source]¶ Load JSON data from a file on disk.
If using Python version betwee 3.0 and 3.6 (inclusive), the data is returned as
collections.OrderedDict. Otherwise, the data is returned asdict.- Parameters
- Returns
data – Data loaded from the JSON file.
- Return type
- Raises
OSError – Raised if any I/O related error occurs while reading the file, e.g. the file doesn’t exist.
References
-
utils.override_config_with_args(config, parser)[source]¶ Override a config dictionary with arguments from the command-line.
- Parameters
config (dict) – Dictionary containing configuration options.
parser (argparse.ArgumentParser) – Argument parser.
- Returns
retval – Contains two lists:
1. args_not_found: saves command-line arguments not found in the config dictionary
2. config_opts_overridden: saves config options overridden by command-line arguments as a three-tuple (option name, old value, new value)
- Return type
-
utils.run_cmd(cmd)[source]¶ Run a shell command with arguments.
The shell command is given as a string but the function will split it in order to get a list having the name of the command and its arguments as items.
- Parameters
cmd (str) –
Command to be executed, e.g.
open -a TextEdit text.txt
- Returns
retcode – Returns code which is 0 if the command was successfully completed. Otherwise, the return code is non-zero.
- Return type
- Raises
FileNotFoundError – Raised if the command
cmdis not recognized, e.g.$ TextEdit {filepath}since TextEdit is not an executable.