Skip to main content

Python SDK for SensorVision IoT platform

Project description

SensorVision Python SDK

Python Version License

Official Python SDK for SensorVision - The IoT platform that scales with you.

Build IoT applications with enterprise-grade infrastructure and developer-friendly tools. This SDK provides simple, production-ready clients for sending telemetry data from IoT devices, Raspberry Pi projects, Python applications, and more.

Features

  • 🚀 Simple API - Send telemetry data with just a few lines of code
  • Async Support - Built-in asyncio support for high-performance applications
  • 🔄 Auto-Retry - Automatic retry logic with exponential backoff
  • 🛡️ Type Safety - Full type hints for IDE autocomplete and type checking
  • 📝 Comprehensive Logging - Built-in logging for debugging and monitoring
  • 🔌 Flexible - Works with any Python-based IoT device or application
  • 🌐 Well-Tested - >90% test coverage

Installation

Install from GitHub (Recommended)

# Basic installation
pip install git+https://github.com/CodeFleck/sensorvision.git#subdirectory=sensorvision-sdk

# With async support
pip install "git+https://github.com/CodeFleck/sensorvision.git#subdirectory=sensorvision-sdk[async]"

# For Raspberry Pi projects
pip install "git+https://github.com/CodeFleck/sensorvision.git#subdirectory=sensorvision-sdk[raspberry-pi]"

Install from PyPI (Coming Soon)

Once published to PyPI, you'll be able to install with:

pip install sensorvision-sdk                    # Basic
pip install sensorvision-sdk[async]            # With async support
pip install sensorvision-sdk[raspberry-pi]     # Raspberry Pi extras

Development Installation

# Clone the repository
git clone https://github.com/CodeFleck/sensorvision.git
cd sensorvision/sensorvision-sdk

# Install in editable mode with dev dependencies
pip install -e ".[dev]"

Quick Start

Synchronous Client

from sensorvision import SensorVisionClient

# Initialize client
client = SensorVisionClient(
    api_url="http://localhost:8080",
    api_key="your-device-token"
)

# Send telemetry data
response = client.send_data("my-sensor", {
    "temperature": 23.5,
    "humidity": 65.2,
    "pressure": 1013.25
})

print(f"Success! {response.message}")

# Close the client
client.close()

Context Manager (Recommended)

from sensorvision import SensorVisionClient

with SensorVisionClient(
    api_url="http://localhost:8080",
    api_key="your-device-token"
) as client:
    response = client.send_data("my-sensor", {
        "temperature": 23.5,
        "humidity": 65.2
    })

Asynchronous Client

import asyncio
from sensorvision import AsyncSensorVisionClient

async def main():
    async with AsyncSensorVisionClient(
        api_url="http://localhost:8080",
        api_key="your-device-token"
    ) as client:
        response = await client.send_data("my-sensor", {
            "temperature": 23.5,
            "humidity": 65.2
        })
        print(response.message)

asyncio.run(main())

Configuration

Client Parameters

SensorVisionClient(
    api_url="http://localhost:8080",     # SensorVision API URL
    api_key="your-device-token",          # Device authentication token
    timeout=30,                           # Request timeout in seconds
    retry_attempts=3,                     # Number of retry attempts
    retry_delay=1.0,                      # Initial retry delay in seconds
    verify_ssl=True                       # SSL certificate verification
)

Environment Variables

You can also configure the SDK using environment variables:

import os
from sensorvision import SensorVisionClient
from sensorvision.utils import get_env_or_raise

client = SensorVisionClient(
    api_url=get_env_or_raise("SENSORVISION_API_URL"),
    api_key=get_env_or_raise("SENSORVISION_API_KEY")
)

Examples

Raspberry Pi DHT22 Sensor

import time
import Adafruit_DHT
from sensorvision import SensorVisionClient

# Setup
sensor = Adafruit_DHT.DHT22
pin = 4
client = SensorVisionClient(
    api_url="http://localhost:8080",
    api_key="your-token"
)

# Read and send data every 60 seconds
while True:
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    if humidity and temperature:
        client.send_data("raspberry-pi-dht22", {
            "temperature": round(temperature, 2),
            "humidity": round(humidity, 2)
        })

    time.sleep(60)

Async Batch Processing

import asyncio
from sensorvision import AsyncSensorVisionClient

async def send_batch(client, device_ids, data):
    tasks = [
        client.send_data(device_id, data[device_id])
        for device_id in device_ids
    ]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    return results

async def main():
    async with AsyncSensorVisionClient(
        api_url="http://localhost:8080",
        api_key="your-token"
    ) as client:
        device_data = {
            "sensor-001": {"temperature": 23.5},
            "sensor-002": {"temperature": 24.1},
            "sensor-003": {"temperature": 22.8},
        }

        results = await send_batch(client, device_data.keys(), device_data)
        print(f"Sent data for {len(results)} devices")

asyncio.run(main())

Multi-Sensor Monitoring

import time
from sensorvision import SensorVisionClient

def read_all_sensors():
    """Read from multiple sensor types."""
    return {
        # Environmental sensors
        "temperature": 23.5,
        "humidity": 65.2,
        "pressure": 1013.25,

        # Air quality sensors
        "co2_ppm": 450,
        "pm25": 12.5,

        # Power monitoring
        "voltage": 220.5,
        "current": 0.85,
        "power_kw": 0.187
    }

with SensorVisionClient(
    api_url="http://localhost:8080",
    api_key="your-token"
) as client:
    while True:
        data = read_all_sensors()
        client.send_data("multi-sensor-station", data)
        time.sleep(30)

Error Handling

The SDK provides specific exception types for different error scenarios:

from sensorvision import SensorVisionClient
from sensorvision.exceptions import (
    AuthenticationError,
    ValidationError,
    NetworkError,
    ServerError,
    RateLimitError
)

client = SensorVisionClient(
    api_url="http://localhost:8080",
    api_key="your-token"
)

try:
    response = client.send_data("my-sensor", {
        "temperature": 23.5
    })
except AuthenticationError:
    print("Invalid API key")
except ValidationError:
    print("Invalid data format")
except RateLimitError:
    print("Rate limit exceeded, slow down")
except NetworkError:
    print("Network connection failed")
except ServerError:
    print("Server error, try again later")

API Reference

SensorVisionClient

send_data(device_id: str, data: Dict[str, float]) -> IngestionResponse

Send telemetry data to SensorVision.

Parameters:

  • device_id (str): Unique identifier for the device
  • data (Dict[str, float]): Dictionary of variable names to numeric values

Returns:

  • IngestionResponse: Response object with success status and message

Raises:

  • ValueError: If device_id or data is invalid
  • AuthenticationError: If API key is invalid
  • NetworkError: If network request fails
  • ServerError: If server returns 5xx error

AsyncSensorVisionClient

Same as SensorVisionClient but with async/await support.

async send_data(device_id: str, data: Dict[str, float]) -> IngestionResponse

Asynchronous version of send_data().

Testing

Run tests with pytest:

# Run all tests
pytest

# Run with coverage
pytest --cov=sensorvision --cov-report=html

# Run specific test file
pytest tests/test_client.py

# Run with verbose output
pytest -v

Development

# Clone the repository
git clone https://github.com/CodeFleck/sensorvision.git
cd sensorvision/sensorvision-sdk

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Run type checking
mypy sensorvision

# Format code
black sensorvision tests examples
isort sensorvision tests examples

# Lint code
flake8 sensorvision tests

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Related Projects

  • SensorVision - Main IoT monitoring platform
  • ESP32/Arduino SDK - Coming soon
  • JavaScript/Node.js SDK - Coming soon

Changelog

Version 0.1.0 (2024-01-01)

  • Initial release
  • Synchronous and asynchronous clients
  • Device token authentication
  • Automatic retry logic
  • Comprehensive error handling
  • Full type hints support
  • Example code for Raspberry Pi and batch processing

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

sensorvision_sdk-0.1.0.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

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

sensorvision_sdk-0.1.0-py3-none-any.whl (12.4 kB view details)

Uploaded Python 3

File details

Details for the file sensorvision_sdk-0.1.0.tar.gz.

File metadata

  • Download URL: sensorvision_sdk-0.1.0.tar.gz
  • Upload date:
  • Size: 15.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for sensorvision_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f06d958992ef4dd53d6b3a55e1fcb319cdac495fa840ea96a90fc3e36d7ab6a0
MD5 08ee4d23a4bb927ca0fc847ae6fb3691
BLAKE2b-256 ea2fca24fdbaff8210262d300292ab2b63612f6b3f51be13d2f5040d39658c7f

See more details on using hashes here.

File details

Details for the file sensorvision_sdk-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for sensorvision_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d968d72e959396784965f6d997cdac129c203a5914aec3d51272859cd04e83f9
MD5 abfb09c179d186c8c9dc926044fde28e
BLAKE2b-256 1d88c97bb74644c4fc98d25ab06df87c8f5ef3dad3acc4b1015f0c5c493e96fb

See more details on using hashes here.

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