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

# Sensores IoT

> Lee datos climáticos de los sensores IoT de Rhombus a través de la API para monitorear temperatura, humedad, calidad del aire y condiciones ambientales en tus instalaciones.

<Note>
  Esta página fue traducida automáticamente. Si encuentra errores o tiene sugerencias, [contáctenos](mailto:support@rhombus.com).
</Note>

## Descripción general

Los sensores IoT de Rhombus (serie E) monitorean continuamente las condiciones ambientales en tus instalaciones. Estos sensores capturan temperatura, humedad, calidad del aire interior (IAQ), niveles de CO2, TVOC y PM2.5, y reportan los datos a la plataforma de Rhombus a través de gateways ambientales.

A través de la API, puedes:

* **Listar sensores** y obtener sus lecturas actuales
* **Consultar datos históricos** para análisis de tendencias y reportes
* **Configurar sensores** actualizando descripciones, ubicaciones y asociaciones de cámaras
* **Establecer políticas de alerta climática** que se activan cuando las lecturas cruzan umbrales definidos
* **Monitorear gateways** que transmiten los datos de los sensores a la nube
* **Exportar datos** como CSV para herramientas de análisis externas

## Requisitos previos

<Note>
  Antes de comenzar, asegúrate de tener:

  * Una **API key de Rhombus** con permisos de sensores (generada en la Consola de Rhombus en Settings > API)
  * Al menos un **sensor ambiental de la serie E** desplegado y conectado a un gateway ambiental
  * Una **ubicación configurada** donde estén instalados tus sensores
</Note>

## Listar todos los sensores

Obtén el estado actual de cada sensor climático en tu organización. Esto devuelve el UUID de cada sensor, su nombre, lecturas actuales, nivel de batería y estado de salud.

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  response = requests.post(
      "https://api2.rhombussystems.com/api/climate/getMinimalClimateStateList",
      headers=headers,
      json={}
  )

  data = response.json()
  for sensor in data.get("climateStates", []):
      name = sensor.get("name", "Unnamed")
      temp_c = sensor.get("temperatureCelcius")
      humidity = sensor.get("humidity")
      iaq = sensor.get("iaq")
      battery = sensor.get("batteryPercent")
      temp_f = round(temp_c * 9 / 5 + 32, 1) if temp_c else None
      print(f"{name}: {temp_f}°F, {humidity}% RH, IAQ {iaq}, Battery {battery}%")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api2.rhombussystems.com/api/climate/getMinimalClimateStateList', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({})
  });

  const data = await response.json();
  for (const sensor of data.climateStates || []) {
    const tempF = sensor.temperatureCelcius
      ? (sensor.temperatureCelcius * 9 / 5 + 32).toFixed(1)
      : null;
    console.log(`${sensor.name}: ${tempF}°F, ${sensor.humidity}% RH, IAQ ${sensor.iaq}, Battery ${sensor.batteryPercent}%`);
  }
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/climate/getMinimalClimateStateList \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{}'
  ```
</CodeGroup>

La respuesta incluye un arreglo `climateStates`. Campos clave de cada sensor:

| Campo                | Tipo    | Descripción                                        |
| -------------------- | ------- | -------------------------------------------------- |
| `sensorUuid`         | string  | Identificador único del sensor                     |
| `name`               | string  | Nombre para mostrar (p. ej., "Server Room Sensor") |
| `temperatureCelcius` | float   | Temperatura actual en grados Celsius               |
| `humidity`           | float   | Porcentaje de humedad relativa                     |
| `iaq`                | float   | Índice de calidad del aire interior                |
| `co2`                | float   | Nivel de CO2 en ppm                                |
| `tvoc`               | float   | Compuestos orgánicos volátiles totales             |
| `pm25`               | float   | Material particulado PM2.5                         |
| `batteryPercent`     | integer | Nivel de batería (0-100)                           |
| `health`             | string  | Estado de salud del sensor (`GREEN` o `RED`)       |
| `locationUuid`       | string  | Ubicación a la que está asignado el sensor         |

<Tip>
  La temperatura se devuelve en grados Celsius. Para convertir a Fahrenheit: `°F = °C × 9/5 + 32`.
</Tip>

## Leer datos del sensor

Consulta eventos climáticos históricos de un sensor específico en un rango de tiempo. Cada evento representa un punto de datos con temperatura, humedad, calidad del aire y otras lecturas ambientales.

<CodeGroup>
  ```python Python theme={null}
  import requests
  import time

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  # Consulta las últimas 24 horas de datos
  now_ms = int(time.time() * 1000)
  one_day_ago_ms = now_ms - (24 * 60 * 60 * 1000)

  response = requests.post(
      "https://api2.rhombussystems.com/api/climate/getClimateEventsForSensor",
      headers=headers,
      json={
          "sensorUuid": "YOUR_SENSOR_UUID",
          "createdAfterMs": one_day_ago_ms,
          "createdBeforeMs": now_ms,
          "limit": 100
      }
  )

  data = response.json()
  for event in data.get("climateEvents", []):
      temp_c = event.get("temp")
      humidity = event.get("humidity")
      timestamp = event.get("timestampMs")
      temp_f = round(temp_c * 9 / 5 + 32, 1) if temp_c else None
      print(f"[{timestamp}] {temp_f}°F, {humidity}% RH")
  ```

  ```javascript JavaScript theme={null}
  const now = Date.now();
  const oneDayAgo = now - (24 * 60 * 60 * 1000);

  const response = await fetch('https://api2.rhombussystems.com/api/climate/getClimateEventsForSensor', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      sensorUuid: 'YOUR_SENSOR_UUID',
      createdAfterMs: oneDayAgo,
      createdBeforeMs: now,
      limit: 100
    })
  });

  const data = await response.json();
  for (const event of data.climateEvents || []) {
    const tempF = event.temp ? (event.temp * 9 / 5 + 32).toFixed(1) : null;
    console.log(`[${new Date(event.timestampMs).toISOString()}] ${tempF}°F, ${event.humidity}% RH`);
  }
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/climate/getClimateEventsForSensor \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{
      "sensorUuid": "YOUR_SENSOR_UUID",
      "createdAfterMs": 1712620800000,
      "createdBeforeMs": 1712707200000,
      "limit": 100
    }'
  ```
</CodeGroup>

Cada evento climático incluye estos campos:

| Campo           | Tipo    | Descripción                                      |
| --------------- | ------- | ------------------------------------------------ |
| `timestampMs`   | integer | Marca de tiempo del evento en milisegundos epoch |
| `temp`          | float   | Temperatura en grados Celsius en esta lectura    |
| `humidity`      | float   | Porcentaje de humedad relativa                   |
| `iaq`           | float   | Índice de calidad del aire interior              |
| `co2`           | float   | Concentración de CO2                             |
| `tvoc`          | float   | Compuestos orgánicos volátiles totales           |
| `pm25`          | float   | Material particulado PM2.5                       |
| `heatIndexDegF` | float   | Índice de calor calculado en grados Fahrenheit   |

<Note>
  El parámetro `limit` limita la cantidad de eventos devueltos. Si necesitas más puntos de datos de los que permite el límite, pagina ajustando la ventana de `createdAfterMs` y `createdBeforeMs`.
</Note>

## Configurar sensores

### Obtener la configuración del sensor

Obtén la configuración completa de un sensor específico, incluyendo sus ajustes de umbral y dispositivos asociados.

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  response = requests.post(
      "https://api2.rhombussystems.com/api/climate/getConfig",
      headers=headers,
      json={
          "uuid": "YOUR_SENSOR_UUID"
      }
  )

  config = response.json().get("config", {})
  print(config)
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api2.rhombussystems.com/api/climate/getConfig', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      uuid: 'YOUR_SENSOR_UUID'
    })
  });

  const data = await response.json();
  console.log(data.config);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/climate/getConfig \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{
      "uuid": "YOUR_SENSOR_UUID"
    }'
  ```
</CodeGroup>

### Actualizar los detalles del sensor

Actualiza la descripción de un sensor, su asignación de ubicación o sus asociaciones de cámaras. Los campos que incluyas con su correspondiente bandera `*Updated` establecida en `true` se modificarán; todos los demás permanecen sin cambios.

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  response = requests.post(
      "https://api2.rhombussystems.com/api/climate/updateDetails",
      headers=headers,
      json={
          "uuid": "YOUR_SENSOR_UUID",
          "description": "Server Room B - Rack 4 temperature and humidity monitor",
          "descriptionUpdated": True,
          "locationUuid": "YOUR_LOCATION_UUID",
          "locationUuidUpdated": True
      }
  )

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api2.rhombussystems.com/api/climate/updateDetails', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      uuid: 'YOUR_SENSOR_UUID',
      description: 'Server Room B - Rack 4 temperature and humidity monitor',
      descriptionUpdated: true,
      locationUuid: 'YOUR_LOCATION_UUID',
      locationUuidUpdated: true
    })
  });

  const data = await response.json();
  console.log(data);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/climate/updateDetails \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{
      "uuid": "YOUR_SENSOR_UUID",
      "description": "Server Room B - Rack 4 temperature and humidity monitor",
      "descriptionUpdated": true,
      "locationUuid": "YOUR_LOCATION_UUID",
      "locationUuidUpdated": true
    }'
  ```
</CodeGroup>

<Warning>
  Debes establecer la correspondiente bandera `*Updated` en `true` para cada campo que quieras cambiar. Por ejemplo, establecer `description` sin `descriptionUpdated: true` no tendrá ningún efecto.
</Warning>

## Configurar alertas climáticas

Las políticas climáticas definen reglas de umbral que activan alertas cuando las lecturas ambientales suben por encima o bajan por debajo de valores especificados. Crea una política y asóciala con sensores para recibir notificaciones.

### Crear una política climática

Este ejemplo crea una política que alerta cuando la temperatura supera los 80°F (26.7°C) o baja de los 40°F (4.4°C).

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  response = requests.post(
      "https://api2.rhombussystems.com/api/policy/createClimatePolicy",
      headers=headers,
      json={
          "policy": {
              "name": "Server Room Temperature Alert",
              "description": "Alert when server room temperature is outside safe operating range",
              "scheduledTriggers": [
                  {
                      "triggerSet": [
                          {
                              "activity": "TEMPERATURE_EXCEEDED_HIGH",
                              "threshold": 26.7
                          },
                          {
                              "activity": "TEMPERATURE_EXCEEDED_LOW",
                              "threshold": 4.4
                          },
                          {
                              "activity": "HUMIDITY_EXCEEDED_HIGH",
                              "threshold": 60.0
                          }
                      ]
                  }
              ]
          }
      }
  )

  data = response.json()
  print(f"Created policy: {data.get('policyUuid')}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api2.rhombussystems.com/api/policy/createClimatePolicy', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      policy: {
        name: 'Server Room Temperature Alert',
        description: 'Alert when server room temperature is outside safe operating range',
        scheduledTriggers: [
          {
            triggerSet: [
              {
                activity: 'TEMPERATURE_EXCEEDED_HIGH',
                threshold: 26.7
              },
              {
                activity: 'TEMPERATURE_EXCEEDED_LOW',
                threshold: 4.4
              },
              {
                activity: 'HUMIDITY_EXCEEDED_HIGH',
                threshold: 60.0
              }
            ]
          }
        ]
      }
    })
  });

  const data = await response.json();
  console.log(`Created policy: ${data.policyUuid}`);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/policy/createClimatePolicy \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{
      "policy": {
        "name": "Server Room Temperature Alert",
        "description": "Alert when server room temperature is outside safe operating range",
        "scheduledTriggers": [
          {
            "triggerSet": [
              {
                "activity": "TEMPERATURE_EXCEEDED_HIGH",
                "threshold": 26.7
              },
              {
                "activity": "TEMPERATURE_EXCEEDED_LOW",
                "threshold": 4.4
              },
              {
                "activity": "HUMIDITY_EXCEEDED_HIGH",
                "threshold": 60.0
              }
            ]
          }
        ]
      }
    }'
  ```
</CodeGroup>

<Tip>
  Los valores de umbral para los activadores de temperatura usan grados Celsius. Convierte tus valores objetivo de Fahrenheit antes de crear la política: `°C = (°F - 32) × 5/9`.
</Tip>

### Listar políticas climáticas

Obtén todas las políticas climáticas configuradas para tu organización.

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  response = requests.post(
      "https://api2.rhombussystems.com/api/policy/getClimatePolicies",
      headers=headers,
      json={}
  )

  data = response.json()
  for policy in data.get("policies", []):
      print(f"{policy.get('name')}: {policy.get('uuid')}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api2.rhombussystems.com/api/policy/getClimatePolicies', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({})
  });

  const data = await response.json();
  for (const policy of data.policies || []) {
    console.log(`${policy.name}: ${policy.uuid}`);
  }
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/policy/getClimatePolicies \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{}'
  ```
</CodeGroup>

## Gateways ambientales

Los gateways ambientales son los hubs de hardware que reciben datos de los sensores de la serie E cercanos vía Bluetooth y los transmiten a la nube de Rhombus. Cada gateway admite múltiples sensores y se conecta a través de tu red.

Usa el endpoint de estado del gateway para verificar la conectividad, las versiones de firmware y qué sensores está atendiendo cada gateway.

<CodeGroup>
  ```python Python theme={null}
  import requests

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  response = requests.post(
      "https://api2.rhombussystems.com/api/climate/getMinimalEnvironmentalGatewayStates",
      headers=headers,
      json={}
  )

  data = response.json()
  for gw in data.get("minimalEnvironmentalGatewayStates", []):
      print(f"Gateway: {gw.get('name')} ({gw.get('deviceUuid')})")
      print(f"  Health: {gw.get('healthStatus')}, Firmware: {gw.get('firmwareVersion')}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api2.rhombussystems.com/api/climate/getMinimalEnvironmentalGatewayStates', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({})
  });

  const data = await response.json();
  for (const gw of data.minimalEnvironmentalGatewayStates || []) {
    console.log(`Gateway: ${gw.name} (${gw.deviceUuid})`);
    console.log(`  Health: ${gw.healthStatus}, Firmware: ${gw.firmwareVersion}`);
  }
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/climate/getMinimalEnvironmentalGatewayStates \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{}'
  ```
</CodeGroup>

### Obtener eventos del gateway

Consulta eventos históricos de un gateway específico, como cambios de conectividad y registro de sensores.

<CodeGroup>
  ```python Python theme={null}
  import requests
  import time

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  now_ms = int(time.time() * 1000)
  one_week_ago_ms = now_ms - (7 * 24 * 60 * 60 * 1000)

  response = requests.post(
      "https://api2.rhombussystems.com/api/climate/getEventsForEnvironmentalGateway",
      headers=headers,
      json={
          "deviceUuid": "YOUR_GATEWAY_UUID",
          "createdAfterMs": one_week_ago_ms,
          "createdBeforeMs": now_ms
      }
  )

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const now = Date.now();
  const oneWeekAgo = now - (7 * 24 * 60 * 60 * 1000);

  const response = await fetch('https://api2.rhombussystems.com/api/climate/getEventsForEnvironmentalGateway', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      deviceUuid: 'YOUR_GATEWAY_UUID',
      createdAfterMs: oneWeekAgo,
      createdBeforeMs: now
    })
  });

  const data = await response.json();
  console.log(data);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/climate/getEventsForEnvironmentalGateway \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{
      "deviceUuid": "YOUR_GATEWAY_UUID",
      "createdAfterMs": 1712016000000,
      "createdBeforeMs": 1712620800000
    }'
  ```
</CodeGroup>

## Exportar datos del sensor

Exporta los datos del sensor climático como un archivo CSV para usarlos en hojas de cálculo, herramientas de análisis de datos o reportes de cumplimiento. Especifica un sensor y un rango de tiempo para descargar todas las lecturas registradas.

<CodeGroup>
  ```python Python theme={null}
  import requests
  import time

  headers = {
      "x-auth-scheme": "api-token",
      "x-auth-apikey": "YOUR_API_KEY",
      "Content-Type": "application/json"
  }

  # Exporta los últimos 30 días de datos
  now_ms = int(time.time() * 1000)
  thirty_days_ago_ms = now_ms - (30 * 24 * 60 * 60 * 1000)

  response = requests.post(
      "https://api2.rhombussystems.com/api/export/climateEvents",
      headers=headers,
      json={
          "sensorUuid": "YOUR_SENSOR_UUID",
          "createdAfterMs": thirty_days_ago_ms,
          "createdBeforeMs": now_ms
      }
  )

  # La respuesta es data CSV
  with open("climate_export.csv", "w") as f:
      f.write(response.text)
  print("Exported climate data to climate_export.csv")
  ```

  ```javascript JavaScript theme={null}
  const now = Date.now();
  const thirtyDaysAgo = now - (30 * 24 * 60 * 60 * 1000);

  const response = await fetch('https://api2.rhombussystems.com/api/export/climateEvents', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-auth-scheme': 'api-token',
      'x-auth-apikey': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
      sensorUuid: 'YOUR_SENSOR_UUID',
      createdAfterMs: thirtyDaysAgo,
      createdBeforeMs: now
    })
  });

  // La respuesta es texto CSV
  const csvData = await response.text();
  console.log(csvData);
  ```

  ```bash cURL theme={null}
  curl -X POST https://api2.rhombussystems.com/api/export/climateEvents \
    -H "Content-Type: application/json" \
    -H "x-auth-scheme: api-token" \
    -H "x-auth-apikey: YOUR_API_KEY" \
    -d '{
      "sensorUuid": "YOUR_SENSOR_UUID",
      "createdAfterMs": 1710028800000,
      "createdBeforeMs": 1712620800000
    }' \
    -o climate_export.csv
  ```
</CodeGroup>

<Note>
  El endpoint de exportación devuelve datos CSV directamente en el cuerpo de la respuesta, no JSON. Usa la bandera `-o` en cURL o escribe el texto de la respuesta en un archivo en tu aplicación.
</Note>

También puedes exportar eventos del gateway ambiental con el mismo patrón usando `/api/export/environmentalGatewayEvents`.

## Próximos pasos

<CardGroup cols={2}>
  <Card title="Monitoreo de alarmas" icon="bell" href="/es/implementations/alarm-monitoring">
    Configura respuestas automáticas de alerta cuando los umbrales de los sensores activen alarmas
  </Card>

  <Card title="Notificaciones de webhook" icon="webhook" href="/es/webhooks">
    Recibe notificaciones push en tiempo real cuando las lecturas de los sensores crucen umbrales
  </Card>
</CardGroup>
