> ## Documentation Index
> Fetch the complete documentation index at: https://avala.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Frota API

> Referência de API REST para recursos de gerenciamento de frota

REST API: endpoints para gerenciar dispositivos, gravações, eventos, regras e alertas em toda a sua frota. Todos os endpoints exigem autenticação por meio de chave de API.

> [!WARNING]
>
> A API do Fleet está em versão preliminar (preview). Os endpoints descritos nesta página podem mudar.

## URL base

Todas as requisições da API do Fleet usam a URL base padrão da Avala API:

```
https://api.avala.ai/api/v1/fleet
```

Autentique cada requisição com sua chave de API no cabeçalho `X-Avala-Api-Key`. Consulte [Autenticação](https://avala.ai/docs/pt/api-reference/authentication.md) para saber como criar e gerenciar chaves.

***

## Dispositivos

Registre, liste e gerencie os dispositivos da sua frota.

### Listar dispositivos

```
GET /api/v1/fleet/devices/
```

Retorna todos os dispositivos da sua organização.

**Parâmetros de consulta**

| Parâmetro | Tipo | Descrição |
| - | - | - |
| `status` | string | Filtra por status do dispositivo: `online`, `offline`, `maintenance` |
| `type` | string | Filtra por tipo de dispositivo (por exemplo, `manipulator`, `amr`, `vehicle`) |
| `tags` | string | Filtro de tags separadas por vírgula |
| `metadata` | string | Filtro de metadados codificado em JSON (por exemplo, `{"location": "warehouse-1"}`) |
| `limit` | integer | Resultados por página (padrão: `50`, máximo: `200`) |
| `cursor` | string | Cursor de paginação |

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/devices/?status=online" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
from avala import Client

client = Client(api_key="your-api-key")

devices = client.fleet.devices.list(status="online")
for device in devices:
    print(device.name, device.status)
```

```typescript TypeScript SDK theme={null}
import Avala from "@avala-ai/sdk";

const avala = new Avala({ apiKey: "your-api-key" });

const devices = await avala.fleet.devices.list({ status: "online" });
for (const device of devices.items) {
  console.log(device.name, device.status);
}
```

**Resposta**

```json theme={null}
{
  "next": "https://api.avala.ai/api/v1/fleet/devices/?cursor=eyJpZCI6MTB9",
  "previous": null,
  "results": [
    {
      "uid": "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "name": "robot-alpha-01",
      "type": "amr",
      "status": "online",
      "tags": ["warehouse", "floor-2"],
      "last_seen_at": "2026-02-26T14:30:00Z",
      "firmware_version": "2.4.1",
      "metadata": {
        "model": "AMR-500",
        "location": "Building A"
      },
      "created_at": "2025-11-01T08:00:00Z",
      "updated_at": "2026-02-26T14:30:00Z"
    }
  ]
}
```

### Registrar dispositivo

```
POST /api/v1/fleet/devices/
```

Registre um novo dispositivo na sua frota.

**Corpo da requisição**

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `name` | string | Sim | Nome do dispositivo legível por humanos |
| `type` | string | Não | Tipo de dispositivo (por exemplo, `manipulator`, `amr`, `drone`) |
| `firmware_version` | string | Não | Versão atual do firmware |
| `tags` | array | Não | Tags para organizar dispositivos |
| `metadata` | objeto | Não | Metadados arbitrários de chave-valor |

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/fleet/devices/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "robot-alpha-02",
    "tags": ["warehouse", "floor-1"],
    "metadata": {
      "model": "AMR-500",
      "location": "Building A"
    }
  }'
```

```python Python SDK theme={null}
device = client.fleet.devices.register(
    name="robot-alpha-02",
    tags=["warehouse", "floor-1"],
    metadata={"model": "AMR-500", "location": "Building A"},
)
print(device.uid)
```

```typescript TypeScript SDK theme={null}
const device = await avala.fleet.devices.register({
  name: "robot-alpha-02",
  tags: ["warehouse", "floor-1"],
  metadata: { model: "AMR-500", location: "Building A" },
});
console.log(device.uid);
```

**Resposta** `201 Created`

```json theme={null}
{
  "uid": "dev_f7e8d9c0-b1a2-3456-cdef-789012345678",
  "name": "robot-alpha-02",
  "status": "offline",
  "tags": ["warehouse", "floor-1"],
  "last_seen_at": null,
  "firmware_version": null,
  "metadata": {
    "model": "AMR-500",
    "location": "Building A"
  },
  "device_token": "<redacted>",
  "created_at": "2026-02-26T15:00:00Z",
  "updated_at": "2026-02-26T15:00:00Z"
}
```

> [!WARNING]
>
> O `device_token` é retornado apenas na resposta de criação. Armazene-o com segurança -- ele não pode ser recuperado novamente. O dispositivo usa esse token para se autenticar ao enviar gravações.

### Obter dispositivo

```
GET /api/v1/fleet/devices/{uid}/
```

Retorna os detalhes completos de um único dispositivo.

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/devices/dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
device = client.fleet.devices.get("dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890")
```

```typescript TypeScript SDK theme={null}
const device = await avala.fleet.devices.get("dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890");
```

### Atualizar dispositivo

```
PATCH /api/v1/fleet/devices/{uid}/
```

Atualiza o nome, as tags ou os metadados de um dispositivo. Apenas os campos informados são modificados.

| Campo | Tipo | Descrição |
| - | - | - |
| `name` | string | Nome atualizado do dispositivo |
| `status` | string | Status do dispositivo: `online`, `offline`, `maintenance` |
| `firmware_version` | string | Versão atual do firmware |
| `tags` | array | Tags de substituição (substitui todas as tags existentes) |
| `metadata` | objeto | Metadados de substituição (mesclados com os existentes) |

```bash cURL theme={null}
curl -X PATCH "https://api.avala.ai/api/v1/fleet/devices/dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tags": ["warehouse", "floor-3"]}'
```

```python Python SDK theme={null}
device = client.fleet.devices.update(
    device_id="dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    tags=["warehouse", "floor-3"],
)
```

```typescript TypeScript SDK theme={null}
const device = await avala.fleet.devices.update({
  deviceId: "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  tags: ["warehouse", "floor-3"],
});
```

### Cancelar registro do dispositivo

```
DELETE /api/v1/fleet/devices/{uid}/
```

Remove um dispositivo da sua frota. As gravações associadas ao dispositivo não são excluídas.

```bash cURL theme={null}
curl -X DELETE "https://api.avala.ai/api/v1/fleet/devices/dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
client.fleet.devices.deregister(device_id="dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890")
```

```typescript TypeScript SDK theme={null}
await avala.fleet.devices.deregister({ deviceId: "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890" });
```

**Resposta** `204 No Content`

### Campos do dispositivo

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string | Identificador exclusivo do dispositivo |
| `name` | string | Nome legível por humanos |
| `type` | string | Tipo de dispositivo (por exemplo, `manipulator`, `amr`, `drone`) |
| `status` | string | `online`, `offline` ou `maintenance` |
| `tags` | array | Tags da organização |
| `last_seen_at` | string (ISO 8601) | Carimbo de data/hora do último heartbeat |
| `firmware_version` | string | Versão de firmware informada |
| `metadata` | objeto | Metadados arbitrários de chave-valor |
| `created_at` | string (ISO 8601) | Carimbo de data/hora do registro |
| `updated_at` | string (ISO 8601) | Carimbo de data/hora da última atualização |

***

## Gravações

Liste, filtre e gerencie as gravações enviadas pelos dispositivos da frota.

### Listar gravações

```
GET /api/v1/fleet/recordings/
```

Retorna as gravações de toda a sua frota, ordenadas por data de criação em ordem decrescente.

**Parâmetros de consulta**

| Parâmetro | Tipo | Descrição |
| - | - | - |
| `device_id` | string | Filtra por UID do dispositivo |
| `status` | string | Filtra por status: `uploading`, `processing`, `ready`, `error`, `archived` |
| `since` | string (ISO 8601) | Retorna gravações criadas após este carimbo de data/hora |
| `until` | string (ISO 8601) | Retorna gravações criadas antes deste carimbo de data/hora |
| `tags` | string | Filtro de tags separadas por vírgula |
| `limit` | integer | Resultados por página (padrão: `50`, máximo: `200`) |
| `cursor` | string | Cursor de paginação |

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/recordings/?device_id=dev_a1b2c3d4&status=ready&since=2026-02-01T00:00:00Z" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
recordings = client.fleet.recordings.list(
    device_id="dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    status="ready",
    since="2026-02-01T00:00:00Z",
)
```

```typescript TypeScript SDK theme={null}
const recordings = await avala.fleet.recordings.list({
  deviceId: "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  status: "ready",
  since: "2026-02-01T00:00:00Z",
});
```

**Resposta**

```json theme={null}
{
  "next": null,
  "previous": null,
  "results": [
    {
      "uid": "rec_11223344-5566-7788-99aa-bbccddeeff00",
      "device_id": "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "device_name": "robot-alpha-01",
      "status": "ready",
      "duration_seconds": 342.5,
      "size_bytes": 1073741824,
      "topic_count": 12,
      "tags": ["mission-47", "outdoor"],
      "started_at": "2026-02-26T10:00:00Z",
      "ended_at": "2026-02-26T10:05:42Z",
      "created_at": "2026-02-26T10:06:00Z"
    }
  ]
}
```

### Obter gravação

```
GET /api/v1/fleet/recordings/{uid}/
```

Retorna os detalhes completos da gravação, incluindo a lista de tópicos e os metadados de processamento.

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/recordings/rec_11223344-5566-7788-99aa-bbccddeeff00/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
recording = client.fleet.recordings.get("rec_11223344-5566-7788-99aa-bbccddeeff00")
```

```typescript TypeScript SDK theme={null}
const recording = await avala.fleet.recordings.get("rec_11223344-5566-7788-99aa-bbccddeeff00");
```

**Resposta**

```json theme={null}
{
  "uid": "rec_11223344-5566-7788-99aa-bbccddeeff00",
  "device_id": "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "device_name": "robot-alpha-01",
  "status": "ready",
  "duration_seconds": 342.5,
  "size_bytes": 1073741824,
  "topic_count": 12,
  "tags": ["mission-47", "outdoor"],
  "topics": [
    {
      "name": "/camera/front/image",
      "schema": "sensor_msgs/Image",
      "message_count": 3425,
      "frequency_hz": 10.0
    },
    {
      "name": "/lidar/points",
      "schema": "sensor_msgs/PointCloud2",
      "message_count": 3425,
      "frequency_hz": 10.0
    }
  ],
  "started_at": "2026-02-26T10:00:00Z",
  "ended_at": "2026-02-26T10:05:42Z",
  "created_at": "2026-02-26T10:06:00Z"
}
```

### Atualizar gravação

```
PATCH /api/v1/fleet/recordings/{uid}/
```

Atualiza as tags ou o status de uma gravação.

| Campo | Tipo | Descrição |
| - | - | - |
| `tags` | array | Tags de substituição |
| `status` | string | Defina como `archived` para arquivar a gravação |

```bash cURL theme={null}
curl -X PATCH "https://api.avala.ai/api/v1/fleet/recordings/rec_11223344-5566-7788-99aa-bbccddeeff00/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tags": ["mission-47", "outdoor", "reviewed"]}'
```

```python Python SDK theme={null}
recording = client.fleet.recordings.update(
    recording_id="rec_11223344-5566-7788-99aa-bbccddeeff00",
    tags=["mission-47", "outdoor", "reviewed"],
)
```

```typescript TypeScript SDK theme={null}
const recording = await avala.fleet.recordings.update({
  recordingId: "rec_11223344-5566-7788-99aa-bbccddeeff00",
  tags: ["mission-47", "outdoor", "reviewed"],
});
```

### Excluir gravação

```
DELETE /api/v1/fleet/recordings/{uid}/
```

Exclui permanentemente uma gravação e todos os dados associados.

> [!WARNING]
>
> Esta ação é irreversível. Todos os dados da gravação, eventos e arquivos associados são removidos permanentemente.

```bash cURL theme={null}
curl -X DELETE "https://api.avala.ai/api/v1/fleet/recordings/rec_11223344-5566-7788-99aa-bbccddeeff00/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
client.fleet.recordings.delete("rec_11223344-5566-7788-99aa-bbccddeeff00")
```

```typescript TypeScript SDK theme={null}
await avala.fleet.recordings.delete("rec_11223344-5566-7788-99aa-bbccddeeff00");
```

**Resposta** `204 No Content`

### Campos da gravação

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string | Identificador exclusivo da gravação |
| `device_id` | string | UID do dispositivo que criou a gravação |
| `device_name` | string | Nome do dispositivo legível por humanos |
| `status` | string | `uploading`, `processing`, `ready`, `error` ou `archived` |
| `duration_seconds` | number | Duração da gravação em segundos |
| `size_bytes` | integer | Tamanho total do arquivo em bytes |
| `topic_count` | integer | Número de tópicos na gravação |
| `tags` | array | Tags da organização |
| `topics` | array | Detalhes dos tópicos (somente no endpoint de detalhes) |
| `started_at` | string (ISO 8601) | Carimbo de data/hora do início da gravação |
| `ended_at` | string (ISO 8601) | Carimbo de data/hora do fim da gravação |
| `created_at` | string (ISO 8601) | Carimbo de data/hora do envio |

***

## Eventos

Crie e consulte eventos de linha do tempo associados às gravações.

### Listar eventos

```
GET /api/v1/fleet/events/
```

Retorna os eventos de toda a sua frota, ordenados por carimbo de data/hora em ordem decrescente.

**Parâmetros de consulta**

| Parâmetro | Tipo | Descrição |
| - | - | - |
| `recording_id` | string | Filtra por UID da gravação |
| `device_id` | string | Filtra por UID do dispositivo |
| `type` | string | Filtra por tipo de evento: `error`, `warning`, `info`, `state_change`, `anomaly`, `custom` |
| `severity` | string | Filtra por severidade: `info`, `warning`, `error`, `critical` |
| `since` | string (ISO 8601) | Retorna eventos após este carimbo de data/hora |
| `until` | string (ISO 8601) | Retorna eventos antes deste carimbo de data/hora |
| `order_by` | string | Ordem de classificação: `timestamp` (crescente) ou `-timestamp` (decrescente, padrão) |
| `metadata_filter` | string | Consulta de metadados codificada em JSON (por exemplo, `{"motor_id": "joint_3"}`) |
| `tags` | string | Filtro de tags separadas por vírgula |
| `limit` | integer | Resultados por página (padrão: `50`, máximo: `200`) |
| `cursor` | string | Cursor de paginação |

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/events/?recording_id=rec_11223344&severity=error" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
events = client.fleet.events.list(
    recording_id="rec_11223344-5566-7788-99aa-bbccddeeff00",
    severity="error",
)
```

```typescript TypeScript SDK theme={null}
const events = await avala.fleet.events.list({
  recordingId: "rec_11223344-5566-7788-99aa-bbccddeeff00",
  severity: "error",
});
```

**Resposta**

```json theme={null}
{
  "next": null,
  "previous": null,
  "results": [
    {
      "uid": "evt_aabbccdd-eeff-0011-2233-445566778899",
      "recording_id": "rec_11223344-5566-7788-99aa-bbccddeeff00",
      "device_id": "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "type": "anomaly",
      "label": "LiDAR topic /lidar/points dropped 15 messages in 2s window",
      "severity": "error",
      "timestamp": "2026-02-26T10:03:22Z",
      "metadata": {
        "topic": "/lidar/points",
        "dropped_count": 15,
        "window_seconds": 2
      },
      "created_at": "2026-02-26T10:03:22Z"
    }
  ]
}
```

### Criar evento

```
POST /api/v1/fleet/events/
```

Cria um novo evento associado a uma gravação ou a um dispositivo.

**Corpo da requisição**

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `recording_id` | string | Sim | Gravação à qual associar o evento |
| `type` | string | Sim | `error`, `warning`, `info`, `state_change`, `anomaly` ou `custom` |
| `label` | string | Sim | Rótulo do evento legível por humanos |
| `timestamp` | string (ISO 8601) | Sim | Quando o evento ocorreu |
| `description` | string | Não | Descrição detalhada do evento |
| `duration_ms` | number | Não | Duração do evento em milissegundos (para eventos do tipo intervalo) |
| `tags` | array | Não | Tags para categorizar o evento |
| `metadata` | objeto | Não | Metadados arbitrários do evento |
| `severity` | string | Não | Substitui a severidade: `info`, `warning`, `error`, `critical`. O padrão é definido com base em `type`. |

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/fleet/events/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "recording_id": "rec_11223344-5566-7788-99aa-bbccddeeff00",
    "type": "anomaly",
    "label": "CPU usage exceeded 90% threshold",
    "timestamp": "2026-02-26T10:02:15Z",
    "metadata": {
      "cpu_percent": 93.2,
      "threshold": 90
    }
  }'
```

```python Python SDK theme={null}
event = client.fleet.events.create(
    recording_id="rec_11223344-5566-7788-99aa-bbccddeeff00",
    type="anomaly",
    label="CPU usage exceeded 90% threshold",
    timestamp="2026-02-26T10:02:15Z",
    metadata={"cpu_percent": 93.2, "threshold": 90},
)
```

```typescript TypeScript SDK theme={null}
const event = await avala.fleet.events.create({
  recordingId: "rec_11223344-5566-7788-99aa-bbccddeeff00",
  type: "anomaly",
  label: "CPU usage exceeded 90% threshold",
  timestamp: "2026-02-26T10:02:15Z",
  metadata: { cpu_percent: 93.2, threshold: 90 },
});
```

**Resposta** `201 Created`

### Criar eventos em lote

```
POST /api/v1/fleet/events/batch/
```

Cria vários eventos em uma única requisição. Aceita até 1.000 eventos. Os eventos são criados de forma atômica — se qualquer evento falhar na validação, nenhum é criado.

**Corpo da requisição**

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `recording_id` | string | Sim | Gravação à qual anexar os eventos |
| `events` | array | Sim | Array de objetos de evento (máximo de 1.000) |

Cada objeto de evento aceita os mesmos campos de `POST /api/v1/fleet/events/` (exceto `recording_id`, que é definido no nível superior).

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/fleet/events/batch/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "recording_id": "rec_11223344-5566-7788-99aa-bbccddeeff00",
    "events": [
      {"timestamp": "2026-02-26T10:02:15Z", "type": "error", "label": "Motor overtemp"},
      {"timestamp": "2026-02-26T10:02:20Z", "type": "state_change", "label": "Emergency stop"}
    ]
  }'
```

```python Python SDK theme={null}
events = client.fleet.events.create_batch(
    recording_id="rec_11223344-5566-7788-99aa-bbccddeeff00",
    events=[
        {"timestamp": "2026-02-26T10:02:15Z", "type": "error", "label": "Motor overtemp"},
        {"timestamp": "2026-02-26T10:02:20Z", "type": "state_change", "label": "Emergency stop"},
    ],
)
```

```typescript TypeScript SDK theme={null}
const result = await avala.fleet.events.createBatch({
  recordingId: "rec_11223344-5566-7788-99aa-bbccddeeff00",
  events: [
    { timestamp: "2026-02-26T10:02:15Z", type: "error", label: "Motor overtemp" },
    { timestamp: "2026-02-26T10:02:20Z", type: "state_change", label: "Emergency stop" },
  ],
});
```

**Resposta** `201 Created` — Retorna o array dos objetos de evento criados.

### Obter evento

```
GET /api/v1/fleet/events/{uid}/
```

### Excluir evento

```
DELETE /api/v1/fleet/events/{uid}/
```

**Resposta** `204 No Content`

### Campos do evento

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string | Identificador exclusivo do evento |
| `recording_id` | string | UID da gravação associada |
| `device_id` | string | Dispositivo que gerou o evento (derivado da gravação) |
| `type` | string | `error`, `warning`, `info`, `state_change`, `anomaly` ou `custom` |
| `label` | string | Rótulo do evento legível por humanos |
| `description` | string | Descrição detalhada do evento |
| `timestamp` | string (ISO 8601) | Quando o evento ocorreu |
| `duration_ms` | number | Duração do evento em milissegundos (pode ser nulo) |
| `tags` | array | Tags do evento |
| `metadata` | objeto | Metadados arbitrários |
| `severity` | string | `info`, `warning`, `error` ou `critical` |
| `created_at` | string (ISO 8601) | Carimbo de data/hora de criação no servidor |

***

## Regras

As regras de gravação definem condições que disparam eventos automaticamente, sinalizam gravações ou iniciam pipelines de processamento.

### Listar regras

```
GET /api/v1/fleet/rules/
```

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/rules/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
rules = client.fleet.rules.list()

# Filter by enabled status or condition type
rules = client.fleet.rules.list(enabled=True)
rules = client.fleet.rules.list(condition_type="threshold")
```

```typescript TypeScript SDK theme={null}
let rules = await avala.fleet.rules.list();

// Filter by enabled status or condition type
rules = await avala.fleet.rules.list({ enabled: true });
rules = await avala.fleet.rules.list({ conditionType: "threshold" });
```

**Parâmetros de consulta**

| Parâmetro | Tipo | Descrição |
| - | - | - |
| `enabled` | `boolean` | Filtra por status habilitada/desabilitada. |
| `condition_type` | `string` | Filtra por tipo de condição (`threshold`, `pattern`, `frequency`, `absence`, `composite`). |

**Resposta**

```json theme={null}
{
  "next": null,
  "previous": null,
  "results": [
    {
      "uid": "rul_00112233-4455-6677-8899-aabbccddeeff",
      "name": "Flag high CPU recordings",
      "description": "Flag any recording where CPU exceeds 90% for more than 10 seconds",
      "enabled": true,
      "condition": {
        "type": "threshold",
        "topic": "/diagnostics/cpu",
        "field": "data.aggregate_percent",
        "operator": "gt",
        "value": 90,
        "window": "10s"
      },
      "actions": [
        {
          "type": "tag",
          "value": "high-cpu"
        },
        {
          "type": "create_event",
          "event_type": "warning",
          "label": "CPU exceeded 90% for >10s"
        }
      ],
      "scope": null,
      "hit_count": 42,
      "last_hit_at": "2026-02-25T18:45:00Z",
      "created_at": "2026-01-15T09:00:00Z",
      "updated_at": "2026-02-20T11:30:00Z"
    }
  ]
}
```

### Criar regra

```
POST /api/v1/fleet/rules/
```

**Corpo da requisição**

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `name` | string | Sim | Nome da regra legível por humanos |
| `description` | string | Não | Descrição da finalidade da regra |
| `enabled` | boolean | Não | Se a regra está ativa (padrão: `true`) |
| `condition` | objeto | Sim | Condição de disparo (veja abaixo) |
| `actions` | array | Sim | Ações a executar quando a condição for atendida |
| `scope` | objeto | Não | Limita a regra a dispositivos ou grupos específicos. Contém arrays `device_ids` e/ou `group_ids`. |

**Tipos de condição**

| Tipo | Descrição | Campos obrigatórios |
| - | - | - |
| `threshold` | Dispara quando um campo de tópico excede um valor | `topic`, `field`, `operator`, `value`, `window` opcional |
| `pattern` | Dispara quando um campo de tópico corresponde a um padrão de regex | `topic`, `field`, `regex` |
| `frequency` | Dispara quando a contagem de eventos ultrapassa um limite em uma janela de tempo | `topic`, `count_operator`, `count`, `window` |
| `absence` | Dispara quando os dados esperados estão ausentes por um período | `topic`, `timeout` |
| `composite` | Combinação lógica de outras condições | `operator` (`and` ou `or`), `conditions` |

**Tipos de ação**

| Tipo | Descrição | Campos obrigatórios |
| - | - | - |
| `tag` | Adiciona uma tag à gravação | `value` |
| `create_event` | Cria um evento de linha do tempo | `event_type`, `label`, `severity` opcional |
| `flag_for_review` | Sinaliza a gravação para revisão manual | -- |
| `notify` | Envia uma notificação para um canal de alerta | `channel_id` |
| `auto_label` | Dispara um pipeline de rotulagem automática | `pipeline_id` |

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/fleet/rules/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "LiDAR dropout detection",
    "description": "Detect when LiDAR data is missing for more than 2 seconds",
    "condition": {
      "type": "absence",
      "topic": "/lidar/points",
      "timeout": "2s"
    },
    "actions": [
      {"type": "create_event", "event_type": "error", "label": "LiDAR data missing for >2s"},
      {"type": "tag", "value": "lidar-dropout"},
      {"type": "notify", "channel_id": "ch_aabb1122"}
    ]
  }'
```

```python Python SDK theme={null}
rule = client.fleet.rules.create(
    name="LiDAR dropout detection",
    description="Detect when LiDAR data is missing for more than 2 seconds",
    condition={
        "type": "absence",
        "topic": "/lidar/points",
        "timeout": "2s",
    },
    actions=[
        {"type": "create_event", "event_type": "error", "label": "LiDAR data missing for >2s"},
        {"type": "tag", "value": "lidar-dropout"},
        {"type": "notify", "channel_id": "ch_aabb1122"},
    ],
)
```

```typescript TypeScript SDK theme={null}
const rule = await avala.fleet.rules.create({
  name: "LiDAR dropout detection",
  description: "Detect when LiDAR data is missing for more than 2 seconds",
  condition: {
    type: "absence",
    topic: "/lidar/points",
    timeout: "2s",
  },
  actions: [
    { type: "create_event", eventType: "error", label: "LiDAR data missing for >2s" },
    { type: "tag", value: "lidar-dropout" },
    { type: "notify", channelId: "ch_aabb1122" },
  ],
});
```

**Resposta** `201 Created`

### Obter regra

```
GET /api/v1/fleet/rules/{uid}/
```

### Atualizar regra

```
PATCH /api/v1/fleet/rules/{uid}/
```

Atualiza o nome, a descrição, o estado de habilitação, a condição ou as ações de uma regra. Apenas os campos informados são modificados.

| Campo | Tipo | Descrição |
| - | - | - |
| `name` | string | Nome atualizado da regra |
| `description` | string | Descrição atualizada |
| `enabled` | boolean | Defina como `false` para desabilitar a regra e `true` para reabilitá-la |
| `condition` | objeto | Condição de disparo atualizada |
| `actions` | array | Lista atualizada de ações |

### Excluir regra

```
DELETE /api/v1/fleet/rules/{uid}/
```

**Resposta** `204 No Content`

### Campos da regra

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string | Identificador exclusivo da regra |
| `name` | string | Nome legível por humanos |
| `description` | string | Descrição da regra |
| `enabled` | boolean | Se a regra está ativa |
| `condition` | objeto | Condição de disparo |
| `actions` | array | Ações a executar |
| `scope` | objeto | Restringe a regra a dispositivos, grupos ou tags específicos (pode ser nulo) |
| `hit_count` | integer | Número total de vezes que a regra foi disparada |
| `last_hit_at` | string (ISO 8601) | Quando a regra foi disparada pela última vez (pode ser nulo) |
| `created_at` | string (ISO 8601) | Carimbo de data/hora de criação |
| `updated_at` | string (ISO 8601) | Carimbo de data/hora da última atualização |

***

## Alertas

Visualize e gerencie os alertas gerados por regras de gravação e limites de diagnóstico.

### Listar alertas

```
GET /api/v1/fleet/alerts/
```

Retorna os alertas ordenados por data de criação em ordem decrescente.

**Parâmetros de consulta**

| Parâmetro | Tipo | Descrição |
| - | - | - |
| `device_id` | string | Filtra por UID do dispositivo |
| `recording_id` | string | Filtra por UID da gravação |
| `rule_id` | string | Filtra por UID da regra |
| `channel_id` | string | Filtra por UID do canal de notificação |
| `status` | string | Filtra por status: `open`, `acknowledged`, `resolved` |
| `severity` | string | Filtra por severidade: `info`, `warning`, `error`, `critical` |
| `since` | string (ISO 8601) | Retorna alertas criados após este carimbo de data/hora |
| `until` | string (ISO 8601) | Retorna alertas criados antes deste carimbo de data/hora |
| `limit` | integer | Resultados por página (padrão: `50`, máximo: `200`) |
| `cursor` | string | Cursor de paginação |

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/alerts/?status=open&severity=error" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
alerts = client.fleet.alerts.list(status="open", severity="error")
```

```typescript TypeScript SDK theme={null}
const alerts = await avala.fleet.alerts.list({ status: "open", severity: "error" });
```

**Resposta**

```json theme={null}
{
  "next": null,
  "previous": null,
  "results": [
    {
      "uid": "alt_99887766-5544-3322-1100-ffeeddccbbaa",
      "rule_id": "rul_00112233-4455-6677-8899-aabbccddeeff",
      "rule_name": "LiDAR dropout detection",
      "device_id": "dev_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "device_name": "robot-alpha-01",
      "recording_id": "rec_11223344-5566-7788-99aa-bbccddeeff00",
      "severity": "error",
      "status": "open",
      "message": "LiDAR frequency dropped below 8 Hz",
      "triggered_at": "2026-02-26T10:03:22Z",
      "acknowledged_at": null,
      "resolved_at": null,
      "created_at": "2026-02-26T10:03:22Z"
    }
  ]
}
```

### Obter alerta

```
GET /api/v1/fleet/alerts/{uid}/
```

### Reconhecer alerta

```
POST /api/v1/fleet/alerts/{uid}/acknowledge/
```

Marca um alerta como reconhecido. Isso indica que alguém está ciente do problema e o está investigando.

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/fleet/alerts/alt_99887766-5544-3322-1100-ffeeddccbbaa/acknowledge/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
client.fleet.alerts.acknowledge(
    alert_id="alt_99887766-5544-3322-1100-ffeeddccbbaa",
    note="Investigating the issue"
)
```

```typescript TypeScript SDK theme={null}
await avala.fleet.alerts.acknowledge({
  alertId: "alt_99887766-5544-3322-1100-ffeeddccbbaa",
  note: "Investigating the issue",
});
```

**Resposta**

```json theme={null}
{
  "uid": "alt_99887766-5544-3322-1100-ffeeddccbbaa",
  "status": "acknowledged",
  "acknowledged_at": "2026-02-26T10:15:00Z",
  "acknowledged_by": "johndoe"
}
```

### Resolver alerta

```
POST /api/v1/fleet/alerts/{uid}/resolve/
```

Marca um alerta como resolvido. Opcionalmente, inclua uma nota de resolução.

**Corpo da requisição**

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `note` | string | Não | Nota de resolução descrevendo o que foi feito |

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/fleet/alerts/alt_99887766-5544-3322-1100-ffeeddccbbaa/resolve/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"note": "LiDAR sensor recalibrated and firmware updated to v2.4.2"}'
```

```python Python SDK theme={null}
client.fleet.alerts.resolve(
    alert_id="alt_99887766-5544-3322-1100-ffeeddccbbaa",
    note="LiDAR sensor recalibrated and firmware updated to v2.4.2",
)
```

```typescript TypeScript SDK theme={null}
await avala.fleet.alerts.resolve({
  alertId: "alt_99887766-5544-3322-1100-ffeeddccbbaa",
  note: "LiDAR sensor recalibrated and firmware updated to v2.4.2",
});
```

### Campos do alerta

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string | Identificador exclusivo do alerta |
| `rule_id` | string | Regra que disparou o alerta |
| `rule_name` | string | Nome da regra legível por humanos |
| `device_id` | string | Dispositivo associado ao alerta |
| `device_name` | string | Nome do dispositivo legível por humanos |
| `recording_id` | string | Gravação associada ao alerta (pode ser nulo) |
| `severity` | string | `info`, `warning`, `error` ou `critical` |
| `status` | string | `open`, `acknowledged` ou `resolved` |
| `message` | string | Descrição do alerta |
| `triggered_at` | string (ISO 8601) | Quando a condição do alerta foi atendida |
| `acknowledged_at` | string (ISO 8601) | Quando o alerta foi reconhecido (pode ser nulo) |
| `acknowledged_by` | string | Usuário que reconheceu o alerta (pode ser nulo) |
| `resolved_at` | string (ISO 8601) | Quando o alerta foi resolvido (pode ser nulo) |
| `duration` | string | Tempo calculado entre `triggered_at` e `resolved_at` (pode ser nulo) |
| `created_at` | string (ISO 8601) | Carimbo de data/hora de criação no servidor |

***

## Canais de alerta

Configure os destinos de notificação dos alertas.

### Listar canais

```
GET /api/v1/fleet/alerts/channels/
```

```bash cURL theme={null}
curl "https://api.avala.ai/api/v1/fleet/alerts/channels/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY"
```

```python Python SDK theme={null}
channels = client.fleet.alerts.channels.list()
```

```typescript TypeScript SDK theme={null}
const channels = await avala.fleet.alerts.channels.list();
```

**Resposta**

```json theme={null}
{
  "next": null,
  "previous": null,
  "results": [
    {
      "uid": "ch_aabb1122-3344-5566-7788-99aabbccddee",
      "name": "Engineering Slack",
      "type": "slack",
      "config": {
        "webhook_url": "https://hooks.slack.com/services/..."
      },
      "created_at": "2026-01-10T08:00:00Z"
    },
    {
      "uid": "ch_ffeeddcc-bbaa-9988-7766-554433221100",
      "name": "Ops Team Email",
      "type": "email",
      "config": {
        "recipients": ["ops@example.com"]
      },
      "created_at": "2026-01-10T08:30:00Z"
    }
  ]
}
```

### Criar canal

```
POST /api/v1/fleet/alerts/channels/
```

**Corpo da requisição**

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `name` | string | Sim | Nome de exibição do canal |
| `type` | string | Sim | Tipo de canal: `slack`, `email` ou `webhook` |
| `config` | objeto | Sim | Configuração específica do canal (veja abaixo) |

**Configuração do canal**

| Tipo | Campos de configuração |
| - | - |
| `slack` | `webhook_url` (obrigatório) -- URL do webhook de entrada do Slack; `channel` -- Substituição opcional do canal; `username` -- Nome de exibição opcional; `icon_emoji` -- Ícone de emoji opcional |
| `email` | `recipients` (obrigatório) -- Array de endereços de e-mail; `subject_prefix` -- Prefixo opcional do assunto do e-mail |
| `webhook` | `url` (obrigatório) -- URL do endpoint HTTP URL; `signing_secret` -- Segredo de assinatura HMAC opcional; `headers` -- Cabeçalhos personalizados opcionais |

```bash cURL theme={null}
curl -X POST "https://api.avala.ai/api/v1/fleet/alerts/channels/" \
  -H "X-Avala-Api-Key: $AVALA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Engineering Slack",
    "type": "slack",
    "config": {
      "webhook_url": "https://hooks.slack.com/services/T00/B00/xxx"
    }
  }'
```

```python Python SDK theme={null}
channel = client.fleet.alerts.channels.create(
    name="Engineering Slack",
    type="slack",
    config={"webhook_url": "https://hooks.slack.com/services/T00/B00/xxx"},
)
```

```typescript TypeScript SDK theme={null}
const channel = await avala.fleet.alerts.channels.create({
  name: "Engineering Slack",
  type: "slack",
  config: { webhook_url: "https://hooks.slack.com/services/T00/B00/xxx" },
});
```

**Resposta** `201 Created`

### Excluir canal

```
DELETE /api/v1/fleet/alerts/channels/{uid}/
```

> [!WARNING]
>
> Excluir um canal referenciado por regras ativas não exclui as regras. As regras continuam funcionando, mas a ação `notify` é ignorada para o canal excluído.

**Resposta** `204 No Content`

### Campos do canal

| Campo | Tipo | Descrição |
| - | - | - |
| `uid` | string | Identificador único do canal |
| `name` | string | Nome de exibição |
| `type` | string | `slack`, `email` ou `webhook` |
| `config` | objeto | Configuração específica do canal |
| `created_at` | string (ISO 8601) | Carimbo de data/hora de criação |

***

## Padrões comuns

### Paginação

Todos os endpoints de listagem usam paginação baseada em cursor. Siga o `next` URL até que ele retorne `null` para recuperar todos os resultados.

```json theme={null}
{
  "next": "https://api.avala.ai/api/v1/fleet/devices/?cursor=eyJpZCI6MTB9",
  "previous": null,
  "results": [...]
}
```

Use o parâmetro `limit` para controlar o tamanho da página. O máximo é de `200` resultados por página.

### Respostas de erro

A API da Fleet usa respostas de erro Avala padrão. Consulte [Códigos de erro](https://avala.ai/docs/pt/api-reference/errors.md) para a referência completa.

| Status | Descrição |
| - | - |
| `400` | Requisição inválida -- campos inválidos ou ausentes |
| `401` | Não autorizado -- chave de API ausente ou inválida |
| `403` | Proibido -- permissões insuficientes |
| `404` | Não encontrado -- o recurso não existe |
| `409` | Conflito -- o recurso já existe (por exemplo, nome de dispositivo duplicado) |
| `429` | Excesso de requisições -- limite de taxa excedido |

### Limites de taxa

Os endpoints de API da Fleet compartilham os limites de taxa padrão de Avala. Consulte [Limites de taxa](https://avala.ai/docs/pt/api-reference/rate-limits.md) para mais detalhes.

## Recursos adicionais de SDK

Os recursos de frota a seguir estão disponíveis por meio dos SDKs de Python e TypeScript. A documentação dos endpoints de REST será adicionada à medida que esses recursos se estabilizarem.

| Recurso | Descrição | Guia |
| - | - | - |
| Grupos de dispositivos | Organize dispositivos em grupos lógicos para regras e métricas com escopo definido | [Painel da Fleet](https://avala.ai/docs/pt/visualization/fleet/fleet-dashboard.md) |
| Métricas da frota | Estatísticas agregadas da frota e telemetria em séries temporais | [Painel da Fleet](https://avala.ai/docs/pt/visualization/fleet/fleet-dashboard.md) |
| Políticas de escalonamento | Defina fluxos de trabalho de escalonamento de alertas em múltiplos estágios | [Alertas e notificações](https://avala.ai/docs/pt/visualization/fleet/alerts-and-notifications.md) |
| Silenciamento e adiamento de alertas | Suprima alertas durante janelas de manutenção | [Alertas e notificações](https://avala.ai/docs/pt/visualization/fleet/alerts-and-notifications.md) |

## Próximos passos

> [card]
>
> Painel da frotaMonitore sua frota visualmente com o painel de Mission Control.
>
> [Open](https://avala.ai/docs/pt/visualization/fleet/fleet-dashboard.md)

> [card]
>
> SDK PythonUse o SDK de Python para o gerenciamento programático da frota.
>
> [Open](https://avala.ai/docs/pt/sdks/python.md)

> [card]
>
> SDK TypeScriptUse o SDK de TypeScript para integrações com Node.js e navegador.
>
> [Open](https://avala.ai/docs/pt/sdks/typescript.md)
