Control devices on Android

This guide continues from Access devices and device metadata on Android and introduces additional examples of device control and access.

To use specific device types or traits, such as the ones used in many of the examples here, import them:

import com.google.home.matter.standard.DimmableLightDevice
import com.google.home.matter.standard.OnOff
import com.google.home.matter.standard.OnOffLightDevice
import com.google.home.matter.standard.OnOffTrait

Check if a trait supports a command

Use the trait-level supports function to check if a command is supported for a particular device.

For example, to check for a device's support of the On/Off trait's toggle command:

// Check if the OnOff trait supports the toggle command.
if (onOffTrait.supports(OnOff.Command.Toggle)) {
  println("onOffTrait supports toggle command")
} else {
  println("onOffTrait does not support stateful toggle command")
}

Send a command to a device

Sending a command is similar to reading a state attribute from a trait. To turn the device on or off, use the OnOff trait's Toggle command, which is defined in the Google Home ecosystem data model as toggle(). This method changes onOff to false if it is true, or to true if it is false:

// Calling a command on a trait.
try {
  onOffTrait.toggle()
} catch (e: HomeException) {
  // Code for handling the exception
}

All trait commands are suspend functions and only complete when a response is returned by the API (such as confirming the device state has changed). Commands might return an exception if an issue is detected with the execution flow. As a developer, you should use a try-catch block to properly handle these exceptions, and surface detailed information to users on cases where the errors are actionable. Unhandled exceptions will stop the app runtime and can result in crashes in your app.

Alternatively, use the off() or on() commands to explicitly set the state:

onOffTrait.off()
onOffTrait.on()

After sending a command to change the state, once it completes you can read the state as described in Read a device state to handle it in your app. Alternatively, use flows as described in Observe state, which is the preferred method.

Send a command with parameters

Some commands may use parameters, like those on the OnOff or LevelControl traits:

offWithEffect

// Turn off the light using the DyingLight effect.
onOffTrait.offWithEffect(
  effectIdentifier = OnOffTrait.EffectIdentifierEnum.DyingLight,
  effectVariant = 0u,
)

moveToLevel

// Change the brightness of the light to 50%
levelControlTrait.moveToLevel(
  level = 127u.toUByte(),
  transitionTime = null,
  optionsMask = LevelControlTrait.OptionsBitmap(),
  optionsOverride = LevelControlTrait.OptionsBitmap(),
)

Some commands have optional arguments, which come after the required arguments.

For example, the step command for the FanControl trait has two optional arguments:

val fanControlTraitFlow: Flow<FanControl?> =
  device.type(FanDevice).map { it.standardTraits.fanControl }.distinctUntilChanged()

val fanControl = fanControlTraitFlow.firstOrNull()

// Calling a command with optional parameters not set.
fanControl?.step(direction = FanControlTrait.StepDirectionEnum.Increase)

// Calling a command with optional parameters.
fanControl?.step(direction = FanControlTrait.StepDirectionEnum.Increase) { wrap = true }

Check if a trait supports an attribute

Some devices may support a Matter trait, but not a specific attribute. For example, a Cloud-to-cloud device that was mapped to Matter may not support every Matter attribute. To handle cases like these, use the trait-level supports function and the trait's Attribute enum to check if the attribute is supported for a particular device.

For example, to check for a device's support of the On/Off trait's onOff attribute:

// Check if the OnOff trait supports the onOff attribute.
if (onOffTrait.supports(OnOff.Attribute.onOff)) {
  println("onOffTrait supports onOff state")
} else {
  println("onOffTrait is for a command only device!")
}

Some attributes are nullable in the Matter specification or the Cloud-to-cloud smart home schema. For these attributes, you can determine whether a null returned by the attribute is due to the device not reporting that value, or if the attribute's value actually is null, by using isNullable in addition to supports:

// Check if a nullable attribute is set or is not supported.
if (onOffTrait.supports(OnOff.Attribute.startUpOnOff)) {
  // The device supports startupOnOff, it is safe to expect this value in the trait.
  if (OnOff.Attribute.startUpOnOff.isNullable && onOffTrait.startUpOnOff == null) {
    // This value is nullable and set to null. Check the specification as to
    // what null in this case means
    println("onOffTrait supports startUpOnOff and it is null")
  } else {
    // This value is nullable and set to a value.
    println("onOffTrait supports startUpOnOff and it is set to ${onOffTrait.startUpOnOff}")
  }
} else {
  println("onOffTrait does not support startUpOnOff!")
}

Update trait attributes

If you want to change the value of a given attribute, and none of the trait's commands does so, the attribute may support having its value explicitly set.

Whether the value of an attribute can be changed depends on two factors:

  • Is the attribute writable?
  • Can the value of the attribute change as a side effect of sending a trait command?

The reference documentation for traits and their attributes provides this information.

Therefore, the combinations of properties that dictate how an attribute's value might be changed are:

  • Read-only and not affected by other commands. This means that the attribute's value doesn't change. For example, the currentPosition attribute of the Switch trait.

  • Read-only and affected by other commands. This means that the only way the attribute's value can change is as the result of sending a command. For example, the currentLevel attribute of the LevelControl Matter trait is read-only, but its value can be mutated by commands such as moveToLevel.

  • Writeable and not affected by other commands. This means that you can directly change the value of the attribute by using the update function of the trait, but there are no commands that will affect the value of the attribute. For example, the WrongCodeEntryLimit attribute of the DoorLock trait.

  • Writeable and affected by other commands. This means that you can directly change the value of the attribute by using the update function of the trait, and the attribute's value can change as the result of sending a command. For example, the speedSetting attribute of the FanControlTrait can be written to directly, but is also mutable using the step command.

Example of using the update function to change an attribute's value

This example shows how to explicitly set the value of the DoorLockTrait.WrongCodeEntryLimit attribute.

To set an attribute value, call the trait's update function and pass it a mutator function that sets the new value. It's a good practice to first verify that the trait supports an attribute.

For example:

    val doorLockDevice = home.devices().list().first { device -> device.has(DoorLock) }

    val traitFlow: Flow<DoorLock?> =
      doorLockDevice.type(DoorLockDevice).map { it.standardTraits.doorLock }.distinctUntilChanged()

    val doorLockTrait: DoorLock = traitFlow.first()!!

    if (doorLockTrait.supports(DoorLock.Attribute.wrongCodeEntryLimit)) {
      val unused = doorLockTrait.update { setWrongCodeEntryLimit(3u) }
    }

Send multiple commands at once

The Batching API allows a client to send multiple Home APIs device commands in a single payload. The commands are batched into a single payload and executed in parallel, similar to how one might construct a Home API automation using the parallel node, such as the Open blinds before sunrise example. However, the Batching API allows for more complex and sophisticated behaviors than the Automation API, such as the ability to dynamically select devices at runtime according to any criteria.

The commands in one batch can target multiple traits across multiple devices, in multiple rooms, in multiple structures.

Sending commands in a batch allows devices to perform actions simultaneously, which isn't really possible when commands are sent sequentially in separate requests. The behavior achieved using batched commands allows the developer to set the state of a group of devices to match a predetermined aggregate state.

Use the Batching API

There are three basic steps involved in invoking commands through the Batching API:

  1. Invoke the Home.sendBatchedCommands() method.
  2. Within the body of the sendBatchedCommands() block, specify the commands to be included in the batch.
  3. Check the results of the sent commands to see whether they succeeded or failed.

Send batched commands

Call the Home.sendBatchedCommands() method. Behind the scenes, this method sets up a lambda expression in a special batch context.

home.sendBatchedCommands() {

Specify batch commands

Within the body of the sendBatchedCommands() block, populate batchable commands. Batchable commands are "shadow" versions of existing Device API commands that can be used in a batch context, and are named with the added suffix Batchable. For example, the LevelControl trait's moveToLevel() command has a counterpart named moveToLevelBatchable().

Example:

  val response1 = add(command1)

  val response2 = add(command2)

The batch is automatically sent once all commands have been added to the batch context and execution has left the context.

Responses are captured in DeferredResponse<T> objects.

The DeferredResponse<T> instances can be gathered into an object of any type, such as a Collection, or a data class that you define. Whatever type of object you choose to assemble the responses is what is returned by sendBatchedCommands(). For example, the batch context can return two DeferredResponse instances in a Pair:

  val (response1, response2) = homeClient.sendBatchedComamnds {
    val response1 = add(someCommandBatched(...))
    val response2 = add(someOtherCommandBatched(...))
    Pair(response1, response2)
  }

Alternatively, the batch context can return the DeferredResponse instances in a custom data class:

  // Custom data class
  data class SpecialResponseHolder(
    val response1: DeferredResponse<String>,
    val response2: DeferredResponse<Int>,
    val other: OtherResponses
  )
  data class OtherResponses(...)

Check each response

Outside the sendBatchedCommands() block, check the responses to determine whether the corresponding command succeeded or failed. This is done by calling DeferredResponse.getOrThrow(), which either: - returns the result of the executed command, - or, if the batch scope has not completed or the command was unsuccessful, throws an error.

You should only check the results outside of the sendBatchedCommands() lambda scope.

Example

Say you wanted to build an app that uses the Batching API to set up a 'good night' scene that configures all the devices in the home for nighttime, when everyone is asleep. This app should turn out the lights and lock the front and back doors.

Here's one way to approach the task:

val lightDevices: List<OnOffLightDevice>
val doorlockDevices: List<DoorLockDevice>

// Send all the commands
val responses: List<DeferredResponse<Unit>> = home.sendBatchedCommands {
  // For each light device, send a Batchable command to turn it on
  val lightResponses: List<DeferredResponse<Unit>> = lightDevices.map { lightDevice ->
    add(lightDevice.standardTraits.onOff.onBatchable())
  }

  // For each doorlock device, send a Batchable command to lock it
  val doorLockResponse: List<DeferredResponse<Unit>> = doorlockDevices.map { doorlockDevice ->
    add(doorlockDevice.standardTraits.doorLock.lockDoorBatchable())
  }

  lightResponses + doorLockResponses
}

// Check that all responses were successful
for (response in responses) {
  response.getOrThrow()
}

Control a device group

When you want to send a command to multiple devices, you can iterate over the devices, sending the same command to each individual device, one by one. The downside of this approach is that the command doesn't take effect all at once. When you're turning a set of lights on or off this way, the user experiences the so-called 'popcorn effect', which gives the impression that the underlying system is chaotic and unreliable.

When you want all the devices to execute the command simultaneously, a better approach is to send the command to the DeviceGroup's device type part. When you do this, the SDK relays the command simultaneously to all associated member devices in the group that support that capability, regardless of their underlying connectivity or transport (such as Matter or Cloud-to-cloud).

DeviceGroup implements the PartsProvider interface, which exposes the DeviceType parts supported by the devices in the group:

  • group.parts() returns a Flow<Set<DeviceType>> of all device types present in the group.
  • group.part() and group.partOrNull() return a flow for a specific device type, such as OnOffLightDevice or DimmableLightDevice.

Group part trait attributes and error handling

When working with traits and commands on a DeviceGroup part, keep the following behaviors in mind:

  • Dynamic state attributes (such as the onOff attribute of the OnOff trait or the currentLevel attribute of the LevelControl trait) are generally not populated on a group part's trait because member devices in a group can be in different states that cannot be combined into a single value. However, supported commands (checked with supports(), such as LevelControl.Command.MoveToLevelWithOnOff on a dimmable light) and select capability attributes (such as colorTempPhysicalMinMireds and colorTempPhysicalMaxMireds on ColorControl for color lights) are populated so that your app can configure UI controls appropriately.
  • Not all commands on traits of group members are available on a group part. In particular, commands that return values are not available.
  • A command on a group part doesn't return individual results for each underlying member device command. To inspect individual command results or call commands that return values, iterate through the group's member devices directly.
  • Commands sent to a part on a DeviceGroup complete once all underlying command outcomes are collected. A command only fails (throws a HomeException) if the command fails for every associated member device or if all target devices are unavailable, surfacing as a single command failure matching the single-command call syntax. If at least one member device executes the command, the group command completes without throwing an exception.

Send commands to a group part

To turn on all OnOffLightDevice lights in a device group:

val lightPart = group.partOrNull(OnOffLightDevice).firstOrNull()
val onOffTrait = lightPart?.trait(OnOff)

if (onOffTrait?.supports(OnOff.Command.On) == true) {
  onOffTrait.on()
}

You can also inspect all device types present in a group using group.parts() to target a trait across multiple related device types (for example, turning off any light device type in the group that supports OnOff):

val lightTypes = listOf(
  OnOffLightDevice,
  DimmableLightDevice,
  ColorTemperatureLightDevice,
  ExtendedColorLightDevice,
)

val parts = group.parts().first()
val onOffTrait = lightTypes.firstNotNullOfOrNull { type ->
  parts.firstOrNull { it.factory == type }
}?.trait(OnOff)

onOffTrait?.off()

You can check command support or read capability bounds on a group part before sending a command (for example, checking MoveToLevelWithOnOff on a dimmable light part or reading colorTempPhysicalMinMireds and colorTempPhysicalMaxMireds on a color temperature light part):

val dimmableLight = group.partOrNull(DimmableLightDevice).firstOrNull()
val levelControl = dimmableLight?.trait(LevelControl)

if (
  levelControl?.supports(
    LevelControl.Command.MoveToLevelWithOnOff
  ) == true
) {
  levelControl.moveToLevelWithOnOff(
    level = 127u,
    transitionTime = null,
    optionsMask = LevelControlTrait.OptionsBitmap(),
    optionsOverride = LevelControlTrait.OptionsBitmap(),
  )
}

val colorLight = group.partOrNull(ColorTemperatureLightDevice).firstOrNull()
val colorControl = colorLight?.trait(ColorControl)
val minMireds = colorControl?.colorTempPhysicalMinMireds
val maxMireds = colorControl?.colorTempPhysicalMaxMireds

if (colorControl != null && minMireds != null && maxMireds != null) {
  val midMireds = ((minMireds.toInt() + maxMireds.toInt()) / 2).toUShort()
  colorControl.moveToColorTemperature(
    colorTemperatureMireds = midMireds,
    transitionTime = 0u,
    optionsMask = ColorControlTrait.OptionsBitmap(),
    optionsOverride = ColorControlTrait.OptionsBitmap(),
  )
}

Supported group part device types

A DeviceGroup synthesizes parts for two Matter Light device types: OnOffLightDevice and DimmableLightDevice.

At least one member device in the group must support one of these device types. If a group has both an OnOffLightDevice and a DimmableLightDevice, sending OnOff.on() to the group's DimmableLightDevice part also turns on the OnOffLightDevice (its supertype), because both belong to the same light component and support the OnOff trait.

Be sure to check at runtime to see if the command you want to send is supported on a DeviceGroup part.

Monitor group parts and connectivity

When devices are added to or removed from a DeviceGroup, the group dynamically recomputes its parts. Collect the Flow<Set<DeviceType>> returned by group.parts() (or the flow returned by group.part() or group.partOrNull()) to receive real-time updates whenever the group's available device types or supported commands change.

For example, to find supported DimmableLightDevice parts and check whether they support the OnOff trait's on command:

group.parts().collect { parts ->
  val dimmableParts = parts.filter { it.factory == DimmableLightDevice }
  for (part in dimmableParts) {
    val supportsOn = part.trait(OnOff)?.supports(OnOff.Command.On) == true
    println("Group ${group.id.id} dimmable part supports on: $supportsOn")
  }
}

A DeviceGroup also reports aggregated connectivity across the traits on its supported parts through group.sourceConnectivity.connectivityState:

  • When cloud connectivity is available, a group with supported parts reports ConnectivityState.ONLINE even if member devices are offline, because the cloud provides a fallback route without tracking member connectivity on group parts. Check the member HomeDevice instances directly for individual device status.
  • When cloud connectivity is unavailable, connectivity reflects local Matter reachability across the group's parts: ConnectivityState.ONLINE when all traits have a reachable local member, ConnectivityState.PARTIALLY_ONLINE when only some traits are reachable locally, and ConnectivityState.OFFLINE when none are reachable. A group with no supported parts reports ConnectivityState.UNKNOWN.

When a home hub and the group's member Matter devices are reachable on the local network, commands sent to a DeviceGroup part are expanded and dispatched locally without requiring internet connectivity. Group management operations, such as creating, renaming, or deleting a group, or adding and removing member devices, require cloud connectivity.

For information about device connectivity, see Connectivity.

Target a group in an automation

You can also control a DeviceGroup in an automation by passing the DeviceGroup instance and a supported DeviceTypeFactory to an action node. Ensure that DeviceGroup is passed in the entityTypes parameter of FactoryRegistry alongside the constituent device types and traits.

@OptIn(HomeExperimentalApi::class)
fun turnOnLightGroupAtEvening(
  structure: Structure,
  lightGroup: DeviceGroup,
): DraftAutomation {
  return automation {
    name = "Turn on evening lights"
    description = "Turn on all lights in the group at 7:00 PM"
    isActive = true
    sequential {
      starter(structure, event = Time.ScheduledTimeEvent) {
        parameter(Time.ScheduledTimeEvent.clockTime(LocalTime.of(19, 0, 0, 0)))
      }
      action(lightGroup, OnOffLightDevice) {
        command(OnOff.on())
      }
    }
  }
}

To discover which automation actions a group supports, call group.candidates() (or structure.allCandidates()). Because a DeviceGroup doesn't aggregate dynamic state attributes or emit state-change events, it only produces CommandCandidate instances and can only be used in action nodes (not in starter or stateReader nodes). In addition, room and structure entity filters (getDevicesOfType()) match only individual HomeDevice entities and never match DeviceGroup entities.