Add new Matter devices to a home

The Home APIs for iOS use a Matter hub to commission a device onto a fabric. During commissioning, the app sends a command to the SDK and then to the hub.

Xcode project configuration

Before you implement the Commissioning API, make sure to add the required capabilities, entitlements, and Info.plist properties to your Xcode targets:

Entitlements

Include the following entries in your main app target and extension's .entitlements files:

  • Thread network credentials management:

    <key>com.apple.developer.networking.manage-thread-network-credentials</key>
    <true/>
    

    To use this entitlement in a distributed build, you must submit an entitlement request form to Apple. Apple requires that you prove membership in the Thread Group and verify that your Thread Border Router is certified by the Thread Group.

  • Wi-Fi information:

    <key>com.apple.developer.networking.wifi-info</key>
    <true/>
    
  • App groups: Add a shared app group to allow your main app and the Matter Add Device Extension to communicate (for example, group.com.yourdomain.appgroupname). This identifier is created and registered by the developer in their Apple Developer Console, and must match the App Group configured in the target capabilities in Xcode. The Google Home SDK uses this identifier in both targets to automatically synchronize commissioning state, fabric credentials, and room lists using a shared UserDefaults container.

Keychain sharing (optional)

If your app extension needs to retrieve credentials or access tokens stored by the main app using UserInfo.authorizationToken(), you must configure a shared keychain access group for both your main app and app extension targets in their entitlements plist:

<key>keychain-access-groups</key>
<array>
    <string>$(AppIdentifierPrefix)your.shared.keychain.group</string>
</array>

Info.plist properties

Include the following description keys in your main app target's Info.plist:

  • Location usage description:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Your custom message explaining why location access is needed to read the current Wi-Fi SSID</string>
    
  • Bonjour services: Under NSBonjourServices, include the services required for local Matter and Thread discovery:

    <key>NSBonjourServices</key>
    <array>
        <string>_matter._tcp</string>
        <string>_matterc._udp</string>
        <string>_matterd._udp</string>
        <string>_meshcop._udp</string>
    </array>
    
  • Local network usage description: Include the NSLocalNetworkUsageDescription key with a message explaining local network discovery permissions.

Commission a device

To commission a Matter device:

  1. Notify the Home APIs iOS SDK to prepare for Matter commissioning requests with structure.prepareForMatterCommissioning(). This command will do the following:

    • Verify the permission has been granted.
    • Make sure the hub is online and reachable.
    • Make sure there is no other active ongoing commissioning session.
    do {
      try await structure.prepareForMatterCommissioning()
    } catch {
      // Failed to prepare for Matter Commissioning
      return
    }
    
  2. Create a request with MatterAddDeviceRequest() to start Apple's Matter support flow.

    let topology = MatterAddDeviceRequest.Topology(
      ecosystemName: "Google Home",
      homes: [MatterAddDeviceRequest.Home(displayName: structure.name)]
    )
    
    let request = MatterAddDeviceRequest(topology: topology)
    
  3. Perform the request with perform(). If an error occurs, cancel the commissioning request with structure.cancelMatterCommissioning().

    do {
      // Starting MatterAddDeviceRequest.
      try await request.perform()
      // Successfully completed MatterAddDeviceRequest.
      let commissionedDeviceIDs = try structure.completeMatterCommissioning()
      // Commissioned device IDs.
    } catch let error {
      structure.cancelMatterCommissioning()
      // Failed to complete MatterAddDeviceRequest.
    }
    
  4. Create an App Group ID in the Apple Developer Console to allow the app to communicate with the MatterAddDevice extension when commissioning the device.

    You will also need to update your application bundle identifier and provisioning profiles to use this group ID.

  5. When initializing, configure the Home instance to use the group identifier.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions
    launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
      Home.configure {
        $0.sharedAppGroup = "group.com.sample.app.commissioning"
      }
    
      return true
    }
    
  6. Implement the iOS Matter App Extension from Apple.

    The sample code shows an example of implementing a subclass of Apple's MatterAddDeviceExtensionRequestHandler API.

    At a minimum, add the GoogleHomeMatterCommissionerSDK Framework to the extension target and override three methods to call the Google Home platformHomeMatterCommissioner APIs.

    • commissionDevice
    • rooms
    • configureDevice
    import MatterSupport
    import GoogleHomeSDK
    import OSLog
    
    final class RequestHandler: MatterAddDeviceExtensionRequestHandler {
      // The App Group ID defined by the application to share information between the extension and main app.
      private static var appGroup = "group.com.sample.app.commissioning"
    
      ...
    
      // MARK: - Home API commissioning handlers
    
      /// Commissions a device to the Google Home ecosystem.
      /// - Parameters:
      ///   - home: The home that the device will be added to
      ///   - onboardingPayload: The payload to be sent to the Matter Commissioning SDK to commission the device.
      ///   - commissioningID: An identifier not used by the Home API SDK.
      override func commissionDevice(in home: MatterAddDeviceRequest.Home?, onboardingPayload: String, commissioningID: UUID) async throws {
        // Commission Matter device with payload.
    
        var onboardingPayloadForHub = onboardingPayload
        let homeMatterCommissioner = try HomeMatterCommissioner(appGroup: RequestHandler.appGroup)
        try await homeMatterCommissioner.commissionMatterDevice(
        onboardingPayload: onboardingPayloadForHub)
      }
    
      /// Obtains rooms from the Home Ecosystem to present to the user during the commissioning flow.
      /// - Parameter home: The home that the device will be added to.
      /// - Returns: A list of rooms if obtained from the Google Home ecosystem or an empty list if there was an error in getting them.
      override func rooms(in home: MatterAddDeviceRequest.Home?) async -> [MatterAddDeviceRequest.Room] {
        do {
          let homeMatterCommissioner = try HomeMatterCommissioner(appGroup: RequestHandler.appGroup)
          let fetchedRooms = try homeMatterCommissioner.fetchRooms()
          // Returning fetched rooms.
          return fetchedRooms
        } catch {
          // Failed to fetch rooms with error
          return []
        }
      }
    
      /// Pushes the device's configurations to the Google Home Ecosystem.
      /// - Parameters:
      ///   - name: The friendly name the user chose to set on the device.
      ///   - room: The room identifier that the user chose to put the device in.
      override func configureDevice(named name: String, in room: MatterAddDeviceRequest.Room?) async {
        // Configure Device name: room
        do {
          let homeMatterCommissioner = try HomeMatterCommissioner(appGroup: RequestHandler.appGroup)
          await homeMatterCommissioner.configureMatterDevice(
            deviceName: name, roomName: room?.displayName)
        } catch {
          // Configure Device failed with error
        }
      }
    }