<br />

| **Note:**An application can only be granted permission to one structure at any given time.

<br />

Structure APIs may be accessed through the Home APIs for Android. Import these packages into your app:  

    import com.google.home.Home
    import com.google.home.Id
    import com.google.home.Structure

## Error handling

<br />

Any method in the Home APIs can throw a[`HomeException`](https://developers.home.google.com/reference/kotlin/com/google/home/HomeException), so we recommend that you use a`try-catch`block to catch`HomeException`on all calls.

When handling`HomeException`, check its[`error.code`](https://developers.home.google.com/apis/android/structure/reference/kotlin/com/google/home/HomeError#code())and[`error.message`](https://developers.home.google.com/apis/android/structure/reference/kotlin/com/google/home/HomeError#message())fields to learn what went wrong. There may be sub-error codes as well, so call the[`getSubErrorCodes()`](https://developers.home.google.com/reference/kotlin/com/google/home/HomeException#getSubErrorCodes())method and check the result.

Any unhandled exceptions will result in your app crashing.

For more information, see[Error handling](https://developers.home.google.com/apis/android/error-handling).

<br />

## Sample calls

<br />

| **Caution:**Code examples shown here may be implemented differently than those of any sample apps, in order to illustrate basic API calls.

<br />

### Get a list of structures

Once initialized, a`structures()`call returns a Flow of structures accessible to you:  

```kotlin
// Get a flow of all structures accessible to the user
val allStructuresFlow: HomeObjectsFlow<Structure> = home.structures()

// Calling list() on a HomeObjectsFlow returns the first Set of elements.
val allStructures: Set<Structure> = allStructuresFlow.list()
```

The`structures()`API is a flow that may not immediately return a valid list of structures. If your app is reactive and subscribes to that flow to drive the UI, a valid list of structures should eventually be returned. There are other situations where an empty structure list could be returned, for example if the user's phone loses connectivity or if the user has revoked permissions to your app. You should be sure to handle these cases in your app.

Alternatively, if imperative programming is strongly required instead of reactive programming, a terminal flow operator can be used:  

```kotlin
val everyStructure = withTimeout(5000) { home.structures().first { it.isNotEmpty() } }
```

This call waits for a valid list of structures to come through the flow and times out if the list is not received within an app-designated timeout.
| **Important:** The Structure API returns only those structures the developer has been granted access to.

### Get structure properties

With the list of structures in hand, you can access the properties for them:  

```kotlin
// Get a flow on a structure. Flow emits new values on structure metadata changes: name.
val structureFlow: Flow<Structure> = home.structures().itemFlow(myStructureId)

// Get a snapshot of the structure.
val structure: Structure = structureFlow.first()

// Get structure properties
println("id ${structure.id}")
println("name ${structure.name}")
```

### Find a structure by name

If you know the name of a structure, you can also access it using the`name`property:  

```kotlin
val myHome = home.structures().list().first { it.name == "My home" }
```

From there, properties, rooms, and devices for each structure are accessible.

### Work with multiple structures

To use more than one structure, get a separate reference to each structure:  

```kotlin
var structure1: Structure? = null
var structure2: Structure? = null

try {
  structure1 = home.structures().list().firstOrNull { it.name == "Main House" }
} catch (e: HomeException) {
  // Code for handling the exception
}
try {
  structure2 = home.structures().list().firstOrNull { it.name == "Guest Cottage" }
} catch (e: HomeException) {
  // Code for handling the exception
}
```

### Get a list of rooms

With a structure in hand, you can get a list of rooms and access the properties for them:  

```kotlin
val allRoomsFlow: HomeObjectsFlow<Room> = structure.rooms()
val allRooms: Set<Room> = allRoomsFlow.list()
val room: Room = allRooms.first()

println("id ${room.id}")
println("name ${room.name}")
```

### Create a room

To create a new room:  

```kotlin
val testName = "Test Room Name"
val newRoom: Room = structure.createRoom(testName)
```

### Delete a room

Or, alternatively, you can delete a room:  

```kotlin
val roomToDelete = structure.rooms().list().filter { it.name == "room_id1" }.firstOrNull()
    structure.deleteRoom(roomToDelete!!)
```

You can also delete a room with just an ID:  

```kotlin
val roomToDelete1 = allRooms.filter { it.id == testRoomId }.firstOrNull()
structure.deleteRoom(roomToDelete1!!)
```

If a room with devices is deleted, the devices will still be in the structure but no longer assigned to a room.

### Move devices to a different room

Once you have a structure, you can move devices to a different room within that structure:  

```kotlin
val room2 = structure.rooms().get(Id("room_id_other_structure"))
    val device1 = structure.devices().get(Id("device_id1"))
    structure.moveDevicesToRoom(room2!!, listOf(device1!!))
```

If you only have device and room IDs, you can also move devices:  

```kotlin
structure.moveDevicesToRoom(Id("room_id_other_structure"), listOf(Id("device_id1")))
```

### Change the name of a room

Call the[`setName()`](https://developers.home.google.com/reference/kotlin/com/google/home/Room#setName(kotlin.String))method to change the name of a room:  

```kotlin
livingRoom.setName("Living Room")
```

Names will be truncated if over the 60 Unicode code point (character) limit and no errors will be thrown. Developers are responsible for handling long names and, for example, can decide if they want to inform users names will be truncated.

## Automations

The entry point to the Automation API is through a structure. To learn more about Automations in the Home APIs, see[Automation API on Android overview](https://developers.home.google.com/apis/android/automation).

## API list

Once an instance of[`Home`](https://developers.home.google.com/reference/kotlin/com/google/home/Home)is created, the following Structure APIs are accessible through it:

|      API       |                                                                                                      Description                                                                                                      |
|----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `structures()` | Get all the structures on the Google Account. Returns a[`HomeObjectsFlow`](https://developers.home.google.com/reference/kotlin/com/google/home/HomeObjectsFlow)that provides further retrieval and filtering options. |

Once you have a[`Structure`](https://developers.home.google.com/reference/kotlin/com/google/home/Structure), the following APIs are accessible through it:

|                  API                   |                                                                          Description                                                                          |
|----------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `automations()`                        | List all automations that belong to the structure. Only automations created through the Home APIs are returned.                                               |
| `createAutomation(automation)`         | Create an automation instance for a structure.                                                                                                                |
| `createRoom(name)`                     | Create a room with the user-given name.                                                                                                                       |
| `deleteAutomation(automationId)`       | Delete an automation instance by its ID.                                                                                                                      |
| `deleteRoom(roomId)`                   | Delete a room with the room ID.                                                                                                                               |
| `devices()`                            | Get all the devices in the structure. Returns a[`HomeObjectsFlow`](https://developers.home.google.com/reference/kotlin/com/google/home/HomeObjectsFlow).      |
| `getAutomation(automationId)`          | Get an automation instance by its ID.                                                                                                                         |
| `getSourceConnectivity(trait)`         | Get metadata for a particular trait. Returns a[`SourceConnectivity`](https://developers.home.google.com/reference/kotlin/com/google/home/SourceConnectivity). |
| `has(trait)`                           | Check if the current requested trait is supported by the device.                                                                                              |
| `id`                                   | The unique system ID of the structure.                                                                                                                        |
| `moveDevicesToRoom(roomId, deviceIds)` | Move devices to a different room ID in the structure.                                                                                                         |
| `name`                                 | The user-provided name of the structure.                                                                                                                      |
| `rooms()`                              | Get all the rooms in the structure. Returns a[`HomeObjectsFlow`](https://developers.home.google.com/reference/kotlin/com/google/home/HomeObjectsFlow).        |
| `trait(trait)`                         | Get a current snapshot of the trait attributes.                                                                                                               |

Some common APIs (such as`devices()`,`id`, and`name`) are also available for a[`Room`](https://developers.home.google.com/reference/kotlin/com/google/home/Room).