Python client library for the PetTracer GPS pet collar portal
Project description
PetTracer API Client
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:
- examples/class_based_example.py - Full async usage
- examples/home_assistant_example.py - Home Assistant integration pattern
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 credentialsawait get_all_devices()- Retrieve all devices owned by the userget_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 intoken- Current bearer tokentoken_expires- Token expiration datetimesession- aiohttp ClientSession object
User Information (available after login):
user_id,user_name,emailpartner_id,languagecountry,country_iddevice_count- Number of devices
Subscription:
subscription_id- Subscription identifiersubscription_expires- Expiration datesubscription_info- FullSubscriptionInfoobject
Raw Data:
login_info- CompleteLoginInfodataclass 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 informationawait 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,modedetails-Detailsobject with name, image, birth datelastPos-LastPosobject with most recent positionmasterHs- Master home station informationlastContact,homeSince- Timestamps- Many more fields for device state
LastPos - Position data:
posLat,posLong- CoordinatestimeMeasure,timeDb- Timestampssat- Satellite countrssi- Signal strengthfixS,fixP,horiPrec- GPS quality metricsacc- Accuracyflags- Status flags
Details - Device/pet details:
name- Pet namebirth- Birth dateimage,img- Image referencescolor- Color code
UserProfile - User account information:
id,email,namestreet,street2,zip,citymobile,lang,country_id- Additional profile fields
LoginInfo - Complete login response data:
- User identification and account details
- Authentication tokens and expiration
- Subscription information via
abofield - Settings and preferences
SubscriptionInfo - Subscription details:
id,userId,odooIddateExpires- Expiration datepaypalSubscriptionId- 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
.envfiles (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
- Copy
.env.exampleto.envand add your credentials - Open
examples/class_based_example.py - Press
F5to run with debugging - 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:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d50de61d1e9cdb9e8b917bd1a1a62d3ee4ce9b7e97627a7cd038b895920c7d0d
|
|
| MD5 |
17886f8818dcd183800bdedfae33bb9d
|
|
| BLAKE2b-256 |
c46a8c0ee9719cbf2f21a3b8728900844730f12f3a0460d7a9215b8b61755242
|
Provenance
The following attestation bundles were made for pettracer_client-0.2.0.tar.gz:
Publisher:
publish.yml on AmbientArchitect/petTracer-API
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pettracer_client-0.2.0.tar.gz -
Subject digest:
d50de61d1e9cdb9e8b917bd1a1a62d3ee4ce9b7e97627a7cd038b895920c7d0d - Sigstore transparency entry: 885210043
- Sigstore integration time:
-
Permalink:
AmbientArchitect/petTracer-API@c593dab04114f5b8bb05d2e644e4386bfdd07ca2 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/AmbientArchitect
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@c593dab04114f5b8bb05d2e644e4386bfdd07ca2 -
Trigger Event:
workflow_dispatch
-
Statement type:
File details
Details for the file pettracer_client-0.2.0-py3-none-any.whl.
File metadata
- Download URL: pettracer_client-0.2.0-py3-none-any.whl
- Upload date:
- Size: 13.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1a1b6f0353f0e72364c9124b7cb2b6c55ba20b3dbb0f2d02f1f88b3ca7432ec9
|
|
| MD5 |
8407e4bbadff779881b230565da0f000
|
|
| BLAKE2b-256 |
2ac26cde26a6053d41b4b78ff249656535dd5e01bf4fc5cdcbda494b3fbdf17e
|
Provenance
The following attestation bundles were made for pettracer_client-0.2.0-py3-none-any.whl:
Publisher:
publish.yml on AmbientArchitect/petTracer-API
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pettracer_client-0.2.0-py3-none-any.whl -
Subject digest:
1a1b6f0353f0e72364c9124b7cb2b6c55ba20b3dbb0f2d02f1f88b3ca7432ec9 - Sigstore transparency entry: 885210143
- Sigstore integration time:
-
Permalink:
AmbientArchitect/petTracer-API@c593dab04114f5b8bb05d2e644e4386bfdd07ca2 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/AmbientArchitect
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@c593dab04114f5b8bb05d2e644e4386bfdd07ca2 -
Trigger Event:
workflow_dispatch
-
Statement type: