This directory contains example scripts demonstrating how to use the teslemetry-stream library to connect to Tesla telemetry data and add custom fields for monitoring.
- Teslemetry Account: Sign up at teslemetry.com
- Access Token: Get your access token from the Teslemetry Console
- Vehicle VIN: Your Tesla vehicle's VIN number
- Python Dependencies: Install the required packages:
pip install teslemetry-stream aiohttp
Purpose: Demonstrates the fundamental pattern for adding telemetry fields and listening to data.
What it shows:
- Connecting to the Teslemetry Stream service
- Adding basic telemetry fields (battery level, speed, charge state)
- Setting up a simple event handler
- Adding custom fields to incoming data
Usage:
# Edit the file to add your ACCESS_TOKEN and VIN
python simple_field_example.pyKey concepts:
- Using
vehicle.add_field()to subscribe to specific telemetry signals - Setting custom intervals for different fields
- Processing incoming telemetry events
- Adding computed fields to the data stream
Purpose: Shows a complete implementation with multiple field types, event handlers, and custom processing.
What it shows:
- Adding multiple fields with different monitoring intervals
- Using typed listener methods for specific signals
- Creating custom event handlers for different data types
- Implementing custom field derivation and alerts
- Proper resource cleanup and error handling
Features demonstrated:
- Battery level monitoring with low battery alerts
- Vehicle speed tracking
- Location monitoring
- Charge state management
- Custom field generation (data freshness, charging recommendations)
Usage:
# Update configuration section with your credentials
python example_add_field.pyPurpose: Demonstrates sophisticated telemetry processing with dynamic field management and data enrichment.
What it shows:
- Dynamic field addition and interval updates during runtime
- Advanced data processing with the
TelemetryProcessorclass - Historical data tracking and trend analysis
- Alert generation based on multiple conditions
- Event statistics and monitoring
- Field configuration management
Advanced features:
- Battery change rate calculation
- Location zone determination
- Climate efficiency assessment
- Energy efficiency categorization
- Multi-field derived metrics
- Real-time alert system
Usage:
# Configure ACCESS_TOKEN and VIN in the script
python advanced_field_example.pyBefore running any example, update these variables in the scripts:
ACCESS_TOKEN = "your_teslemetry_access_token_here"
VIN = "your_vehicle_vin_here"
SERVER = "api.teslemetry.com" # or your regional serverChoose the appropriate server based on your location:
api.teslemetry.com- Global (recommended)na.teslemetry.com- North Americaeu.teslemetry.com- Europe
The library supports numerous telemetry fields defined in the Signal enum. Common fields include:
BATTERY_LEVEL- Battery percentageCHARGE_STATE- Charging statusCHARGE_AMPS- Charging currentCHARGER_VOLTAGE- Charger voltageTIME_TO_FULL_CHARGE- Estimated time to full charge
VEHICLE_SPEED- Current speedLOCATION- GPS coordinatesODOMETER- Total distance traveledGEAR- Current gear selection
INSIDE_TEMP- Cabin temperatureOUTSIDE_TEMP- Ambient temperatureHVAC_POWER- Climate system statusHVAC_FAN_SPEED- Fan speed setting
DOOR_STATE- Door open/closed statusLOCKED- Vehicle lock stateSENTRY_MODE- Sentry mode statusCENTER_DISPLAY- Display state
For a complete list of available fields, see:
- The
Signalenum inteslemetry_stream/const.py - Teslemetry Fields API
# Add field with 30-second updates
await vehicle.add_field(Signal.BATTERY_LEVEL, interval=30)
# Add field with default interval
await vehicle.add_field(Signal.CHARGE_STATE)# Set up typed listeners for specific fields
def battery_handler(battery_level):
print(f"Battery: {battery_level}%")
remove_listener = vehicle.listen_BatteryLevel(battery_handler)# Handle all telemetry events
def handle_all_data(event):
if "data" in event:
data = event["data"]
# Process any fields present in the data
remove_listener = stream.async_add_listener(handle_all_data)All examples demonstrate adding custom fields to the telemetry data:
# Add computed status field
if "BatteryLevel" in data:
if data["BatteryLevel"] > 80:
data["battery_status"] = "high"
elif data["BatteryLevel"] > 20:
data["battery_status"] = "medium"
else:
data["battery_status"] = "low"# Add time-based fields
data["processed_at"] = datetime.now().isoformat()
# Add multi-field derivatives
if "BatteryLevel" in data and "ChargeState" in data:
data["needs_charging"] = (
data["ChargeState"] != "Charging" and data["BatteryLevel"] < 30
)The examples include proper error handling patterns:
try:
async with stream: # Auto-connect and cleanup
# Your telemetry processing code
await asyncio.sleep(duration)
except Exception as e:
logger.error(f"Telemetry error: {e}")
finally:
# Cleanup listeners
remove_listener()- Use appropriate intervals: Don't request data more frequently than needed
- Handle reconnections: The library handles reconnections automatically
- Clean up listeners: Always remove listeners when done
- Process data efficiently: Avoid blocking operations in event handlers
- Monitor rate limits: Be aware of API rate limiting
- Use typed listeners: Prefer typed listeners for better error handling
- Log appropriately: Use structured logging for debugging and monitoring
- Authentication Error: Verify your access token is correct and active
- VIN Not Found: Ensure the VIN is correct and associated with your account
- Connection Timeout: Check network connectivity and server selection
- No Data Received: Verify the vehicle is online and telemetry is enabled
Enable debug logging to see detailed connection information:
import logging
logging.basicConfig(level=logging.DEBUG)If you encounter rate limiting:
- Increase field intervals
- Reduce the number of concurrent fields
- Contact Teslemetry support for higher limits
After running these examples:
- Customize field selection: Choose only the fields you need for your application
- Implement data persistence: Store telemetry data in a database
- Create dashboards: Visualize the telemetry data
- Set up alerts: Create automated alerts for important conditions
- Integrate with other services: Send data to cloud services or home automation systems
- Library Documentation: See the main README.md
- Teslemetry Documentation: docs.teslemetry.com
- API Reference: api.teslemetry.com
- Community Support: Join the Teslemetry community forums
These examples are provided under the same license as the main library.