Skip to content

Python tutorials

Learn how to integrate Dracal devices into your Python applications using the REST JSON API. These tutorials provide complete, working examples that demonstrate core functionality.

Overview

The Python tutorials use the requests library for HTTP communication and Python's built-in json module for parsing responses. They're designed to be simple, readable, and easy to adapt for your own projects.

Prerequisites

  • Python 3.6 or higher
  • pip package manager
  • Dracal device service installed and running

Setting up a virtual environment

It's recommended to use a virtual environment to manage dependencies:

python -m venv venv
venv\Scripts\activate
pip install requests
python3 -m venv venv
source venv/bin/activate
pip install requests

After activation, your command prompt will show (venv) indicating the virtual environment is active.

To deactivate the virtual environment when you're done:

deactivate

Tutorial examples

Example 1: Check if service is running

Demonstrates how to verify that the Dracal device service is running and accessible.

File: 1_check_running.py

"""
Example 1: Check if Dracal Device Service is Running

This example demonstrates how to verify that the Dracal device service
is running and accessible via the REST JSON API.
"""

import requests
import sys


def check_if_running():
    """
    Check if the Dracal device service is running.

    Returns:
        bool: True if service is running and accessible, False otherwise
    """
    try:
        response = requests.get(
            "http://localhost:11395/dracal-service-info",
            timeout=1
        )

        if response.status_code != 200:
            return False

        # Print the JSON response (pretty-printed)
        print(response.text)
        return True

    except requests.exceptions.RequestException:
        # Connection failed, timeout, or other request error
        return False


def main():
    """Main entry point for the example."""
    is_running = check_if_running()

    if not is_running:
        print("The Dracal device service is not running")
        input("\nPress enter to close this window...")
        return -1

    print("\nDracal device service is running")
    input("\nPress enter to close this window...")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run the example:

python 1_check_running.py

Expected output:

{
  "service_name": "dracal-device-service",
  "status": "ok",
  "version": {
    "major": 3,
    "minor": 5,
    "patch": 0,
    "tag": "v3.5.0",
    "tweak": 0
  }
}

Dracal device service is running

Press enter to close this window...

Example 2: List connected devices

Shows how to retrieve and display a list of all connected Dracal devices.

File: 2_device_list.py

"""
Example 2: List Connected Devices

This example demonstrates how to retrieve and display all connected
Dracal devices using the REST JSON API.
"""

import requests
import sys


def get_device_list():
    """
    Get list of connected Dracal devices.

    Returns:
        dict or None: Device data if successful, None otherwise
    """
    try:
        response = requests.get(
            "http://localhost:11395/3.5.0/devices/usb",
            timeout=1
        )

        if response.status_code != 200:
            return None

        return response.json()

    except requests.exceptions.RequestException:
        return None


def main():
    """Main entry point for the example."""
    data = get_device_list()

    if data is None:
        print("Failed to retrieve device list")
        input("\nPress enter to close this window...")
        return -1

    devices = data.get("devices", {})

    if not devices:
        print("No Dracal devices found")
        input("\nPress enter to close this window...")
        return 0

    print("Dracal devices found:")
    for serial, device in devices.items():
        product = device["info"]["product"]
        print(f"\t{product} with serial {serial}")

    input("\nPress enter to close this window...")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run the example:

python 2_device_list.py

Expected output:

Dracal devices found:
    VCP-BAR20-CAL with serial E23892

Press enter to close this window...

Example 3: Get device information

Retrieves detailed information about a specific device, including all available channels and their current readings.

File: 3_get_device.py

"""
Example 3: Get Device Information

This example demonstrates how to retrieve detailed information about
the first connected device, including all channels and their values.
"""

import requests
import sys


def get_device_info():
    """
    Get detailed information about the first connected device.

    Returns:
        tuple: (serial, device_data) if successful, (None, None) otherwise
    """
    try:
        response = requests.get(
            "http://localhost:11395/3.5.0/devices/usb",
            timeout=1
        )

        if response.status_code != 200:
            return None, None

        data = response.json()
        devices = data.get("devices", {})

        if not devices:
            return None, None

        # Get the first device
        first_serial = list(devices.keys())[0]
        first_device = devices[first_serial]

        return first_serial, first_device

    except requests.exceptions.RequestException:
        return None, None


def main():
    """Main entry point for the example."""
    serial, device = get_device_info()

    if device is None:
        print("No Dracal devices found")
        input("\nPress enter to close this window...")
        return -1

    product = device["info"]["product"]
    print(f"First Dracal device found:")
    print(f"{product} with serial {serial}")

    print("\nChannels")
    for channel_name in device["channel_list"]:
        channel = device["channels"][channel_name]
        value = channel["value"]

        magnitude = value["magnitude"]
        unit = value["unit"]
        timestamp = value["timestamp"]

        print(f"\t{channel_name:25}: timestamp: {timestamp} value: {magnitude} {unit}")

    input("\nPress enter to close this window...")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run the example:

python 3_get_device.py

Expected output:

First Dracal device found:
VCP-BAR20-CAL with serial E23892

Channels
    altitude                 : timestamp: 2025-12-03T18:52:29.178Z value: -2808795.75 mm
    internal_temperature     : timestamp: 2025-12-03T18:52:29.178Z value: 25.34 °C
    pressure                 : timestamp: 2025-12-03T18:52:29.178Z value: 139.94 kPa

Press enter to close this window...

Example 4: Work with RTD300 device

Demonstrates working with a specific device type (RTD300 temperature sensor) and extracting temperature readings.

File: 4_RTD300.py

"""
Example 4: Work with RTD300 Device

This example demonstrates how to find and read data from a specific
device type (RTD300 temperature sensor).
"""

import requests
import sys


def get_rtd300_device():
    """
    Find and retrieve data from the first RTD300 device.

    Returns:
        tuple: (serial, device_data) if found, (None, None) otherwise
    """
    try:
        response = requests.get(
            "http://localhost:11395/3.5.0/devices/usb",
            timeout=1
        )

        if response.status_code != 200:
            return None, None

        data = response.json()
        devices = data.get("devices", {})

        # Find first RTD300 device
        for serial, device in devices.items():
            product = device["info"]["product"]
            if "RTD300" in product:
                return serial, device

        return None, None

    except requests.exceptions.RequestException:
        return None, None


def main():
    """Main entry point for the example."""
    serial, device = get_rtd300_device()

    if device is None:
        print("No RTD300 device found")
        input("\nPress enter to close this window...")
        return -1

    product = device["info"]["product"]
    print(f"First Dracal RTD300 device found:")
    print(f"\tProduct: {product}, Serial: {serial}")

    # Get temperature channel
    if "temperature" in device["channels"]:
        temp_channel = device["channels"]["temperature"]
        temp_value = temp_channel["value"]

        print(f"\t\tTemperature:")
        print(f"\t\t\ttimestamp: {temp_value['timestamp']}")
        print(f"\t\t\tvalue    : {temp_value['magnitude']} {temp_value['unit']}")

    input("\nPress enter to close this window...")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run the example:

python 4_RTD300.py

Expected output:

First Dracal RTD300 device found:
    Product: VCP-RTD300-CAL, Serial: E22377
        Temperature:
            timestamp: 2025-12-12T01:27:54.087Z
            value    : 120.68 °C

Press enter to close this window...