Build a Pi Extension with Jev Hooks: Safety & Tests
In this article
This guide walks through building a Raspberry Pi extension that uses Jev Hooks for lifecycle management, with a strong focus on safety and real session testing. You'll end up with a reusable, testable extension that can safely handle interrupts, GPIO, and session state.
What You'll Need
- A Raspberry Pi (any model with GPIO pins, e.g., Pi 4 or Zero 2 W) running Raspberry Pi OS (Bookworm or later)
- Python 3.9+ installed
- Jev Hooks library installed (
pip install jev-hooks) - Basic familiarity with Python, GPIO, and terminal commands
- Optional: breadboard, LEDs, resistors for physical testing
Step-by-Step
- Set up your project structure. Create a directory for your extension, e.g.,
pi_ext/, with subfolders:hooks/,tests/, andsrc/. This keeps hooks, code, and tests separate. - Install Jev Hooks. In a virtual environment, run
pip install jev-hooks. Verify withpython -c "import jev_hooks; print(jev_hooks.__version__)". - Define your hook points. In
src/hooks.py, create a class that inherits fromjev_hooks.HookRegistry. Define hook names likebefore_session_start,after_session_end,on_gpio_change. These will be called at specific points in your extension's lifecycle. - Implement safety checks in hooks. In each hook, add validation. For example, in
before_session_start, check that GPIO pins are not already in use, and that the session ID is unique. Usetry/exceptto catch errors and log them. - Create the main extension class. In
src/extension.py, define a class that uses the hook registry. It should have methods likestart_session()andstop_session()that call the hooks at the right time. - Add GPIO handling with safety. Use
RPi.GPIOorgpiozero. Set up pins with pull-up/pull-down resistors, and use software debouncing. In the GPIO callback, call theon_gpio_changehook with the pin number and value. - Write real session tests. In
tests/test_session.py, useunittestorpytest. Create a test that starts a session, simulates GPIO events (by directly calling the callback), and verifies that hooks fire in the correct order and that state changes are logged. - Run tests with a mock GPIO. To test without physical hardware, use
unittest.mockto patch the GPIO library. This lets you simulate pin reads and writes. For real hardware tests, run the tests withsudo(if needed) and a physical setup. - Add a safety timeout. In your session class, add a watchdog timer that automatically ends the session if no activity occurs for a set period. This prevents hangs.
- Document your hooks. Write a README that lists each hook, when it's called, and what parameters it receives. This is crucial for other developers.
Common Mistakes
- Not cleaning up GPIO. Always call
GPIO.cleanup()in afinallyblock, otherwise pins stay in use and can cause issues on reboot. - Ignoring exceptions in hooks. If a hook raises an unhandled exception, it can crash the entire extension. Always catch and log exceptions within hooks.
- Testing without mocking. Running tests on real hardware without mocking can be flaky and dangerous (e.g., accidentally shorting pins).
- Not using debouncing. Without debouncing, a single button press can trigger multiple GPIO events, causing multiple hook calls.
- Forgetting to set pin modes. Always set each pin as INPUT or OUTPUT before using it.
Tips
- Use a virtual environment. This isolates your dependencies and prevents conflicts.
- Log everything. Use Python's
loggingmodule to record hook calls, errors, and session state changes. This is invaluable for debugging. - Design hooks to be idempotent. If a hook is called twice, it should not cause issues. For example,
after_session_endshould be safe to call multiple times. - Write tests before the implementation. This forces you to think about the hook interface first, making the code cleaner.
- Use type hints. They make the code more readable and help catch errors early.
Troubleshooting
- Hooks not firing: Check that the hook names match exactly between the registry and the calls. Also, ensure that the extension class is actually using the registry instance.
- GPIO errors: If you get "GPIO already in use", make sure you call
GPIO.cleanup()in a previous run, or reboot the Pi. Also, check that you're using the correct pin numbering (BOARD vs BCM). - Tests fail on real hardware: Run the tests with
sudoif you're accessing GPIO. Also, verify that the wiring is correct and that no pins are shorted. - Session hangs: If the session doesn't end, check that the watchdog timer is properly started and that the timeout value is reasonable. Also, ensure that the
stop_session()method is called in afinallyblock. - Import errors: Make sure your
srcfolder is a package (has an__init__.pyfile) and that you're running tests from the project root.
Frequently Asked Questions
What exactly is a Jev Hook?
A Jev Hook is a callback function that you register with a hook registry. Your extension calls these hooks at specific points, allowing other code to react without modifying the core logic.
How do I test hooks without real hardware?
Use unittest.mock to patch the GPIO library. You can then simulate pin reads and writes, and verify that your hooks receive the expected arguments.
Can I use this with other Pi models?
Yes, the code is compatible with any Raspberry Pi that runs Raspberry Pi OS and has GPIO pins. Just ensure you have the correct pin mapping.
What is a real session test?
A real session test runs the full extension with actual (or mocked) GPIO events, verifying that the session starts, hooks fire, and the session ends correctly. It's more realistic than unit tests that only test individual functions.
How do I add a new hook?
Add a new method to your hook registry class, then call it from your extension code at the appropriate point. Remember to update the documentation and tests.
Is it safe to run hooks in a different thread?
Yes, but you need to be careful with shared state. Use locks or queues to avoid race conditions. Jev Hooks does not manage threading for you.