---
sidebar:
  hidden: true
title: roboto.domain.devices.device
---
## Module Contents

### Device

```python
class roboto.domain.devices.device.Device(
    record: roboto.domain.devices.record.DeviceRecord,
    roboto_client: Optional[roboto.http.RobotoClient] = None,
)
```

`from roboto import Device`

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L49-L998)

A device: a robot, upload station, or other non-human entity that interacts with Roboto programmatically.

A device belongs to one organization, which gives it an ID, such as a serial number or asset tag, unique within that organization. Access tokens from `create_token` let the device make requests as itself, such as creating datasets and uploading files, which then record its ID. A device also has files of its own, its `configurations`, and carries tags, key-value metadata, and custom-field values.

Get a `Device` from `create`, `from_id`, or `for_org`. To wrap a [`DeviceRecord`](/docs/reference/python-sdk/roboto/domain/devices/record#roboto.domain.devices.record.DeviceRecord) already fetched from Roboto, build a `Device` from it directly. Methods that change the device return a new `Device` holding the updated record, and leave the record of the instance they were called on as it was.

**Parameters**

- **record** (`roboto.domain.devices.record.DeviceRecord`): Record of the device.
- **roboto_client** (`Optional[roboto.http.RobotoClient]`): Client to make requests to Roboto with. Defaults to one configured from the environment, by [`from_env()`](/docs/reference/python-sdk/roboto/http/roboto_client#roboto.http.roboto_client.RobotoClient.from_env).

**Properties**

- **Device.configurations** (`roboto.domain.files.FileSystem`): Files of the device itself, such as URDFs, calibration files, manifests, and maintenance logs.

  Data the device records goes to datasets instead: a dataset file whose `device_id` names this device is not one of its configurations.

  A device with a device type also inherits the type's configurations. Pass `include_inherited=True` to [`list_files()`](/docs/reference/python-sdk/roboto/domain/files/file_system#roboto.domain.files.file_system.FileSystem.list_files) or [`download_files()`](/docs/reference/python-sdk/roboto/domain/files/file_system#roboto.domain.files.file_system.FileSystem.download_files) to include them; the other methods act on the device's own files only.

  Reading it raises `RobotoNotReadyException` when the device's record has no `universal_device_id`.

- **Device.created** (`datetime.datetime`): Time the device was created.

- **Device.created_by** (`str`): Principal that created the device, as `<type>:<id>`, such as `user:<user_id>`.

- **Device.custom_fields** (`dict[str, Any]`): Values of the custom fields the organization defines for devices, keyed by field name.

  Which fields appear as keys is as [`custom_fields`](/docs/reference/python-sdk/roboto/domain/devices/record#roboto.domain.devices.record.DeviceRecord.custom_fields) describes. A [`Timestamp`](/docs/reference/python-sdk/roboto/domain/custom_fields/record#roboto.domain.custom_fields.record.CustomFieldType.Timestamp) value is an ISO 8601 string.

- **Device.device_id** (`str`): ID the organization gave the device, such as a serial number, unique within the organization.

- **Device.device_type_id** (`str | None`): ID of the device type assigned to the device, beginning with `dt_`, or `None` if it has none.

  Return type: `Optional[str]`

- **Device.encoded_device_id** (`str`): Device ID, percent-encoded so that it fits in one segment of a URL path, `/` included.

- **Device.metadata** (`dict[str, Any]`): Key-value metadata on the device.

- **Device.modified** (`datetime.datetime`): Time the device was last modified.

- **Device.modified_by** (`str`): Principal that last modified the device, in the same `<type>:<id>` form as `created_by`.

- **Device.org_id** (`str`): ID of the organization that owns the device.

- **Device.record** (`roboto.domain.devices.record.DeviceRecord`): Record of the device that this instance holds.

- **Device.tags** (`list[str]`): Tags on the device.

#### Device.clear_custom_field()

```python
def clear_custom_field(name: str) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L891-L908)

Clear one custom-field value on the device, so the field reads back as `None`.

**Parameters**

- **name** (`str`): Name of a ready custom field defined for devices in the device's organization.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Raises**

- [`RobotoIllegalArgumentException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoIllegalArgumentException): `name` is not a ready custom field for devices.

**Usage**

```python
device = Device.from_id("robot_001")
device.clear_custom_field("firmware_version").custom_fields["firmware_version"] is None
# True
```

#### Device.clear_custom_fields()

```python
def clear_custom_fields(names: collections.abc.Sequence[str]) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L933-L949)

Clear several custom-field values on the device, so each field reads back as `None`.

**Parameters**

- **names** (`collections.abc.Sequence[str]`): Names of ready custom fields defined for devices in the device's organization.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Raises**

- [`RobotoIllegalArgumentException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoIllegalArgumentException): A name is not a ready custom field for devices.

**Usage**

```python
device = Device.from_id("robot_001")
device = device.clear_custom_fields(["firmware_version", "site"])
```

#### Device.create()

```python
@classmethod
def create(
    device_id: str,
    metadata: Optional[dict[str, Any]] = None,
    tags: Optional[list[str]] = None,
    custom_fields: Optional[dict[str, Any]] = None,
    caller_org_id: Optional[str] = None,
    roboto_client: Optional[roboto.http.RobotoClient] = None,
    device_type_id: Optional[str] = None,
) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L72-L138)

Create a device.

**Parameters**

- **device_id** (`str`): ID to give the device, such as a serial number, unique within the organization. [`validate_device_id()`](/docs/reference/python-sdk/roboto/domain/devices/operations#roboto.domain.devices.operations.validate_device_id) lists the IDs Roboto refuses.
- **metadata** (`Optional[dict[str, Any]]`): Key-value metadata to set on the device. `None` sets none.
- **tags** (`Optional[list[str]]`): Tags to set on the device. `None` sets none.
- **custom_fields** (`Optional[dict[str, Any]]`): Initial values for the device's custom fields, keyed by field name. Each name must be a custom field defined for devices in the organization, with status [`Ready`](/docs/reference/python-sdk/roboto/domain/custom_fields/record#roboto.domain.custom_fields.record.CustomFieldStatus.Ready), and each value must match that field's declared type. `None` sets none.
- **caller_org_id** (`Optional[str]`): Organization to create the device in. Required when the caller belongs to more than one organization; otherwise the caller's only organization.
- **roboto_client** (`Optional[roboto.http.RobotoClient]`): Client to make requests to Roboto with. Defaults to one configured from the environment, by [`from_env()`](/docs/reference/python-sdk/roboto/http/roboto_client#roboto.http.roboto_client.RobotoClient.from_env).
- **device_type_id** (`Optional[str]`): ID of a device type in the same organization to assign to the device, beginning with `dt_`. `None` leaves the device without one.

**Returns**

- `Device`: The new device.

**Raises**

- [`RobotoConflictException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoConflictException): The organization already has a device with this `device_id`.
- [`RobotoInvalidRequestException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoInvalidRequestException): `device_type_id` is given and the organization has no such device type.
- [`RobotoIllegalArgumentException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoIllegalArgumentException): A `custom_fields` name is not a ready custom field for devices, or its value does not match the field's type.
- `pydantic.ValidationError`: [`validate_device_id()`](/docs/reference/python-sdk/roboto/domain/devices/operations#roboto.domain.devices.operations.validate_device_id) refuses `device_id`. Raised before anything is sent to Roboto.

**Usage**

Create a device in a named organization:

```python
device = Device.create(device_id="robot_001", caller_org_id="og_12345")
device.device_id
# 'robot_001'
```

Create a device with tags and metadata:

```python
device = Device.create(
    device_id="upload_station_alpha",
    tags=["production", "warehouse-a"],
    metadata={"model": "mk2", "serial_number": "SN001234"},
)
```

#### Device.create_session()

```python
def create_session(
    name: str,
    description: Optional[str] = None,
    metadata: Optional[dict[str, Any]] = None,
    tags: Optional[collections.abc.Sequence[str]] = None,
    custom_fields: Optional[dict[str, Any]] = None,
    anchor: Optional[roboto.time.Time] = None,
    files: Optional[collections.abc.Sequence[roboto.experimental.sessions.SessionFile]] = None,
) -> roboto.experimental.sessions.Session
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L373-L485)

Create one session on this device, optionally with its files, topics, and schemas.

The one-session form of `create_sessions`, taking a single declaration's fields as arguments and sharing its semantics: the session, its file attachments, its topics, and its time ranges are created together or not at all, and every file the declaration names must already be uploaded. `name` identifies the session within this device, so resending the same call is safe: Roboto reuses the session already registered under that name instead of creating a second one. Arguments left at their defaults are left out of the request, so a call that reuses an existing session never overwrites attributes it does not name. To create a session with no name, or one spanning several devices, use [`create()`](/docs/reference/python-sdk/roboto/experimental/sessions/session#roboto.experimental.sessions.session.Session.create).

A declaration Roboto refuses raises its exception here, where `create_sessions` reports it in its response instead.

Declared times are stored exactly as given, in each file's own timestamps, and read as nanoseconds since the Unix epoch; Roboto never invents a wall-clock time. To place the session at the wall-clock time it happened, supply `anchor`, or call [`set_unix_offset()`](/docs/reference/python-sdk/roboto/experimental/sessions/session#roboto.experimental.sessions.session.Session.set_unix_offset) later.

**Parameters**

- **name** (`str`): Name of the session, unique within this device, at most 120 characters.
- **description** (`Optional[str]`): Human-readable description of the session.
- **metadata** (`Optional[dict[str, Any]]`): Key-value metadata to set on the session. Sessions cannot be filtered or sorted by metadata keys; for attributes to query by, define a custom field for sessions.
- **tags** (`Optional[collections.abc.Sequence[str]]`): Tags to set on the session. Sessions can be filtered by tag but not sorted by tag.
- **custom_fields** (`Optional[dict[str, Any]]`): Initial values for the session's custom fields, keyed by field name. Each name must be a custom field defined for sessions in this device's organization, with status [`Ready`](/docs/reference/python-sdk/roboto/domain/custom_fields/record#roboto.domain.custom_fields.record.CustomFieldStatus.Ready), and each value must match that field's declared type.
- **anchor** (`Optional[roboto.time.Time]`): Wall-clock time at which the declared data's time 0 occurred. An `int` is nanoseconds since the Unix epoch; any other [`Time`](/docs/reference/python-sdk/roboto/time#roboto.time.Time) is read as [`to_epoch_nanoseconds()`](/docs/reference/python-sdk/roboto/time#roboto.time.to_epoch_nanoseconds) reads it (a `datetime.datetime` or ISO 8601 string is that instant; a `float`, `decimal.Decimal`, or numeric string is seconds since the epoch). It applies to every file entry that does not carry its own [`anchor_ns`](/docs/reference/python-sdk/roboto/experimental/sessions/operations#roboto.experimental.sessions.operations.FileDeclaration.anchor_ns).
- **files** (`Optional[collections.abc.Sequence[roboto.experimental.sessions.SessionFile]]`): Files in the session, with the topics whose data each one carries. Each file must already be uploaded, and may appear at most once. [`add_file()`](/docs/reference/python-sdk/roboto/experimental/sessions/session#roboto.experimental.sessions.session.Session.add_file) and [`add_files()`](/docs/reference/python-sdk/roboto/experimental/sessions/session#roboto.experimental.sessions.session.Session.add_files) add files after creation.

**Returns**

- `roboto.experimental.sessions.Session`: The new session, or the existing session this device holds under `name`.

**Raises**

- `TypeError`: `anchor` is not one of the [`Time`](/docs/reference/python-sdk/roboto/time#roboto.time.Time) types.
- `ValueError`: `anchor` is a boolean, a negative number (an `int`, `float`, `decimal.Decimal`, or numeric string), or a string that is neither a number of seconds nor an ISO 8601 timestamp. Raised before anything is sent to Roboto.
- `OverflowError`: `anchor` is an infinite `float`, `decimal.Decimal`, or string, such as `"inf"`. Raised before anything is sent to Roboto.
- `pydantic.ValidationError`: `name` is empty or longer than 120 characters, `anchor` does not fall after the Unix epoch or is too large for a signed 64-bit integer of nanoseconds, a file appears in more than one entry, `files` declares more than 500 files and topics combined ([`MAX_FILES_AND_TOPICS_PER_REQUEST`](/docs/reference/python-sdk/roboto/experimental/ingest/operations#roboto.experimental.ingest.operations.MAX_FILES_AND_TOPICS_PER_REQUEST)), or representations name one file in two storage formats. Raised while the request is being built, before anything is sent to Roboto.
- [`RobotoInvalidRequestException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoInvalidRequestException): Roboto refuses the declaration, either because it contradicts data Roboto already holds or because it carries a value Roboto rejects, such as a `custom_fields` value that does not satisfy its field's declared type. No session, file attachment, topic, or time range is created; the topic identifiers and schema definitions the declaration resolved stay stored, and a resend reuses them.
- [`RobotoConflictException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoConflictException): Something the declaration was prepared against changed while it was being written. Nothing is created; resending is the fix.
- [`RobotoNotFoundException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoNotFoundException): This device is no longer registered; the `file_id` of a file entry, or of a representation one of its topics lists, does not name a file in this device's organization whose status is [`Available`](/docs/reference/python-sdk/roboto/domain/files/record#roboto.domain.files.record.FileStatus.Available); or the declaration names something else that does not exist, such as a `custom_fields` key naming a custom field the organization does not define for sessions. Nothing is created.
- [`RobotoUnauthorizedException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoUnauthorizedException): The caller cannot create sessions on this device, or cannot edit a file the declaration declares topics on, a file it anchors, or a file a listed representation names, or lacks topic edit access in this device's organization while the declaration states `is_default_for_reads` on a timeline source.
- [`RobotoUnrecognizedErrorException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoUnrecognizedErrorException): Roboto refuses the declaration under an error code this SDK release does not define. Carries the code and message Roboto sent.

**Usage**

Create a session and add a file to it:

```python
device = Device.from_id("robot_001", org_id="og_12345")
session = device.create_session(name="2024-05-01_morning_run")
session.add_file("fl_12345")
```

Create a session placed at the wall-clock time it was recorded:

```python
import datetime
session = device.create_session(
    name="2024-05-01_morning_run",
    anchor=datetime.datetime(2024, 5, 1, 9, 30, tzinfo=datetime.timezone.utc),
)
```

#### Device.create_sessions()

```python
def create_sessions(
    sessions: collections.abc.Sequence[roboto.experimental.sessions.SessionDeclaration],
) -> roboto.http.BatchResponse[roboto.experimental.sessions.Session]
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L488-L641)

Create many sessions on this device, each with its files, topics, and schemas, in one request.

Each call accepts up to 100 declarations ([`MAX_SESSIONS_PER_REQUEST`](/docs/reference/python-sdk/roboto/experimental/sessions/operations#roboto.experimental.sessions.operations.MAX_SESSIONS_PER_REQUEST)), one per session (such as the episodes of a LeRobot dataset), and up to 500 files and topics combined ([`MAX_FILES_AND_TOPICS_PER_REQUEST`](/docs/reference/python-sdk/roboto/experimental/ingest/operations#roboto.experimental.ingest.operations.MAX_FILES_AND_TOPICS_PER_REQUEST)), counted across every declaration; split anything larger across several calls. Every file a declaration names must already be uploaded; [`upload_files()`](/docs/reference/python-sdk/roboto/domain/datasets/dataset#roboto.domain.datasets.dataset.Dataset.upload_files) returns the file IDs it creates, and files from any number of datasets may appear in one batch.

Roboto decides which declarations to refuse before writing anything, then writes the rest together. A declaration's session, file attachments, topics, and time ranges are created together or not at all, and a declaration Roboto refuses leaves the others written as if it were absent. None of the declarations is written when a failure Roboto did not anticipate, such as a timeout, interrupts the call, or when a session a declaration reuses is deleted before the call completes, which raises [`RobotoNotFoundException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoNotFoundException). Each declaration is written as it would be had the ones before it been sent as calls of their own: a later declaration anchoring data an earlier one holds moves the earlier session's time range with it. A refused declaration, or a call that fails, still leaves behind the topic identifiers and schema definitions it resolved, which a resend reuses.

Check [`failed`](/docs/reference/python-sdk/roboto/http/response#roboto.http.response.BatchResponse.failed) before treating the batch as done. Each entry there is the [`RobotoDomainException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoDomainException) Roboto refused a declaration with, so `isinstance` tells the reasons apart; a refusal under an error code this SDK release does not define arrives as [`RobotoUnrecognizedErrorException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoUnrecognizedErrorException).

Resending the same call is safe. This device and each declaration's `name` identify the session the declaration creates or reuses, so a resend fills in only what is missing rather than duplicating what an earlier attempt created.

Declared times are stored exactly as given, in each file's own timestamps, and read as nanoseconds since the Unix epoch; Roboto never invents a wall-clock time. A recording whose timestamps start at 0 therefore sits at the epoch until it is anchored. To place a session at the wall-clock time it happened, supply [`anchor_ns`](/docs/reference/python-sdk/roboto/experimental/sessions/operations#roboto.experimental.sessions.operations.SessionDeclaration.anchor_ns), or call [`set_unix_offset()`](/docs/reference/python-sdk/roboto/experimental/sessions/session#roboto.experimental.sessions.session.Session.set_unix_offset) later.

**Parameters**

- **sessions** (`collections.abc.Sequence[roboto.experimental.sessions.SessionDeclaration]`): One declaration per session to create. An empty sequence returns an empty response without contacting Roboto.

**Returns**

- `roboto.http.BatchResponse[roboto.experimental.sessions.Session]`: A [`BatchResponse`](/docs/reference/python-sdk/roboto/http/response#roboto.http.response.BatchResponse) with one element per declaration, in request order, holding either the session the declaration created or why Roboto refused it. A declaration naming a session this device already holds yields that session rather than a second one.

**Raises**

- `pydantic.ValidationError`: More than 100 declarations are given, the batch declares more than 500 files and topics combined, the same session name is declared more than once, or representations name one file in two storage formats. Raised while the request body is built, before anything is sent to Roboto.
- [`RobotoInvalidRequestException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoInvalidRequestException): The batch is malformed. Nothing is created.
- [`RobotoNotFoundException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoNotFoundException): This device is no longer registered; the `file_id` of a file entry, or of a representation one of its topics lists, does not name a file in this device's organization whose status is [`Available`](/docs/reference/python-sdk/roboto/domain/files/record#roboto.domain.files.record.FileStatus.Available); or a session a declaration reuses is deleted before the call completes. Nothing is created.
- [`RobotoUnauthorizedException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoUnauthorizedException): The caller cannot create sessions on this device, or cannot edit a file a declaration declares topics on, a file it anchors, or a file a listed representation names, or lacks topic edit access in this device's organization while a declaration states `is_default_for_reads` on a timeline source.

**Usage**

Register two chunks of one recording as a single session, each chunk's topic data read from the chunk itself:

```python
import pathlib
from roboto.domain.datasets import Dataset
from roboto.domain.devices import Device
from roboto.domain.topics import CanonicalDataType, RepresentationStorageFormat
from roboto.experimental.ingest import (
    Field,
    McapLogTimeSource,
    RepresentationDeclaration,
    Schema,
    TopicDeclaration,
)
from roboto.experimental.sessions import SessionDeclaration, SessionFile
imu_schema = Schema(
    name="sensor_msgs/msg/Imu",
    fields=[
        Field(
            name="angular_velocity_x",
            data_type="float64",
            canonical_data_type=CanonicalDataType.Number,
        ),
    ],
)
dataset = Dataset.from_id("ds_12345")
device = Device.from_id("robot_001")
chunks = [pathlib.Path("recording/chunk_0000.mcap"), pathlib.Path("recording/chunk_0001.mcap")]
file_ids = dataset.upload_files(chunks)
batch = device.create_sessions(
    [
        SessionDeclaration(
            name="morning_drive",
            files=[
                SessionFile(
                    file_id=file_ids[chunks[0]],
                    topics=[
                        TopicDeclaration(
                            topic_name="/imu",
                            topic_schema=imu_schema,
                            timeline_sources=[
                                McapLogTimeSource(
                                    min_file_timestamp_ns=1_785_974_400_000_000_000,
                                    max_file_timestamp_ns=1_785_974_404_000_000_000,
                                ),
                            ],
                            representations=[
                                RepresentationDeclaration(
                                    file_id=file_ids[chunks[0]],
                                    storage_format=RepresentationStorageFormat.MCAP,
                                ),
                            ],
                        ),
                    ],
                ),
                SessionFile(
                    file_id=file_ids[chunks[1]],
                    topics=[
                        TopicDeclaration(
                            topic_name="/imu",
                            topic_schema=imu_schema,
                            timeline_sources=[
                                McapLogTimeSource(
                                    min_file_timestamp_ns=1_785_974_404_000_000_000,
                                    max_file_timestamp_ns=1_785_974_408_000_000_000,
                                ),
                            ],
                            representations=[
                                RepresentationDeclaration(
                                    file_id=file_ids[chunks[1]],
                                    storage_format=RepresentationStorageFormat.MCAP,
                                ),
                            ],
                        ),
                    ],
                ),
            ],
        ),
    ],
)
batch.failed
# []
```

#### Device.create_token()

```python
def create_token(
    expiry_days: int = 366,
    name: Optional[str] = None,
    description: Optional[str] = None,
    api_scopes: Optional[collections.abc.Collection[roboto.auth.scope.ApiScope]] = None,
) -> tuple[roboto.domain.tokens.Token, str]
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L643-L698)

Create an access token that makes requests as this device.

Roboto returns the token's secret only in this response; it cannot be fetched again, so store it.

**Parameters**

- **expiry_days** (`int`): Number of days the token stays valid, counted from its creation.
- **name** (`Optional[str]`): Human-readable name of the token. `None` names it `<org_id>_<device_id>`.
- **description** (`Optional[str]`): Human-readable description of the token.
- **api_scopes** (`Optional[collections.abc.Collection[roboto.auth.scope.ApiScope]]`): API scopes the token is limited to. `None` or an empty collection grants every scope. The token cannot be granted more than the credential creating it holds.

**Returns**

- `tuple[roboto.domain.tokens.Token, str]`: `(token, secret)`: the new token and its secret.

**Usage**

Create a token that expires in 366 days:

```python
device = Device.from_id("robot_001", org_id="og_12345")
token, secret = device.create_token()
```

Create a token that expires in 30 days, with a name and description:

```python
token, secret = device.create_token(
    expiry_days=30, name="Monthly Upload Token", description="Token for automated monthly data uploads"
)
```

#### Device.delete()

```python
def delete(keep_configurations: bool = False) -> None
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L700-L740)

Delete the device, with its access tokens and its configurations. This cannot be undone.

The device's tokens are deleted with it. Its `configurations` are deleted shortly after this call returns, every version of each file. With `keep_configurations=True` they move to the organization's assets ([`assets`](/docs/reference/python-sdk/roboto/domain/orgs/org#roboto.domain.orgs.org.Org.assets)) instead, under `devices/<universal_device_id>/`, keeping their file IDs and every version. Links among the device's configurations are deleted in both cases, and the files they point at are left alone.

Shortly after this call returns, Roboto also clears the device's ID from the `device_id` of the organization's datasets and of every version of its files, unless a device with the same ID is created in the organization before then.

Deleting a device that no longer exists succeeds and changes nothing.

**Parameters**

- **keep_configurations** (`bool`): Whether to move the device's configurations to the organization's assets instead of deleting them.

**Raises**

- [`RobotoUnauthorizedException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoUnauthorizedException): `keep_configurations` is `True` and the caller cannot upload files to the organization.
- [`RobotoConflictException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoConflictException): `keep_configurations` is `True` and the organization's assets hold a file, not a directory, at `devices` or `devices/<universal_device_id>`.

**Returns**

- `None`

**Usage**

Delete a device and its configurations:

```python
device = Device.from_id("old_robot_001")
device.delete()
```

Delete a device but keep its configurations in the organization's assets:

```python
device = Device.from_id("old_robot_002")
device.delete(keep_configurations=True)
```

#### Device.for_org()

```python
@classmethod
def for_org(
    org_id: str,
    roboto_client: Optional[roboto.http.RobotoClient] = None,
) -> collections.abc.Generator[Device, None, None]
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L141-L181)

List the devices of an organization.

Fetches the devices a page at a time, as the generator is iterated.

**Parameters**

- **org_id** (`str`): ID of the organization whose devices to list.
- **roboto_client** (`Optional[roboto.http.RobotoClient]`): Client to make requests to Roboto with. Defaults to one configured from the environment, by [`from_env()`](/docs/reference/python-sdk/roboto/http/roboto_client#roboto.http.roboto_client.RobotoClient.from_env).

**Returns**

- `collections.abc.Generator[Device, None, None]`

**Usage**

Print the ID of every device in an organization:

```python
for device in Device.for_org("og_12345"):
    print(device.device_id)
```

Count the devices in an organization:

```python
device_count = sum(1 for _ in Device.for_org("og_12345"))
```

#### Device.from_id()

```python
@classmethod
def from_id(
    device_id: str,
    roboto_client: Optional[roboto.http.RobotoClient] = None,
    org_id: Optional[str] = None,
) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L184-L213)

Fetch a device by its ID.

**Parameters**

- **device_id** (`str`): ID the organization gave the device when creating it.
- **roboto_client** (`Optional[roboto.http.RobotoClient]`): Client to make requests to Roboto with. Defaults to one configured from the environment, by [`from_env()`](/docs/reference/python-sdk/roboto/http/roboto_client#roboto.http.roboto_client.RobotoClient.from_env).
- **org_id** (`Optional[str]`): Organization that owns the device. Required when the caller belongs to more than one organization; otherwise the caller's only organization.

**Raises**

- [`RobotoNotFoundException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoNotFoundException): The organization has no device with this ID.

**Returns**

- `Device`

**Usage**

```python
device = Device.from_id("robot_001", org_id="og_12345")
device.org_id
# 'og_12345'
```

#### Device.list_sessions()

```python
def list_sessions() -> collections.abc.Generator[roboto.experimental.sessions.Session, None, None]
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L743-L772)

List the sessions on this device.

Fetches the sessions a page at a time, as the generator is iterated.

**Usage**

Print the name of every session on a device:

```python
device = Device.from_id("robot_001", org_id="og_12345")
for session in device.list_sessions():
    print(session.name)
```

**Returns**

- `collections.abc.Generator[roboto.experimental.sessions.Session, None, None]`

#### Device.put_metadata()

```python
def put_metadata(metadata: dict[str, Any]) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L774-L791)

Set metadata keys on the device, adding new keys and overwriting existing ones.

Keys the dict does not name keep their values.

**Parameters**

- **metadata** (`dict[str, Any]`): Key-value metadata to set on the device.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Usage**

```python
device = Device.from_id("robot_001")
updated_device = device.put_metadata({"firmware_version": "2.1.0", "location": "warehouse-b"})
print(updated_device.metadata["firmware_version"])
# 2.1.0
```

#### Device.put_tags()

```python
def put_tags(tags: list[str]) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L793-L810)

Add tags to the device, keeping its existing tags.

A tag the device already has is not added again.

**Parameters**

- **tags** (`list[str]`): Tags to add to the device.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Usage**

```python
device = Device.from_id("robot_001")
updated_device = device.put_tags(["production", "warehouse-c"])
print("production" in updated_device.tags)
# True
```

#### Device.remove_metadata()

```python
def remove_metadata(keys: list[str]) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L812-L825)

Remove metadata keys from the device.

**Parameters**

- **keys** (`list[str]`): Metadata keys to remove.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Usage**

```python
device = Device.from_id("robot_001")
updated_device = device.remove_metadata(["old_field", "deprecated_key"])
```

#### Device.remove_tags()

```python
def remove_tags(tags: list[str]) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L827-L840)

Remove tags from the device.

**Parameters**

- **tags** (`list[str]`): Tags to remove from the device.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Usage**

```python
device = Device.from_id("robot_001")
updated_device = device.remove_tags(["old_tag", "deprecated"])
```

#### Device.set_custom_field()

```python
def set_custom_field(name: str, value: Any) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L869-L888)

Set one custom-field value on the device.

**Parameters**

- **name** (`str`): Name of a custom field defined for devices in the device's organization, with status [`Ready`](/docs/reference/python-sdk/roboto/domain/custom_fields/record#roboto.domain.custom_fields.record.CustomFieldStatus.Ready).
- **value** (`Any`): Value to set, which must match the field's declared type.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Raises**

- [`RobotoIllegalArgumentException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoIllegalArgumentException): `name` is not a ready custom field for devices, or `value` does not match its type.

**Usage**

```python
device = Device.from_id("robot_001")
device = device.set_custom_field("firmware_version", "2.1.0")
```

#### Device.set_custom_fields()

```python
def set_custom_fields(fields: dict[str, Any]) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L911-L930)

Set several custom-field values on the device. Fields not named keep their values.

**Parameters**

- **fields** (`dict[str, Any]`): New values keyed by field name. Each name must be a custom field defined for devices in the device's organization, with status [`Ready`](/docs/reference/python-sdk/roboto/domain/custom_fields/record#roboto.domain.custom_fields.record.CustomFieldStatus.Ready), and each value must match that field's declared type.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Raises**

- [`RobotoIllegalArgumentException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoIllegalArgumentException): A name is not a ready custom field for devices, or a value does not match its field's type.

**Usage**

```python
device = Device.from_id("robot_001")
device = device.set_custom_fields({"firmware_version": "2.1.0", "site": "warehouse-b"})
```

#### Device.set_device_type()

```python
def set_device_type(device_type_id: Optional[str]) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L842-L866)

Assign a device type to the device, or remove its type.

The device's own configurations are unaffected. Listing them with `include_inherited=True` afterwards includes the new type's configurations, or only the device's own when the type was removed.

**Parameters**

- **device_type_id** (`Optional[str]`): ID of a device type in the device's organization, beginning with `dt_`. `None` removes the device's type.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Raises**

- [`RobotoInvalidRequestException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoInvalidRequestException): `device_type_id` is not `None` and the organization has no such device type.

**Usage**

```python
device = Device.from_id("robot_001")
device.set_device_type("dt_12345").device_type_id
# 'dt_12345'
device.set_device_type(None).device_type_id is None
# True
```

#### Device.tokens()

```python
def tokens() -> collections.abc.Sequence[roboto.domain.tokens.Token]
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L951-L965)

Fetch the device's access tokens, expired ones included.

The tokens come without their secrets, which Roboto returns only from `create_token`. At most 1,000 tokens are returned.

**Usage**

```python
device = Device.from_id("robot_001")
for token in device.tokens():
    print(token.token_id)
```

**Returns**

- `collections.abc.Sequence[roboto.domain.tokens.Token]`

#### Device.update()

```python
def update(request: roboto.domain.devices.operations.UpdateDeviceRequest) -> Device
```

[Source](https://github.com/roboto-ai/roboto-python-sdk/blob/main/src/roboto/domain/devices/device.py#L967-L998)

Update the device's properties.

**Parameters**

- **request** (`roboto.domain.devices.operations.UpdateDeviceRequest`): Changes to apply. Each field left at its default leaves that property unchanged.

**Returns**

- `Device`: A new `Device` holding the updated record. This instance keeps its earlier record.

**Raises**

- [`RobotoInvalidRequestException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoInvalidRequestException): `request.device_type_id` names no device type in the organization.
- [`RobotoIllegalArgumentException`](/docs/reference/python-sdk/roboto/exceptions/domain#roboto.exceptions.domain.RobotoIllegalArgumentException): The custom-field changeset names a field that is not a ready custom field for devices, or sets a value that does not match its field's type.

**Usage**

```python
from roboto.domain.devices import UpdateDeviceRequest
from roboto.updates import MetadataChangeset
device = Device.from_id("robot_001")
updated_device = device.update(
    UpdateDeviceRequest(
        metadata_changeset=MetadataChangeset(
            put_fields={"version": "2.0"}, put_tags=["updated"], remove_tags=["old"]
        )
    )
)
```
