Skip to main content

Python client library for the PetTracer GPS pet collar portal

Project description

PetTracer API Client

PyPI version Python License: MIT Status

Async Python client library for the PetTracer GPS pet collar portal. Provides a clean, object-oriented interface for managing devices, tracking positions, and accessing user information.

Note: This is an unofficial API derived from the petTracer web site. Use with caution and respect for their service. You need to own a pet collar, have an account and paid subscription for this client to be useful.

Features

  • Async/await support - Non-blocking I/O (version 0.2.0)
  • 🎯 Object-oriented design - Clean class hierarchy for intuitive API usage
  • 🔐 Automatic authentication - Login once, use everywhere
  • 📍 Position tracking - Fetch device locations with time-range filtering
  • 👤 User management - Access profile and subscription information
  • 🐾 Device management - Control and monitor multiple pet collars
  • 📊 Typed data models - Full dataclass support for all responses
  • Well tested - Comprehensive test suite included

Installation

Install from PyPI:

pip install pettracer-client

Or install the required dependencies for development:

pip install aiohttp

For development:

pip install -r requirements-dev.txt

Quick Start

import asyncio
from pettracer import PetTracerClient

async def main():
    # Create client and authenticate
    async with PetTracerClient() as client:
        await client.login("your_username", "your_password")
        
        # Access user information (cached from login)
        print(f"Welcome, {client.user_name}!")
        print(f"You have {client.device_count} device(s)")
        print(f"Subscription expires: {client.subscription_expires}")
        
        # Get all devices
        devices = await client.get_all_devices()
        for device in devices:
            print(f"{device.details.name}: Battery {device.bat}mV")
        
        # Work with a specific device
        pet_device = client.get_device(devices[0].id)
        positions = await pet_device.get_positions(
            filter_time=1767152926491,  # Unix timestamp in milliseconds
            to_time=1767174526491
        )

asyncio.run(main())

For complete examples, see:

Home Assistant Integration

The client is designed to work seamlessly with Home Assistant:

from homeassistant.helpers.aiohttp_client import async_get_clientsession
from pettracer import PetTracerClient

async def async_setup_entry(hass, entry):
    # Pass in Home Assistant's aiohttp session
    session = async_get_clientsession(hass)
    client = PetTracerClient(session=session)
    
    await client.login(
        entry.data["username"],
        entry.data["password"]
    )
    
    # Use the client...
    # Note: Don't call client.close() - HA manages the session

Architecture

The library uses a two-tier class architecture:

Client Hierarchy

PetTracerClient (user-level operations)
    ├── Authentication & session management
    ├── User profile & subscription info
    └── Device discovery
         └── PetTracerDevice (device-specific operations)
              ├── Device information
              └── Position history

Key Classes

PetTracerClient

The main entry point for all API operations. Manages authentication and provides access to user-level functionality.

Initialization:

import asyncio
from pettracer import PetTracerClient

# Option 1: Context manager (recommended)
async with PetTracerClient() as client:
    await client.login(username, password)
    # Use client...

# Option 2: Manual session management
client = PetTracerClient()
await client.login(username, password)
# ... use client ...
await client.close()  # Clean up

# Option 3: Pass in existing aiohttp session (e.g., from Home Assistant)
import aiohttp
async with aiohttp.ClientSession() as session:
    client = PetTracerClient(session=session)
    await client.login(username, password)
    # Don't call close() - you manage the session

Core Methods (all async):

  • await login(username, password) - Authenticate and store credentials
  • await get_all_devices() - Retrieve all devices owned by the user
  • get_device(device_id) - Get a device-specific client (not async)
  • await get_user_profile() - Fetch detailed user profile (updates cached data)
  • await close() - Close the session if owned by this client

Authentication:

  • is_authenticated - Check if logged in
  • token - Current bearer token
  • token_expires - Token expiration datetime
  • session - aiohttp ClientSession object

User Information (available after login):

  • user_id, user_name, email
  • partner_id, language
  • country, country_id
  • device_count - Number of devices

Subscription:

  • subscription_id - Subscription identifier
  • subscription_expires - Expiration date
  • subscription_info - Full SubscriptionInfo object

Raw Data:

  • login_info - Complete LoginInfo dataclass with all login response data

PetTracerDevice

Represents a single pet tracker device. Created via client.get_device(device_id).

Methods (all async):

  • await get_info() - Fetch current device information
  • await get_positions(filter_time, to_time) - Get position history within time range

Properties:

  • device_id - The device identifier

Time Parameters: Position history methods use Unix timestamps in milliseconds:

from datetime import datetime, timedelta

now = datetime.now()
yesterday = now - timedelta(days=1)

positions = await device.get_positions(
    filter_time=int(yesterday.timestamp() * 1000),
    to_time=int(now.timestamp() * 1000)
)

Data Models

All API responses are parsed into typed dataclasses for easy access and IDE autocomplete support.

Core Types

Device - Complete device information:

  • id, bat (battery), status, mode
  • details - Details object with name, image, birth date
  • lastPos - LastPos object with most recent position
  • masterHs - Master home station information
  • lastContact, homeSince - Timestamps
  • Many more fields for device state

LastPos - Position data:

  • posLat, posLong - Coordinates
  • timeMeasure, timeDb - Timestamps
  • sat - Satellite count
  • rssi - Signal strength
  • fixS, fixP, horiPrec - GPS quality metrics
  • acc - Accuracy
  • flags - Status flags

Details - Device/pet details:

  • name - Pet name
  • birth - Birth date
  • image, img - Image references
  • color - Color code

UserProfile - User account information:

  • id, email, name
  • street, street2, zip, city
  • mobile, lang, country_id
  • Additional profile fields

LoginInfo - Complete login response data:

  • User identification and account details
  • Authentication tokens and expiration
  • Subscription information via abo field
  • Settings and preferences

SubscriptionInfo - Subscription details:

  • id, userId, odooId
  • dateExpires - Expiration date
  • paypalSubscriptionId
  • Raw subscription dict

Working with Data

# Device information
device = devices[0]
print(f"Pet: {device.details.name}")
print(f"Battery: {device.bat}mV")
print(f"Last seen: {device.lastContact}")

if device.lastPos:
    print(f"Location: {device.lastPos.posLat}, {device.lastPos.posLong}")
    print(f"Satellites: {device.lastPos.sat}")
    print(f"Time: {device.lastPos.timeMeasure}")

# Position history
for pos in positions:
    print(f"{pos.timeMeasure}: ({pos.posLat}, {pos.posLong})")
    print(f"  Accuracy: {pos.acc}m, Satellites: {pos.sat}")

# User profile
profile = client.get_user_profile()
print(f"{profile.name} - {profile.email}")
print(f"{profile.city}, {profile.zip}")

Example Application

See examples/class_based_example.py for a complete working example that demonstrates:

  • Client initialization and login
  • Accessing user information and subscription details
  • Fetching and displaying all devices
  • Working with device-specific clients
  • Retrieving position history with time ranges
  • Error handling and data validation

Run the example:

export PETTRACER_USERNAME="your_username"
export PETTRACER_PASSWORD="your_password"
python examples/class_based_example.py

Security

⚠️ Important: Authentication tokens are secrets. Always:

  • Store credentials in environment variables or secure vaults
  • Never commit tokens or passwords to version control
  • Use .env files (which are gitignored) for local development
  • Rotate tokens regularly

The client supports token storage via environment variable:

import os
os.environ['PETTRACER_TOKEN'] = 'your_token_here'

Testing

Run the comprehensive test suite:

# Install test dependencies
pip install -r requirements-dev.txt

# Run all tests
pytest -v

# Run specific test file
pytest tests/test_client.py -v

# Run with coverage
pytest --cov=pettracer tests/

The test suite uses pytest with monkeypatch to mock HTTP responses, ensuring tests run without actual API calls.

VS Code Setup

This workspace is pre-configured for VS Code development. See VSCODE_GUIDE.md for detailed instructions.

Quick Start in VS Code

  1. Copy .env.example to .env and add your credentials
  2. Open examples/class_based_example.py
  3. Press F5 to run with debugging
  4. Choose "Python: Run with .env"

The workspace includes:

  • Launch configurations for debugging
  • Automatic PYTHONPATH setup in terminals
  • pytest test discovery and debugging
  • Python interpreter configuration

Development

Project Structure

pettracer/
├── __init__.py           # Package exports
├── client.py             # PetTracerClient and PetTracerDevice classes
└── types.py              # Dataclass definitions

examples/
└── class_based_example.py  # Complete usage example

tests/
└── test_client.py        # Test suite

.vscode/
├── settings.json         # VS Code configuration
└── launch.json          # Debug configurations

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

Issues and feature requests can be submitted via GitHub Issues.

License

See repository for license information.


Note: This is an unofficial client library. PetTracer® is a trademark of its respective owner.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pettracer_client-0.2.0.tar.gz (22.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pettracer_client-0.2.0-py3-none-any.whl (13.9 kB view details)

Uploaded Python 3

File details

Details for the file pettracer_client-0.2.0.tar.gz.

File metadata

  • Download URL: pettracer_client-0.2.0.tar.gz
  • Upload date:
  • Size: 22.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pettracer_client-0.2.0.tar.gz
Algorithm Hash digest
SHA256 d50de61d1e9cdb9e8b917bd1a1a62d3ee4ce9b7e97627a7cd038b895920c7d0d
MD5 17886f8818dcd183800bdedfae33bb9d
BLAKE2b-256 c46a8c0ee9719cbf2f21a3b8728900844730f12f3a0460d7a9215b8b61755242

See more details on using hashes here.

Provenance

The following attestation bundles were made for pettracer_client-0.2.0.tar.gz:

Publisher: publish.yml on AmbientArchitect/petTracer-API

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pettracer_client-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pettracer_client-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1a1b6f0353f0e72364c9124b7cb2b6c55ba20b3dbb0f2d02f1f88b3ca7432ec9
MD5 8407e4bbadff779881b230565da0f000
BLAKE2b-256 2ac26cde26a6053d41b4b78ff249656535dd5e01bf4fc5cdcbda494b3fbdf17e

See more details on using hashes here.

Provenance

The following attestation bundles were made for pettracer_client-0.2.0-py3-none-any.whl:

Publisher: publish.yml on AmbientArchitect/petTracer-API

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page