Skip to main content

pydartsnut

Python module for interfacing with Dartsnut hardware. Provides dart position tracking, button state monitoring, display control, and event-based input handling.

Installation

pip install pydartsnut

Requirements

  • Python >= 3.1
  • PIL/Pillow (for image handling, optional)

Usage

Initialize the module

from pydartsnut import Dartsnut

dartsnut = Dartsnut()

The Dartsnut class accepts command-line arguments:

  • --params: JSON string for widget parameters (default: "{}")
  • --shm: Shared memory name for display (default: "pdishm")
  • --data-store: Path to data store directory (defaults to script directory)

Example:

# When running from command line:
# python your_script.py --params '{"city": "New York"}' --shm pdishm --data-store /path/to/data

Retrieve user input parameters

params = dartsnut.widget_params
# Returns a dictionary of current widget parameters.
print(params)

# Safely get the city name from params
city_name = ""
if params is not None:
    city_name = params.get("city", "")
if city_name == "":
    # TODO: assign default value or show a warning image
    pass

Update the frame buffer for display

from PIL import Image

# Using a PIL Image
image = Image.open("your_image.png")
dartsnut.update_frame_buffer(image)

# Or using a bytearray (RGB888 format)
dartsnut.update_frame_buffer(bytearray_data)

The update_frame_buffer() method returns True if the frame was successfully updated, False if the display buffer is busy or in an invalid state.

Get dart positions (polling)

darts = dartsnut.get_darts()
# Returns a list of 12 [x, y] coordinates.
# [-1, -1] means the dart is not present.
# Coordinates are in range 0-127 for both x and y.

Get dart hits (event-based)

dart_hits = dartsnut.get_dart_hits()
# Returns a list of tuples (dart_index, x, y) for new dart hits.
# Only registers hits when a dart transitions from invalid to valid position.
# Each dart index is blocked after detection to prevent duplicate events.
# Darts are automatically unblocked after 0.5 seconds of invalid state.

for dart_index, x, y in dart_hits:
    print(f"Dart {dart_index} hit at ({x}, {y})")

Get active darts (all current darts)

active_darts = dartsnut.get_active_darts()
# Returns a list of tuples (dart_index, x, y) for ALL active darts.
# Useful for continuous tracking regardless of blocking state.

for dart_index, x, y in active_darts:
    print(f"Dart {dart_index} is at ({x}, {y})")

Reset dart blocking state

dartsnut.reset_blocking_state()
# Clears all blocked dart indices, allowing all darts to be eligible for event detection again.

Get button states (polling)

buttons = dartsnut.get_buttons()
# Returns a dictionary with current button states (with 30ms debouncing):
# {
#     "btn_a": False,
#     "btn_b": False,
#     "btn_up": False,
#     "btn_right": False,
#     "btn_left": False,
#     "btn_down": False,
#     "btn_home": False,
#     "btn_reserved": False,
# }

Get button events (event-based)

button_events = dartsnut.get_button_events()
# Returns a dictionary where buttons are True only on press (transition from False to True).
# This provides event-based button detection rather than continuous state polling.

if button_events["btn_a"]:
    print("Button A was just pressed!")

Set display brightness

dartsnut.set_brightness(50)  # Brightness level between 10 and 100

Data persistence

The module provides methods to store and retrieve data in a JSON file:

# Store a value
dartsnut.set_value("player_name", "John Doe")
dartsnut.set_value("high_score", 180)
dartsnut.set_value("settings", {"theme": "dark", "sound": True})

# Retrieve a value
player_name = dartsnut.get_value("player_name", "Unknown")
high_score = dartsnut.get_value("high_score", 0)
settings = dartsnut.get_value("settings", {})

Data is stored atomically to prevent corruption during writes. The default storage location is the script directory, but can be customized with the --data-store argument.

Running state management

# Check if the application should continue running
while dartsnut.running:
    # Your main loop
    dart_hits = dartsnut.get_dart_hits()
    # ... process events ...
    
# The running flag is automatically set to False on SIGINT (Ctrl+C)

Complete Example

from pydartsnut import Dartsnut
from PIL import Image, ImageDraw

dartsnut = Dartsnut()

# Create a simple image
img = Image.new('RGB', (128, 128), color='black')
draw = ImageDraw.Draw(img)

while dartsnut.running:
    # Check for dart hits
    dart_hits = dartsnut.get_dart_hits()
    for dart_index, x, y in dart_hits:
        print(f"Dart {dart_index} hit at ({x}, {y})")
        # Draw a circle at the hit position
        draw.ellipse([x-2, y-2, x+2, y+2], fill='red')
    
    # Check for button presses
    button_events = dartsnut.get_button_events()
    if button_events["btn_a"]:
        print("Button A pressed!")
        # Clear the image
        img = Image.new('RGB', (128, 128), color='black')
        draw = ImageDraw.Draw(img)
    
    # Update display
    dartsnut.update_frame_buffer(img)
    
    # Small delay to prevent excessive CPU usage
    import time
    time.sleep(0.01)

API Reference

Dartsnut Class

Attributes

  • running: Boolean flag indicating if the application should continue running
  • widget_params: Dictionary of widget parameters parsed from command line

Methods

  • update_frame_buffer(frame): Update display frame buffer (returns bool)
  • get_darts(): Get current dart positions (returns list of 12 [x, y] coordinates)
  • get_dart_hits(): Get new dart hits as events (returns list of (dart_index, x, y) tuples)
  • get_active_darts(): Get all currently active darts (returns list of (dart_index, x, y) tuples)
  • reset_blocking_state(): Reset dart blocking state
  • get_buttons(): Get current button states with debouncing (returns dict)
  • get_button_events(): Get button press events (returns dict)
  • get_controllers(): Get stable handles for up to four connected controllers

Multiple controllers and analog axes

controllers = dartsnut.get_controllers()
for controller in controllers:
    if controller.get_button_events()["btn_a"]:
        print(controller.id, controller.get_controller_axes())

Each handle exposes independent button levels, press edges, and left-stick x/y values normalized to [-1.0, 1.0]. The opaque id remains stable when Linux can recover the physical controller identity. Existing get_buttons() and get_button_events() merge all controllers for older games. Controller HOME is reserved by firmware and hidden from Python games by default.

DARTSNUT_CONTROLLER_MODE selects auto (default), broker, direct, or off. Production firmware uses the shared-memory broker; direct is intended for emulator and development use.

  • set_brightness(brightness): Set display brightness (10-100)
  • set_value(key, value): Store a value in the data store
  • get_value(key, default=None): Retrieve a value from the data store

License

See the project repository for license information.

Metadata

Release files for pydartsnut 1.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydartsnut 1.4.0
File Size Uploaded Provenance Actions
pydartsnut-1.4.0.tar.gz 24.2 kB Without provenance Details for pydartsnut-1.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pydartsnut 1.4.0
File Interpreter ABI Platform Actions
pydartsnut-1.4.0-py3-none-any.whl Python 3 none any Details for pydartsnut-1.4.0-py3-none-any.whl

Total release size: 45.5 kB

Release files / pydartsnut-1.4.0.tar.gz

Download URL pydartsnut-1.4.0.tar.gz
Size 24.2 kB
Tags Source
SHA-256 checksum
How to use checksums
185e33731d0c2e9662fbac73616545b5aa01e71be196b1770a1b9c47b631b0b3
BLAKE2b-256 checksum
How to use checksums
a88ef120688a17945a81d25eada1f07ddf827f477bdf712e14a130a1e827412f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.10 {"installer":{"name":"uv","version":"0.12.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / pydartsnut-1.4.0-py3-none-any.whl

Download URL pydartsnut-1.4.0-py3-none-any.whl
Size 21.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9afcb94de95fdbf517316f19ec16e7f440f102000c38c7d0fbdb9c4b68fa8e49
BLAKE2b-256 checksum
How to use checksums
649f0ef8aa9472ec10bda990e7addbcf798fc05ca51a299b2bbae0bb566ea61e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.12.10 {"installer":{"name":"uv","version":"0.12.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for pydartsnut 1.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page