> Documentation index: https://developers.home.google.com/apis/android/device/llms.txt

<br />

A camera with floodlight device, such as the Google Nest Cam with floodlight,
combines a camera and a wired floodlight mount into a single multipart
[`HomeDevice`](https://developers.home.google.com/reference/kotlin/com/google/home/HomeDevice.md.txt).

The camera component is implemented with the
[`GoogleCameraDevice`](https://developers.home.google.com/reference/kotlin/com/google/home/google/GoogleCameraDevice.md.txt)
device type using three primary streaming and snapshot traits:
[`PushAvStreamTransport`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransport.md.txt),
which handles audio and video stream transport using push-based protocols,
[`WebRtcLiveView`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveView.md.txt),
which controls livestreams and talkback, and
[`CameraSnapshot`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraSnapshot.md.txt),
which provides cached preview snapshots and live snapshot captures.

The floodlight component is implemented with the
[`DimmableLightDevice`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/DimmableLightDevice.md.txt)
and
[`OnOffLightDevice`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/OnOffLightDevice.md.txt)
device types using the standard Matter
[`OnOff`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/OnOff.md.txt) and
[`LevelControl`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/LevelControl.md.txt)
traits for power and brightness control, and the
[`CameraLighting`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraLighting.md.txt)
trait for motion triggers, camera event triggers, timer duration, and daylight
sensor sensitivity.

Always check for attribute and command support for a device prior to using any
features or attempting to update attributes. See [Control devices on
Android](https://developers.home.google.com/apis/android/device/control) for more
information.

> [!WARNING]
> **Warning:** The camera traits are restricted and not available for general use.

<br />


| Home APIs Device Type | Traits | Kotlin Sample App | Use Case |
|---|---|:---:|:---:|
| Dimmable Light `DimmableLightDevice` `home.matter.0000.types.0101` A lighting device that is capable of being switched on or off, the intensity of its light adjusted, and being switched by means of a bound occupancy sensor. | Required Traits matter [Identify](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/Identify.md.txt) matter [OnOff](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/OnOff.md.txt) matter [LevelControl](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/LevelControl.md.txt) Optional Traits google [LightEffects](https://developers.home.google.com/reference/kotlin/com/google/home/google/LightEffects.md.txt) | Yes on and off, brightness | [Light](https://developers.home.google.com/use-cases?device=light) |
| On/Off Light `OnOffLightDevice` `home.matter.0000.types.0100` A lighting device that is capable of being switched on or off. | Required Traits matter [Identify](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/Identify.md.txt) matter [OnOff](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/OnOff.md.txt) Optional Traits matter [LevelControl](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/LevelControl.md.txt) google [LightEffects](https://developers.home.google.com/reference/kotlin/com/google/home/google/LightEffects.md.txt) | Yes on and off, brightness | [Light](https://developers.home.google.com/use-cases?device=light) |
| Camera `GoogleCameraDevice` `home.matter.6006.types.0158` A device that captures still images or video. Cameras may feature accessible livestreams, two-way talkback, or detection events. | Required Traits google [PushAvStreamTransport](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransport.md.txt) google [WebRtcLiveView](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveView.md.txt) | Yes | [Camera](https://developers.home.google.com/use-cases?device=camera) |

<br />

> [!NOTE]
> **Note:** The Automation API doesn't support the camera streaming traits.

## Multipart support

When you query devices with
[multipart device support](https://developers.home.google.com/apis/android/device/multipart.md.txt) enabled
(`enableMultipartDevices = true`), a single `HomeDevice` exposes
`GoogleCameraDevice` alongside `DimmableLightDevice`, `OnOffLightDevice`, and
[`RootNodeDevice`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/RootNodeDevice.md.txt).

When inspecting devices in a structure, register both the camera and light
device types in your `FactoryRegistry` and check for each device type
independently:

```kotlin
// Register camera and light device types in FactoryRegistry
val registry = FactoryRegistry(
  devices = listOf(
    GoogleCameraDevice,
    DimmableLightDevice,
    OnOffLightDevice
  ),
  traits = listOf(
    WebRtcLiveView,
    CameraAvStreamManagement,
    PushAvStreamTransport,
    CameraLighting,
    OnOff,
    LevelControl
  )
)

// Query with enableMultipartDevices = true so composite devices are combined
home.devices(enableMultipartDevices = true).list().forEach { device ->
  if (device.has(GoogleCameraDevice)) {
    val cameraType = device.type(GoogleCameraDevice).first()
    // Access camera traits on cameraType.traits
  }
  if (device.has(DimmableLightDevice)) {
    val floodlightType = device.type(DimmableLightDevice).first()
    // Control floodlight power, brightness, and CameraLighting settings
  }
}
```

> [!NOTE]
> **Note:** If the floodlight mount is physically disconnected from the camera and later reconnected, the floodlight component receives a new component ID. Existing automations that reference the floodlight component must be recreated. See [Multipart device automations](https://developers.home.google.com/apis/android/automation/multipart.md.txt) for more information.

## Configure floodlight settings

On a Nest Cam with floodlight, use the standard `OnOff` and `LevelControl`
traits on the `DimmableLightDevice` component to turn the floodlight on or off
and adjust its brightness (from `0` to `254`). For more details on standard
light control commands, see the
[Light device guide](https://developers.home.google.com/apis/android/device/light.md.txt#control). Use the
`CameraLighting` trait on the `DimmableLightDevice` or `OnOffLightDevice`
component to configure automatic triggers, timer duration, and daylight sensor
sensitivity:

```kotlin
// Obtain the DimmableLightDevice component from the multipart HomeDevice
val floodlight = device.type(DimmableLightDevice).firstOrNull()

// Turn the floodlight on and set brightness to ~75% (190 out of 254)
floodlight?.standardTraits?.onOff?.on()
floodlight?.standardTraits?.levelControl?.moveToLevelWithOnOff(
  level = 190u,
  transitionTime = null,
  optionsMask = LevelControlTrait.OptionsBitmap(),
  optionsOverride = LevelControlTrait.OptionsBitmap()
)

// Access the CameraLighting trait for floodlight settings
val cameraLighting: CameraLighting? = floodlight?.trait(CameraLighting)
```

### Configure floodlight turn-on triggers

The floodlight can turn on automatically in response to built-in passive
infrared (PIR) motion detection, camera recording events, or live stream
viewing. Check `triggerEditable` to confirm which triggers can be modified on
the device:

| Attribute | Description |
|---|---|
| `lightPirTriggerEnabled` | Enables or disables turning on the floodlight when the built-in motion sensor detects motion. |
| `pirSensitivity` | Adjusts the range and sensitivity of the motion sensor (`PirSensitivityEnum.Low`, `PirSensitivityEnum.Medium`, or `PirSensitivityEnum.High`). This setting only applies when `lightPirTriggerEnabled` is `true`. When `lightPirTriggerEnabled` is `false`, `pirSensitivity` reports `PirSensitivityEnum.Unspecified`. Enabling `lightPirTriggerEnabled` without specifying `pirSensitivity` defaults the sensitivity to `PirSensitivityEnum.High`. |
| `cameraRecordingEventTriggerEnabled` | Turns on the floodlight when the camera starts recording an event. |
| `cameraLiveviewTriggerEnabled` | Turns on the floodlight when a user views the camera's livestream. |

> [!NOTE]
> **Note:** The `snoozeAutoTriggers` attribute is not supported on the Nest Cam with floodlight. Do not pass `Unspecified` when updating `pirSensitivity` or `ambientLightSensitivity`.

```kotlin
// Enable the motion trigger and set motion sensitivity to Medium
cameraLighting?.update {
  setLightPirTriggerEnabled(true)
  setPirSensitivity(CameraLightingTrait.PirSensitivityEnum.Medium)
}

// Turn on the floodlight for camera recording events and live viewing
cameraLighting?.update {
  setCameraRecordingEventTriggerEnabled(true)
  setCameraLiveviewTriggerEnabled(true)
}
```

### Set the floodlight timer

To control how long the floodlight remains on after a motion trigger activates
it, update the `pirTriggerDurationSeconds` attribute on the `CameraLighting`
trait. The Nest Cam with floodlight supports durations from `10u` (10
seconds) to `300u` (5 minutes), with standard presets of `10u`, `30u` (default),
`60u`, `180u`, and `300u`:

```kotlin
// Keep the floodlight on for 60 seconds after motion is detected
cameraLighting?.update {
  setPirTriggerDurationSeconds(60u)
}
```

### Adjust daylight sensor sensitivity

The ambient light sensor prevents automatic triggers from turning on the
floodlight during the day. To configure how dark it must be before automatic
triggers activate the floodlight, update the `ambientLightSensitivity` attribute
using `CameraLightingTrait.AmbientLightSensitivityEnum`:

- `UltraLow` activates only in the darkest conditions.
- `Low` activates in darker conditions.
- `Medium` is the default balanced threshold.
- `High` activates in brighter conditions (turns on earlier at dusk and stays active later at dawn).

```kotlin
// Set daylight sensor sensitivity to Medium
cameraLighting?.update {
  setAmbientLightSensitivity(
    CameraLightingTrait.AmbientLightSensitivityEnum.Medium
  )
}
```

## Get basic information about a device

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

The [`BasicInformation`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/BasicInformation.md.txt)
trait includes information like vendor name, vendor ID, product ID,
product name (includes model information), and software version for a device:

```
// Get device basic information. All general information traits are on the RootNodeDevice type.
    device.type(RootNodeDevice).first().standardTraits.basicInformation?.let { basicInformation ->
        println("vendorName ${basicInformation.vendorName}")
        println("vendorId ${basicInformation.vendorId}")
        println("productId ${basicInformation.productId}")
        println("productName ${basicInformation.productName}")
        println("softwareVersion ${basicInformation.softwareVersion}")
    }
```

## Get serial number

To obtain the serial number of the device, use the
[`GetSerialNumber` command](https://developers.home.google.com/reference/kotlin/com/google/home/google/ExtendedBasicInformationTrait.GetSerialNumberCommand.md.txt) of the
[`ExtendedBasicInformation`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ExtendedBasicInformation.md.txt) trait.
The example shows saving the serial number in a variable named `serialNumber`:

```kotlin
val basicInfo: ExtendedBasicInformation = device.getTrait(ExtendedBasicInformation)
val serialNumber = basicInfo.getSerialNumber().serialNumber
```

## Get the most recent time of device cloud contact

To find the most recent time that the device had contact with the cloud, use
the `lastContactTimestamp` attribute of the
[`ExtendedGeneralDiagnostics`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ExtendedGeneralDiagnostics.md.txt)
trait:

```kotlin
fun getLastContactTimeStamp(trait: ExtendedGeneralDiagnostics): java.time.Instant {
  val timestamp = trait.lastContactTimestamp
  return Instant.ofEpochSecond(timestamp.toLong())
}
```

## Camera mount type settings

The [`Mount`](https://developers.home.google.com/reference/kotlin/com/google/home/google/Mount.md.txt) trait contains
camera mount settings and status information. You can read attributes such
as the mount state, detection type, and mount type name. In addition,
you can use the `Mount` trait to override the default mount type configuration.

```kotlin
// Get the Mount trait
val mountTrait: Mount = device.getTrait(Mount)

// Read the current mount state and detection type
val mountState = mountTrait.mountState
val mountDetectionType = mountTrait.mountDetectionType

// Read the current mount type name
val mountTypeName = mountTrait.mountTypeName

// Update the mount type override
mountTrait.update {
  setMountTypeOverride(MountTrait.MountTypeOverrideEnum.Official)
}
```

## Check connectivity for a device

Connectivity for a device is actually checked at the device type level because
some devices support multiple device types. The state returned is a
combination of the connectivity states for all traits on that device.
[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

```kotlin
val cameraConnectivity = cameraDevice.metadata.sourceConnectivity.connectivityState
```

A state of `PARTIALLY_ONLINE` may be observed in the case
of mixed device types when there is no internet connectivity.
Matter standard traits may still be online due to local
routing, but cloud-based traits will be offline.

> [!IMPORTANT]
> **Important:** A device that has a `connectivityState` of [`PARTIALLY_ONLINE`](https://developers.home.google.com/reference/kotlin/com/google/home/ConnectivityState.md.txt#PARTIALLY_ONLINE) should be represented to the user as "Online."

### Get the IP address of the device

To find the IP address of the device, use the `networkInterfaces` attribute of
the
[`GeneralDiagnostics`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/GeneralDiagnostics.md.txt)
trait. The addresses are returned as byte arrays, which you can format to
standard IPv4 or IPv6 strings:

```kotlin
val ipAddresses =
  trait.networkInterfaces?.flatMap { networkInterface ->
    (networkInterface.ipv4Addresses + networkInterface.ipv6Addresses).mapNotNull { bytes ->
      try {
        java.net.InetAddress.getByAddress(bytes).hostAddress
      } catch (e: java.net.UnknownHostException) {
        null
      }
    }
  } ?: emptyList()
```

## Start a livestream

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

To start a livestream, send the Session Description Protocol (SDP) string
to the
[`WebRtcLiveView`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveView.md.txt)
trait's
[`startLiveView()`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveViewCommands.md.txt#startLiveView(kotlin.String)) method, which returns a
[`WebRtcLiveViewTrait.StartLiveViewCommand.Response`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveViewTrait.StartLiveViewCommand.Response.md.txt)
containing three values:

- The SDP for the session.
- The session duration in seconds.
- The session ID, which may be used to extend or terminate the session.

```kotlin
suspend fun getWebRtcLiveViewTrait(cameraDevice: HomeDevice) {
 return cameraDevice.type(GoogleCameraDevice).trait(WebRtcLiveView).first {
    it?.metadata?.sourceConnectivity?.connectivityState == ConnectivityState.ONLINE
  }

}

// Start the live view
suspend fun startCameraStream(trait: WebRtcLiveView, offerSdp: String) {
  val response = trait.startLiveView(offerSdp)
  // Response contains three fields (see below)
  return response
}
  ...

// This is used to manage the WebRTC connection
val peerConnection: RTCPeerConnection = ...

   ...

val startResponse = startCameraStream(sdp)
val answerSdp = startResponse?.answerSdp
val sessionDuration = startResponse?.liveSessionDurationSeconds
val mediaSessionId = startResponse?.mediaSessionId

peerConnection.setRemoteDescription(SessionDescription.Type.ANSWER,
                                    answerSdp)
```

### Extend a livestream

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

Livestreams have a preset duration after which they expire. To lengthen the
duration of an active stream, issue an extension request using the
[`WebRtcLiveView.extendLiveView()`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveViewCommands.md.txt#extendLiveView(kotlin.String,kotlin.Function1))
method:

```kotlin
// Assuming camera stream has just been started
suspend fun scheduleExtension(trait: WebRtcLiveView, mediaSessionId: String, liveSessionDurationSeconds: UShort ) {
  delay(liveSessionDurationSeconds - BUFFER_SECONDS * 1000)
  val response = trait.extendLiveView(mediaSessionId)
  // returns how long the session will be live for
  return response.liveSessionDurationSeconds
}
```

### Start and stop talkback

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

To start talkback, call the
[`WebRtcLiveView`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveView.md.txt)
trait's [`startTalkback()`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveViewCommands.md.txt#startTalkback(kotlin.String,kotlin.Function1))
method. To stop, use
[`stopTalkback()`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveViewCommands.md.txt#stopTalkback(kotlin.String)).

```kotlin
// Make sure camera stream is on
suspend fun setTalkback(isOn: Boolean, trait: WebRtcLiveView, mediaSessionId: String) {
  if(isOn) {
    trait.startTalkback(mediaSessionId)
  } else {
    trait.stopTalkback(mediaSessionId)
  }
}
```

## Manage livestream

Adjusting the livestream quality is useful to optimize bandwidth usage based on
the client's viewing context (for example, switching to a lower resolution
when displaying a smaller preview tile, grid view, or picture-in-picture mode).

Changing the quality dynamically by using the
[`WebRtcLiveView`](https://developers.home.google.com/reference/kotlin/com/google/home/google/WebRtcLiveView.md.txt)
trait specifically manages the resolution of the active livestream session
on a particular client. It is not the same as configuring a device-wide
bandwidth usage setting directly on the device, which would affect all
concurrent viewers and the quality of historical video recordings
saved to the cloud.

The following example demonstrates how to retrieve and update the livestream
quality for a device:

- Retrieve supported quality options: Get the available streaming resolutions
  supported by the device. The code queries the `WebRtcLiveView`
  trait's `supportedQualityHints` attribute on the device type flow and exposes
  the supported qualities as a `StateFlow` containing a list of `QualityHint`
  values (such as `QUALITY_HINT_SD`, `QUALITY_HINT_HD`, `QUALITY_HINT_FHD`,
  `QUALITY_HINT_QHD`, or `QUALITY_HINT_UHD`).

- Change the livestream quality: Apply a selected `QualityHint` to change
  the streaming resolution of the active livestream
  (for example, switching from Standard Definition to High Definition).
  The `changeQuality` function resolves the device's livestreaming trait
  and calls `changeLiveViewQuality` with the active `mediaSessionId`
  and the chosen `QualityHint` configuration.

```kotlin
// Assuming you have a HomeDevice instance 'device'
val availableQualityHints: StateFlow<List> =
    device.type(GoogleCameraDevice)
        .trait(WebRtcLiveView)
        .map { trait ->
            trait?.supportedQualityHints ?: emptyList()
        }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList())

// Assuming you have a HomeDevice instance 'device'
suspend fun changeQuality(mediaSessionId: String, qualityHint: QualityHint) {
    // Get the trait from the device
    val trait = device.type(GoogleCameraDevice).trait(WebRtcLiveView).first() ?: return
    try {
        trait.changeLiveViewQuality(mediaSessionId, qualityHint)
    } catch (e: Exception) {
        // Handle error
    }
}
```

## Enable and disable recording capability

To enable the camera's recording capability, pass
[`TransportStatusEnum.Active`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportStatusEnum.md.txt#Active)
to the
[`PushAvStreamTransport`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransport.md.txt)
trait's
[`setTransportStatus()`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportCommands.md.txt#setTransportStatus(com.google.home.google.PushAvStreamTransportTrait.TransportStatusEnum,kotlin.Function1))
method. To disable the recording capability, pass it
[`TransportStatusEnum.Inactive`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportStatusEnum.md.txt#Inactive).
In the following example, we wrap these calls in a single call that uses a
`Boolean` to toggle the recording capability:

```kotlin
// Start or stop recording for all connections.
suspend fun setCameraRecording(trait: PushAvStreamTransport, isOn: Boolean) {
  if(isOn) {
    trait.setTransportStatus(TransportStatusEnum.Active)
  } else {
    trait.setTransportStatus(TransportStatusEnum.Inactive)
  }
}
```

Enabling or disabling the camera's recording capability is the same as turning
the camera video on or off. When a camera's video is on, it is recording (for
purposes of events and related clips).

When the recording capability is disabled (the camera video is off):

- The camera can still show as online per the [`connectivityState` of the
  device type](https://developers.home.google.com/apis/android/device#check_connectivity_for_a_device).
- The livestream cannot be accessed, nor does the camera detect any cloud events.

### Check if recording capability is enabled

To determine if a camera's recording capability is enabled, check to see if any
connections are active. The following example defines two functions to do this:

```kotlin
// Get the on/off state
suspend fun onOffState(pushAvStreamTransport: PushAvStreamTransport) {
  return pushAvStreamTransport
    .currentConnections?.any { it.transportStatus == TransportStatusEnum.Active } ?: false
}

// Check if the camera's recording capability is enabled
fun PushAvStreamTransport.recordModeActive(): Boolean {
  return currentConnections?.any { it.transportStatus == TransportStatusEnum.Active } ?: false
}
```

Another way to check is using the `findTransport()` function with a predicate:

```kotlin
// Fetch the current connections
suspend fun queryRecordModeState(trait: PushAvStreamTransport) {
  return trait.findTransport().let {
      it.transportConfigurations.any { it.transportStatus == TransportStatusEnum.Active
    }
}
```

## Retrieve camera snapshots

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

Use the `CameraSnapshot` trait to retrieve static image snapshots from a camera.
These snapshots are useful for several scenarios:

- As a placeholder tile in the UI while a [WebRTC
  livestream](https://developers.home.google.com/apis/android/device/camera-floodlight#start_a_livestream) is loading.
- As a static preview image that upgrades to a livestream upon user interaction.
- As a background canvas for drawing and configuring custom [activity
  zones](https://developers.home.google.com/apis/android/device/camera-floodlight#activity-zones).

The `CameraSnapshot` trait offers two ways to fetch snapshots, depending on
whether you need a cached snapshot for fast rendering or an on-demand live
snapshot.

### Get a cached preview snapshot

A preview snapshot is a cached image that the SDK can retrieve without waking
the camera. This is the fastest method to fetch a static image and is ideal
for camera overview pages or dashboard grids.

To get the preview snapshot, read the `preview_image_url` trait attribute:

```kotlin
// Get a flow of the CameraSnapshot trait
val cameraSnapshotFlow: Flow<CameraSnapshot?> = cameraDevice
  .type(GoogleCameraDevice)
  .trait(CameraSnapshot)

// Get the current trait state
val cameraSnapshot = cameraSnapshotFlow.firstOrNull()
if (cameraSnapshot != null) {
  val previewImageUrl = cameraSnapshot.previewImageUrl
  // Load the preview image from the URL
} else {
  // CameraSnapshot trait not supported on this device
}
```

Depending on camera configuration and activity, the preview URL points to a
cached image generated from recent video footage (the first I-frame of the
latest video fragment) or a snapshot periodically uploaded by the camera.

To indicate the freshness of the image, the Google Home cloud embeds an
`X-Home-Image-Captured-At` header in the served
JPEG/PNG image, formatted in UTC. You can parse this header on the
client-side to display the age of the snapshot in an app.

### Get an on-demand live snapshot

For user journeys that require the camera's current live view---such as setting
up Activity Zones---you can request a live snapshot. Triggering a live snapshot
instructs the camera to wake up, capture a new frame, and upload it to the
cloud.

To request a live snapshot, use the `getLiveSnapshot()` command:

```kotlin
try {
  val response = cameraSnapshot.getLiveSnapshot()
  val snapshotUrl = response.snapshotUrl
  // Load the live snapshot image from the URL
} catch (e: Exception) {
  Log.e("CameraSnapshot", "Failed to get live snapshot: ${e.message}")
}
```

> [!WARNING]
> **Warning:** Requesting a live snapshot is relatively slow and resource-intensive because it wakes up battery-powered or sleeping cameras. Only use this command when a fresh, real-time image is required. For general UI previews, use the cached `previewImageUrl` instead.

### Authenticate snapshot requests

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

All snapshot URLs point to secure media and require an OAuth 2.0 token for the
Home APIs v2 scope. To download and render the images, the OAuth token must be
injected as a Bearer token in the `Authorization` header of your HTTP request.

The following example demonstrates how to configure a secure network request
to download a snapshot:

```kotlin
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * Downloads a snapshot from a URL using an OAuth access token.
 */
suspend fun loadSnapshotImage(urlString: String, oauthToken: String): Bitmap? =
  withContext(Dispatchers.IO) {
    var connection: HttpURLConnection? = null
    try {
      val url = URL(urlString)
      connection = url.openConnection() as HttpURLConnection
      // 1. Configure the HTTP GET request with the Bearer token
      connection.setRequestProperty("Authorization", "Bearer $oauthToken")

      // 2. Fetch the image data
      if (connection.responseCode == HttpURLConnection.HTTP_OK) {
        connection.inputStream.use { inputStream ->
          BitmapFactory.decodeStream(inputStream)
        }
      } else {
        null
      }
    } catch (e: IOException) {
      e.printStackTrace()
      null
    } finally {
      connection?.disconnect()
    }
  }
```

## Battery settings

Various battery settings can be controlled through the Home APIs.

### Set the battery usage preference

Setting the energy balance lets you configure the tradeoff between battery
life and performance for a device. You can create different battery
profiles, such as "Extended," "Balanced," and "Performance,"
and switch between them.

This feature is implemented by updating the
[`currentEnergyBalance`](https://developers.home.google.com/reference/kotlin/com/google/home/google/EnergyPreferenceTrait.Attributes#currentEnergyBalance())
attribute of the
[`EnergyPreference`](https://developers.home.google.com/reference/kotlin/com/google/home/google/EnergyPreference)
trait. The attribute accepts an integer
index that corresponds to a specific profile defined in the
device's `energyBalances` list (for example, `0` for `EXTENDED`,
`1` for `BALANCED`, and `2` for `PERFORMANCE`).

A `null` value for `currentEnergyBalance` indicates the device is using a
custom profile. This is a read-only state.

The following shows an example of a structure that the `currentEnergyBalance`
attribute will use, followed by the actual code snippet that uses the attribute.

```json
// Example energyBalances list
energy_balances: [
  {
    step: 0,
    label: "EXTENDED"
  },
  {
    step: 50,
    label: "BALANCED"
  },
  {
    step: 100,
    label: "PERFORMANCE"
  }
]
```

```kotlin
// The index parameter must be within the UByte range (0-255).
suspend fun setEnergyBalance(trait: EnergyPreference, index: Int) {
  trait.update { setCurrentEnergyBalance(index.toUByte()) }
}

// Setting the battery usage to more recording ie performance
setEnergyBalance(energyPreference, 2)
```

### Turn on automatic battery saver

To configure this feature, update the
[`currentLowPowerModeSensitivity`](https://developers.home.google.com/reference/kotlin/com/google/home/google/EnergyPreferenceTrait.Attributes#currentLowPowerModeSensitivity())
attribute of the
[`EnergyPreference`](https://developers.home.google.com/reference/kotlin/com/google/home/google/EnergyPreference)
trait. This attribute uses an index
to select a sensitivity level, where `0` typically represents `Disabled`
and `1` represents `Enabled` or `Automatic`.

```kotlin
suspend fun setAutomaticBatterySaver(enable: Boolean, trait: EnergyPreference) {
  // 0 is Disabled, 1 is Enabled
  val value = if (enable) 1.toUByte() else 0.toUByte()
  trait.update { setCurrentLowPowerModeSensitivity(value) }
}
```

### Get the battery charging state

To get the device's current charging state (charging, fully charged, or not
charging), use the
[`batChargeState`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSourceTrait.Attributes.md.txt#batChargeState())
attribute of the
[`PowerSource`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSource.md.txt)
trait.

```kotlin
// Get the battery charging state
val batteryChargeState = powerSource.batChargeState

when (batteryChargeState) {
    PowerSourceTrait.BatChargeStateEnum.IsCharging -> "Charging"
    PowerSourceTrait.BatChargeStateEnum.IsAtFullCharge -> "Full"
    PowerSourceTrait.BatChargeStateEnum.IsNotCharging -> "Not Charging"
    else -> "Unknown"
}
```

### Get the battery level

To get the current battery level, use the
[`batChargeLevel`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSourceTrait.Attributes.md.txt#batChargeLevel())
attribute of the
[`PowerSource`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSource.md.txt)
trait. The level is either `OK`, `Warning` (low), or `Critical`.

```kotlin
// Get the battery charge level
val batteryLevel = powerSourceTrait.batChargeLevel

when (batteryLevel) {
    PowerSourceTrait.BatChargeLevelEnum.OK -> "OK"
    PowerSourceTrait.BatChargeLevelEnum.Warning -> "Warning"
    PowerSourceTrait.BatChargeLevelEnum.Critical -> "Critical"
    else -> "Unknown"
}
```

### Get the power source

To determine the power source the device is using,
use the [`BatPresent`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSourceTrait.Attributes.md.txt#batPresent())
and
[`wiredPresent`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSourceTrait.Attributes.md.txt#wiredPresent())
attributes of the
[`PowerSource`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSource.md.txt)
trait.

```kotlin
  val trait: PowerSource
  val isWired = trait.wiredPresent
  val hasBattery = trait.batPresent
```

### Check to see if the battery needs to be replaced

The [`batReplaceability`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSourceTrait.Attributes.md.txt#batReplaceability())
attribute indicates whether the battery is unreplaceable, user-replaceable, or
factory-replaceable.

The
[`batReplacementNeeded`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSourceTrait.Attributes.md.txt#batReplacementNeeded())
attribute of the
[`PowerSource`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSource.md.txt)
trait tells you whether the battery needs to be replaced.

```kotlin
// Get the battery replacement status
val batteryStatus = powerSourceTrait.batReplacementNeeded

if (batteryStatus) {
  println("Replace the battery.")
}
```

When the battery is user-replaceable, the
[`batReplacementDescription`](https://developers.home.google.com/reference/kotlin/com/google/home/matter/standard/PowerSourceTrait.Attributes.md.txt#batReplacementDescription())
describes the battery, including information such as form factor, chemistry, and
preferred manufacturer.

## Audio settings

Various audio settings can be controlled through the Home APIs.

### Turn microphone on or off

To turn the device's microphone on or off, update the
[`microphoneMuted`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#microphoneMuted())
attribute of the `CameraAvStreamManagement` trait using the built-in
`setMicrophoneMuted` Kotlin function:

```kotlin
// Turn the device's microphone on or off
suspend fun turnOffMicrophone(disableMicrophone: Boolean, trait: CameraAvStreamManagement) {
  trait.update { setMicrophoneMuted(disableMicrophone) }
}
```

### Turn audio recording on or off

To turn audio recording on or off for the device, update the
[`recordingMicrophoneMuted`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#recordingMicrophoneMuted())
attribute of the `CameraAvStreamManagement` trait using the built-in
`setRecordingMicrophoneMuted` Kotlin function:

```kotlin
// Turn audio recording on or off for the device
suspend fun turnOffAudioRecording(disableAudioRecording: Boolean, trait: CameraAvStreamManagement) {
  trait.update { setRecordingMicrophoneMuted(disableAudioRecording) }
}
```

### Adjust the speaker volume

To adjust the speaker volume for the device, update the
[`speakerVolumeLevel`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#speakerVolumeLevel())
attribute of the `CameraAvStreamManagement` trait using the built-in
`setSpeakerVolumeLevel` Kotlin function:

```kotlin
// Adjust the camera speaker volume
suspend fun adjustSpeakerVolume(volume: Int, trait: CameraAvStreamManagement) {
  trait.update { setSpeakerVolumeLevel(volume.toUbyte()) }
}
```

## Activity zone settings

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

The `ZoneManagement` trait provides an interface for managing custom
regions of interest (activity zones) on camera and doorbell devices.
These zones are used to filter event detection (such as person
or vehicle motion) to specific areas within the device's field of view.

Activity zones are configured by the user within a partner application,
allowing them to draw zones over specific areas in the camera's field of view.
These user-defined zones are then translated into the structures used by this trait.
For more information on how activity zones work, see
[Set up and use Activity Zones](https://support.google.com/googlenest/answer/9207697).

Activity zones are typically defined using 2D Cartesian coordinates.
The trait provides the
[`TwoDCartesianVertexStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.TwoDCartesianVertexStruct.md.txt) for vertices and the
[`TwoDCartesianZoneStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.TwoDCartesianZoneStruct.md.txt)
for the zone definition (name, vertices, color, and usage).

### Check activity zones

To display activity zones, check the
[`zones`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.Attributes.md.txt#zones)
attribute of the `ZoneManagement` trait.

```kotlin
// 1. Obtain the trait flow from the device
private val zoneManagementFlow: Flow =
  device.type(CAMERA_TYPE).flatMapLatest { it.trait(ZoneManagement) }

// 2. Map the flow to the list of zone structures
val activityZones: Flow<List<ZoneManagementTrait.ZoneInformationStruct>> =
  zoneManagementFlow.map { trait ->
    trait.zones ?: emptyList()
  }
```

### Add an activity zone

To create a new zone, use the
[`createTwoDCartesianZone`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.CreateTwoDCartesianZoneCommand.md.txt) command. This command takes a [`TwoDCartesianZoneStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.TwoDCartesianZoneStruct.md.txt),
which defines the zone's name, vertices, color, and usage.

The following example shows how to create a zone named "Front Porch" with four
vertices, colored salmon (#F439A0), and used for motion detection.

```kotlin
import com.google.home.google.ZoneManagement
import com.google.home.google.ZoneManagementTrait
import com.google.home.matter.serialization.OptionalValue

/**
 * Creates a custom activity zone named "Front Porch" with a salmon color
 * configured for motion detection.
 */
suspend fun createFrontPorchZone(zoneManagement: ZoneManagement) {
  // 1. Define the vertices for the zone (2D Cartesian coordinates)
  // Values are typically scaled to a maximum defined by the device's twoDCartesianMax attribute.
  val vertices =
    listOf(
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 260u, y = 422u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 1049u, y = 0u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 2048u, y = 0u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 2048u, y = 950u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 1630u, y = 1349u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 880u, y = 2048u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 0u, y = 2048u),
      ZoneManagementTrait.TwoDCartesianVertexStruct(x = 638u, y = 1090u)
    )

  // 2. Define the zone structure
  val newZone =
    ZoneManagementTrait.TwoDCartesianZoneStruct(
      name = "Front Porch",
      vertices = vertices,
      // Usage defines what the zone filters (for example, Motion, Person, Vehicle)
      use = listOf(ZoneManagementTrait.ZoneUseEnum.Motion),
      // Color is typically a hex string (for example, Salmon/Pink)
      color = OptionalValue.present("#F439A0")
    )

  try {
    // 3. Execute the command to add the zone to the device
    zoneManagement.createTwoDCartesianZone(newZone)
    println("Successfully created activity zone.")
  } catch (e: Exception) {
    // Handle potential HomeException or Timeout
    println("Failed to create activity zone: ${e.message}")
  }
}
```

### Update an activity zone

To update an existing zone, use the
[`updateTwoDCartesianZone`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.UpdateTwoDCartesianZoneCommand.md.txt) command. This command requires the `zoneId` and the updated
[`TwoDCartesianZoneStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.TwoDCartesianZoneStruct.md.txt).

```kotlin
private suspend fun ZoneManagement.updateZone(
  zoneId: UShort,
  zone: ZoneManagementTrait.TwoDCartesianZoneStruct
) {
  // Execute the command to update the zone
  this.updateTwoDCartesianZone(zoneId = zoneId, zone = zone)
}
```

### Delete an activity zone

To remove a zone, use the
[`removeZone`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ZoneManagementTrait.RemoveZoneCommand.md.txt)
command with the specific `zoneId`.

```kotlin
private suspend fun ZoneManagement.deleteZone(zoneId: UShort) {
  // Execute the command to remove the zone
  this.removeZone(zoneId = zoneId)
}
```

## Sound Event Triggers

The `AvStreamAnalysis` trait provides an interface for managing event detection
triggers on camera and doorbell devices. While vision-based triggers
(such as people or vehicles) can be zone-specific, sound-related triggers
are typically device-level configurations.

The following trigger types are available for sound detection with the
[`EventTriggerTypeEnum`](https://developers.home.google.com/reference/kotlin/com/google/home/google/AvStreamAnalysisTrait.EventTriggerTypeEnum.md.txt):

| Mode | Enum value | Description |
|---|---|---|
| Sound | `Sound` | General sound detection. |
| Person talking | `PersonTalking` | Detects speech. |
| Dog bark | `DogBark` | Detects canine vocalizations. |
| Glass break | `GlassBreak` | Detects the sound of breaking glass. |
| Smoke alarm | `SmokeAlarm` | Detects smoke alarms, often recognized by the T3 audible pattern (three short beeps followed by a pause). |
| CO alarm | `CoAlarm` | Detects carbon monoxide (CO) alarms, typically recognized by the T4 audible pattern (four short beeps followed by a pause). |

### Check sound detection status

To display the current state of sound detection to the user, you must check
what the device supports and what is enabled by the device hardware.
The two attributes to check are:

- [`supportedEventTriggers`](https://developers.home.google.com/reference/kotlin/com/google/home/google/AvStreamAnalysisTrait.Attributes.md.txt#supportedEventTriggers())
- [`enabledEventTriggers`](https://developers.home.google.com/reference/kotlin/com/google/home/google/AvStreamAnalysisTrait.Attributes.md.txt#enabledEventTriggers())

In Android development using Kotlin Flows, you typically would observe the
`AvStreamAnalysis` trait from the `HomeDevice`.

```kotlin
// Example structure to store the
data class EventTriggerAttribute(val type: EventTriggerTypeEnum, val enabled: Boolean)

// 1. Obtain the trait flow from the device
private val avStreamAnalysisFlow: Flow<AvStreamAnalysis> =
  device.traitFromType(AvStreamAnalysis, CAMERA_TYPES.first { device.has(it) })

// 2. Map the flow to a list of sound event attributes
val soundEventTriggersState: Flow<List<EventTriggerAttribute>> =
  avStreamAnalysisFlow.map { trait ->
    // Get raw lists from the trait attributes
    val supported = trait.supportedEventTriggers ?: emptyList()
    val enabled = trait.enabledEventTriggers ?: emptyList()

    // Define sound-specific triggers to filter for
    val soundTypes = setOf(
      EventTriggerTypeEnum.Sound,
      EventTriggerTypeEnum.PersonTalking,
      EventTriggerTypeEnum.DogBark,
      EventTriggerTypeEnum.GlassBreak,
      EventTriggerTypeEnum.SmokeAlarm,
      EventTriggerTypeEnum.CoAlarm,
    )

    // Filter and associate status
    supported
      .filter { soundTypes.contains(it) }
      .map { type ->
        EventTriggerAttribute(
          type = type,
          enabled = enabled.contains(type)
        )
      }
  }
```

### Update the set of enabled triggers

To update the set of enabled triggers, use the
[`SetOrUpdateEventDetectionTriggers`](https://developers.home.google.com/reference/kotlin/com/google/home/google/AvStreamAnalysisTrait.SetOrUpdateEventDetectionTriggersCommand.md.txt)
command, which takes a list of `EventTriggerEnablement` structures.

```kotlin
private suspend fun AvStreamAnalysis.updateEventTriggers(
  eventTriggers: List<EventTriggerAttribute>
) {
  val toUpdate = eventTriggers.map {
    EventTriggerEnablement(
      eventTriggerType = it.type,
      enablementStatus = if (it.enabled) {
        EnablementStatusEnum.Enabled
      } else {
        EnablementStatusEnum.Disabled
      },
    )
  }

  // Execute the command on the device
  setOrUpdateEventDetectionTriggers(toUpdate)
}
```

## Recording modes

[Implemented in Sample App for Android](https://developers.home.google.com/apis/android/sample-app/build.md.txt)

The `RecordingMode` trait provides an interface for managing the video
and image recording behavior on camera and doorbell devices. It allows
users to choose between continuous recording, event-based recording,
or disabling recording entirely (Live View only).

The [`RecordingModeEnum`](https://developers.home.google.com/reference/kotlin/com/google/home/google/RecordingModeTrait.RecordingModeEnum.md.txt)
defines the available recording strategies:

| Mode | Enum value | Description |
|---|---|---|
| **Disabled** | `Disabled` | Recording is completely disabled. Used mainly by legacy devices. |
| **CVR** (Continuous Video Recording) | `Cvr` | Video is recorded 24x7. Requires a subscription (for example, Google Home Premium. |
| **EBR** (Event Based Recording) | `Ebr` | Recording is triggered by events (person, motion). Video length depends on the event duration and subscription. |
| **ETR** (Event Triggered Recording) | `Etr` | Short preview recording (for example, 10 seconds) triggered by events. |
| **Live View** | `LiveView` | Recording is disabled, but users can still access the livestream. |
| **Still Images** | `Images` | Snapshots are recorded instead of video when events occur. |

### Check recording modes

To display the current recording configuration, check the attributes
of the `RecordingMode` trait:

- [`supportedRecordingModes`](https://developers.home.google.com/reference/kotlin/com/google/home/google/RecordingModeTrait.Attributes.md.txt#supportedRecordingModes()) - All potential modes
- [`availableRecordingModes`](https://developers.home.google.com/reference/kotlin/com/google/home/google/RecordingModeTrait.Attributes.md.txt#availableRecordingModes()) - Selectable modes
- [`selectedRecordingMode`](https://developers.home.google.com/reference/kotlin/com/google/home/google/RecordingModeTrait.Attributes.md.txt#selectedRecordingMode()) - The active mode

```kotlin
// 1. Obtain the trait flow from the device
private val recordingModeTraitFlow: Flow =
    device.traitFromType(RecordingMode, CAMERA_TYPES.first { device.has(it) })

// 2. Map the flow to recording mode options
data class RecordingModeOptions(
    val recordingMode: RecordingModeTrait.RecordingModeEnum,
    val index: Int,
    val available: Boolean,
    val readableString: String,
)

private val recordingModeOptions: Flow<List> =
    recordingModeTraitFlow.map { trait ->
        val supported = trait.supportedRecordingModes?.map { it.recordingMode } ?: emptyList()
        val available = trait.availableRecordingModes?.map { it.toInt() } ?: emptyList()

        supported.withIndex().map { (index, mode) ->
            RecordingModeOptions(
                recordingMode = mode,
                index = index,
                available = available.contains(index),
                readableString = mode.toReadableString(),
            )
        }
    }
```

### Change the recording mode

Before updating, ensure that the chosen index from the `supportedRecordingModes`
attribute is present in the `availableRecordingModes` attribute.

> [!WARNING]
> **Warning:** If a user changes the recording mode from `EBR` or `CVR` to either `Disabled` or `Live View`, their video history is deleted. Your app should warn users before they make this change.

To update the selected mode, use the
`setSelectedRecordingMode` function, passing the index of the chosen mode:

```kotlin
private suspend fun RecordingMode.updateRecordingMode(index: Int) {
    // Execute the command to update the selected mode
    this.setSelectedRecordingMode(index.toUByte())
}
```

## Other settings

Various other settings can be controlled through the Home APIs.

### Change the image orientation

The orientation of the camera image (video) can be rotated. The video can only
be rotated 180 degrees.

> [!NOTE]
> **Note:** This is not supported for doorbells.

To change the camera's image orientation, update the
[`imageRotation`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#imageRotation())
attribute of the `CameraAvStreamManagement` trait using the built-in
`setImageRotation` Kotlin function:

```kotlin
// Change the camera's image orientation
val isRotated = false

cameraAvStreamManagement.update { setImageRotation(if (isRotated) 180.toUShort() else 0.toUShort()) }
```

### Turn night vision on or off

To turn night vision on or off for the camera, use [`TriStateAutoEnum`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.TriStateAutoEnum.md.txt)
to update the
[`nightVision`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#nightVision())
attribute of the `CameraAvStreamManagement` trait using the built-in
`setNightVision` Kotlin function:

```kotlin
// Turn night vision on
cameraAvStreamManagement.update {
  setNightVision(CameraAvStreamManagementTrait.TriStateAutoEnum.On)
}

// Turn night vision off
CameraAvStreamManagement.update {
  setNightVision(CameraAvStreamManagementTrait.TriStateAutoEnum.Off)
}
```

### Change the brightness of the status LED

To change the brightness of the status LED, use
[`ThreeLevelAutoEnum`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.ThreeLevelAutoEnum.md.txt)
to update the
[`statusLightBrightness`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#statusLightBrightness())
attribute of the `CameraAvStreamManagement` trait using the built-in
`setStatusLightBrightness` Kotlin function:

```kotlin
// Set the LED brightness to high
cameraAvStreamManagement.update {
  setStatusLightBrightness(CameraAvStreamManagementTrait.ThreeLevelAutoEnum.High)
}

// Set the LED brightness to low
cameraAvStreamManagement.update {
  setStatusLightBrightness(CameraAvStreamManagementTrait.ThreeLevelAutoEnum.Low)
}
```

### Change the camera viewport

The camera viewport is the same as the Zoom and Crop feature described in the
[Zoom and enhance Nest camera
video](https://support.google.com/googlenest/answer/9251364)
support article.

The viewport is defined in a `ViewportStruct` that contains four values, which
are used as the coordinates of the viewport. The coordinates are defined as:

```
(x1,y1) -- (x2,y1)
   |          |
(x1,y2) -- (x2,y2)
```

Determining the values for the `ViewportStruct` depends on an app's UI and
camera implementation. At a very basic level, to set the viewport of the camera
video, update the
[`viewport`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#viewport())
attribute of the `CameraAvStreamManagement` trait with a `ViewportStruct`, using
the built-in `setViewport` Kotlin function:

```kotlin
cameraAvStreamManagement
  .update { setViewport(
    CameraAvStreamManagementTrait.ViewportStruct(
      x1 = horizontalRange.rangeStart.roundToInt().toUShort(),
      x2 = horizontalRange.rangeEnd.roundToInt().toUShort(),
      y1 = verticalRange.rangeStart.roundToInt().toUShort(),
      y2 = verticalRange.rangeEnd.roundToInt().toUShort(),
    )
) }
```

### Enable or disable analytics

Each device may individually opt-in to send detailed analytics data to the
Google Home cloud (see [Cloud Monitoring for Home
APIs](https://developers.home.google.com/apis/android/eap/analytics/monitoring)).

> [!IMPORTANT]
> **Important:** Before enabling analytics for a device, the partner should prompt the user to confirm whether or not the user agrees to permit sharing analytics data for that device. Partners should also provide a clear and straightforward way to opt out of sending analytics data for each device.

To enable analytics for a device, set the
[`analyticsEnabled`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ExtendedGeneralDiagnosticsTrait.Attributes.md.txt#analyticsEnabled())
property of the
[`ExtendedGeneralDiagnosticsTrait`](https://developers.home.google.com/reference/kotlin/com/google/home/google/ExtendedGeneralDiagnosticsTrait.md.txt)
to `true`. When you set `analyticsEnabled`,
another property, `logUploadEnabled`, is automatically set to `true`, which
allows the analytics log files to be uploaded to the Google Home cloud.

```kotlin
// Enable analytics
extendedGeneralDiagnostics.update {
  setAnalyticsEnabled(true)
}

// Disable analytics
extendedGeneralDiagnostics.update {
  setAnalyticsEnabled(false)
}
```

## Transport and recording configurations

This section covers settings related to camera streaming quality and
event triggering. These settings are managed by the
[`PushAvStreamTransport`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransport.md.txt)
trait.

### Read transport settings

This section demonstrates how to retrieve the current configuration from
a camera or doorbell device. It fetches the `PushAvStreamTransport` trait,
finds the specific connection used for recording, and then extracts
the current values for bandwidth quality, wake-up sensitivity,
and maximum event length.

```kotlin
val trait: PushAvStreamTransport = device.getTrait(PushAvStreamTransport)
val connections = trait.findTransport().transportConfigurations

// Locate the connection designated for recording
val recordingConnection = connections.firstOrNull {
    it.transportOptions.getOrNull()?.streamUsage == StreamUsageEnum.Recording
}

val options = recordingConnection?.transportOptions?.getOrNull()

// 1. Bandwidth Quality (Video Stream ID)
val videoStreamId = options?.videoStreamId?.getOrNull()

// 2. Wake-up Sensitivity (Motion Sensitivity)
val wakeUpSensitivity = options?.triggerOptions?.motionSensitivity?.getOrNull()

// 3. Max Event Length (Motion Trigger Time Control)
val maxEventLength = options?.triggerOptions?.motionTimeControl?.getOrNull()?.maxDuration
```

### Update transport settings

This section shows how to change the transport settings.
It creates a new `TransportOptionsStruct` containing the new values and
then uses the `modifyPushTransport` command to send these updated settings
back to the device, applying them to the recording connection found
in the previous step.

To modify these settings, use the
[`modifyPushTransport` command](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.ModifyPushTransportCommand.md.txt) with a [`TransportOptionsStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportOptionsStruct.md.txt).

```kotlin
val toUpdate = TransportOptionsStruct(
    videoStreamId = OptionalValue.present(2u), // e.g., Max Quality
    triggerOptions = TransportTriggerOptionsStruct(
        motionSensitivity = OptionalValue.present(5u), // e.g., Medium
        motionTimeControl = OptionalValue.present(
            TransportMotionTriggerTimeControlStruct(maxDuration = 30u)
        )
    )
)

if (recordingConnection != null) {
    trait.modifyPushTransport(
        connectionId = recordingConnection.connectionId,
        transportOptions = toUpdate
    )
}
```

### Determine bandwidth quality

The [`videoStreamId`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportOptionsStruct.md.txt#videoStreamId())
property of the [`TransportOptionsStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportOptionsStruct.md.txt) corresponds to a
specific video stream configuration.

To get the supported video streams, refer to the
[`allocatedVideoStreams`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.Attributes.md.txt#allocatedVideoStreams()) attribute,
which is a list of [`VideoStreamStructs`](https://developers.home.google.com/reference/kotlin/com/google/home/google/CameraAvStreamManagementTrait.VideoStreamStruct.md.txt).
from the `CameraAvStreamManagement` trait for the device.

### Adjust the device wake-up sensitivity

The [`motionSensitivity`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportTriggerOptionsStruct.md.txt#motionSensitivity())
property of the [`TransportTriggerOptionsStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportTriggerOptionsStruct.md.txt) corresponds to the
following values:

| Label | Value (UByte) |
|---|---|
| Low | 1u |
| Medium | 5u |
| High | 10u |

### Adjust the maximum event length

The [`maxDuration`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportMotionTriggerTimeControlStruct.md.txt#maxDuration())
property of the [`TransportMotionTriggerTimeControlStruct`](https://developers.home.google.com/reference/kotlin/com/google/home/google/PushAvStreamTransportTrait.TransportMotionTriggerTimeControlStruct.md.txt)
corresponds to the following durations (in seconds):

- **10u** , **15u** , **30u** , **60u** , **120u** , **180u**

## Decommission a device

To remove a camera-floodlight from a structure, call
`device.decommissionDevice()`. Decommissioning prompts the user with a
Google-managed confirmation screen warning that all recorded 24/7 video
history, event history, clips, and familiar face library data will be
permanently deleted across the structure.

For detailed instructions and code examples, see
[Remove a device](https://developers.home.google.com/apis/android/device/remove.md.txt#cameras-doorbells).