Skip to main content

Fostrom Device SDK

Project description

Fostrom Device SDK for Python

Fostrom is an IoT Cloud Platform built for developers. Monitor and control your fleet of devices, from microcontrollers to industrial IoT. Designed to be simple, secure, and fast. Experience first-class tooling with Device SDKs, type-safe schemas, programmable actions, and more.

The Fostrom Device SDK for Python works with Python 3.8+ and helps you quickly integrate, start monitoring, and controlling your IoT devices in just a few lines of code.

Installation

pip install fostrom

Quick Start

from fostrom import Fostrom

# Create SDK instance
fostrom = Fostrom({
    "fleet_id": "<your-fleet-id>",
    "device_id": "<your-device-id>",
    "device_secret": "<your-device-secret>",
})

# Setup mail handler for incoming messages
def handle_mail(mail):
    print(f"Received: {mail.name} ({mail.id})")
    mail.ack()  # Acknowledge the message

fostrom.on_mail = handle_mail

# Connect and start sending data
if fostrom.connect():
    print("Connected successfully!")
else:
    print("Connection failed - check event handlers for details")
    return

# Send sensor data
fostrom.send_datapoint("sensors", {
    "temperature": 23.5,
    "humidity": 65,
    "timestamp": time.time()
})

# Send status messages
fostrom.send_msg("status", {"online": True})

# Keep running to receive events
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print("Stopping...")

Features

  • Simple API: Clean, Pythonic interface with full type annotations
  • Real-time Events: Automatic event streaming for instant mail delivery
  • Background Agent: Handles connection management and reconnection automatically
  • Error Handling: Comprehensive error handling with detailed error messages
  • Mail System: Send and receive messages with ack/reject/requeue operations
  • Type Safety: Full typing support with mypy compatibility

Event Handlers

The SDK provides several event handlers you can customize:

fostrom = Fostrom(config)

# Handle incoming mail
fostrom.on_mail = lambda mail: (
    print(f"Mail: {mail.name}"),
    mail.ack()
)

# Handle connection events
fostrom.on_connected = lambda: print("Connected to Fostrom!")
fostrom.on_unauthorized = lambda reason, after: print(f"Auth failed: {reason}")
fostrom.on_reconnecting = lambda reason, after: print(f"Reconnecting: {reason}")

API Reference

Fostrom Class

__init__(config)

Create a new Fostrom instance.

Parameters:

  • config (dict): Configuration dictionary with:
    • fleet_id (str): Your fleet ID
    • device_id (str): Your device ID
    • device_secret (str): Your device secret
    • log (bool, optional): Enable logging (default: True)

connect() -> bool

Connect to Fostrom and start the event stream. Returns True on success, False on failure. On failure, calls appropriate event handlers (on_unauthorized or on_reconnecting) instead of raising exceptions.

send_datapoint(name: str, payload: dict) -> None

Send a datapoint to Fostrom.

send_msg(name: str, payload: dict) -> None

Send a message to Fostrom.

mailbox_status() -> dict

Get current mailbox status.

next_mail() -> Mail | None

Get the next mail from the mailbox.

Mail Class

Properties

  • id (str): Mail ID
  • name (str): Mail name/type
  • payload (dict): Mail payload data
  • mailbox_size (int): Current mailbox size

Methods

  • ack(): Acknowledge the mail
  • reject(): Reject the mail
  • requeue(): Requeue the mail

Error Handling

The SDK uses FostromError for all Fostrom-related errors:

from fostrom import Fostrom, FostromError

try:
    fostrom.connect()
except FostromError as e:
    print(f"Error [{e.atom}]: {e.message}")

Complete Example

import time
import random
from fostrom import Fostrom, FostromError

def main():
    fostrom = Fostrom({
        "fleet_id": "your-fleet-id",
        "device_id": "your-device-id",
        "device_secret": "your-device-secret",
    })

    # Event handlers
    fostrom.on_mail = lambda mail: (
        print(f"📧 Mail: {mail.name}"),
        mail.ack()
    )

    fostrom.on_connected = lambda: print("🟢 Connected!")
    fostrom.on_unauthorized = lambda r, a: print(f"🔒 Auth failed: {r}")

    print("Connecting to Fostrom...")
    if fostrom.connect():
        # Send periodic sensor data
        try:
            while True:
                data = {
                    "temperature": round(random.uniform(20, 25), 1),
                    "humidity": random.randint(40, 80),
                    "timestamp": time.time()
                }

                fostrom.send_datapoint("sensors", data)
                print(f"Sent: {data}")

                time.sleep(10)

        except KeyboardInterrupt:
            print("🛑 Stopping...")
    else:
        print("❌ Failed to connect - check event handlers for details")

if __name__ == "__main__":
    try:
        main()
    except FostromError as e:
        print(f"❌ Error: [{e.atom}] {e.message}")

Device Agent

The Fostrom Device SDK downloads and runs the Fostrom Device Agent in the background. The Agent is downloaded automatically when the package is installed. The Device Agent starts when fostrom.connect() is called and handles all communication with the Fostrom platform.

The Agent runs continuously in the background for optimal reconnection performance. To stop the Agent completely:

Fostrom.stop_agent()

Note: Your Python program will continue running to receive real-time events from the Agent. Use Ctrl+C to stop your program gracefully.

Requirements

  • Python 3.8+
  • Linux or macOS
  • Network connectivity

Links

License

Apache 2.0

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

fostrom-0.0.5.tar.gz (9.6 kB view details)

Uploaded Source

Built Distribution

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

fostrom-0.0.5-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

Details for the file fostrom-0.0.5.tar.gz.

File metadata

  • Download URL: fostrom-0.0.5.tar.gz
  • Upload date:
  • Size: 9.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.2

File hashes

Hashes for fostrom-0.0.5.tar.gz
Algorithm Hash digest
SHA256 17783b33fc59d54f849aabfb198251aa867fc30aac7d8203d893c1aa08694464
MD5 6b70010c8441031e78a535504c8426b6
BLAKE2b-256 727e1b69ae1aad4a68571025c07b6c063b4b1626aa45ecc1b79891ad04159511

See more details on using hashes here.

File details

Details for the file fostrom-0.0.5-py3-none-any.whl.

File metadata

  • Download URL: fostrom-0.0.5-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.2

File hashes

Hashes for fostrom-0.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 83326e60cc3c3019c2c29bcdf4b5603268d4109424901c2fdee66c09e873ffe3
MD5 1b3e161cdf619567677d6cb6bc172579
BLAKE2b-256 538c3a49f914f51b71c86150c6e6f6708e66092df92f9470d7ce8c26599b2b72

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