Добавьте в дом новые устройства Matter

API Home для iOS используют концентратор Matter для ввода устройства в эксплуатацию на фабрике. Во время ввода в эксплуатацию приложение отправляет команду в SDK, а затем в концентратор.

Чтобы ввести в эксплуатацию устройство Matter :

  1. Уведомить Home APIs iOS SDK о необходимости подготовки к запросам на комиссию Matter с помощью structure.prepareForMatterCommissioning() . Эта команда выполнит следующее:

    • Убедитесь, что разрешение предоставлено.
    • Убедитесь, что концентратор подключен к сети и доступен.
    • Убедитесь, что в настоящее время нет других активных сеансов ввода в эксплуатацию.
    do {
      try await structure.prepareForMatterCommissioning()
    } catch {
      Logger.error("Failed to prepare for Matter Commissioning: \(error).")
      return
    }
    
  2. Создайте запрос с помощью MatterAddDeviceRequest() чтобы запустить процесс поддержки Matter от Apple.

    let topology = MatterAddDeviceRequest.Topology(
      ecosystemName: "Google Home",
      homes: [MatterAddDeviceRequest.Home(displayName: structure.name)]
    )
    
    let request = MatterAddDeviceRequest(topology: topology)
    
  3. Выполните запрос с помощью perform() . Если произошла ошибка, отмените запрос на ввод в эксплуатацию с помощью structure.cancelMatterCommissioning() .

    do {
      Logger.info("Starting MatterAddDeviceRequest.")
      try await request.perform()
      Logger.info("Successfully completed MatterAddDeviceRequest.")
      let commissionedDeviceIDs = try structure.completeMatterCommissioning()
      Logger.info("Commissioned device IDs: \(commissionedDeviceIDs).")
    } catch let error {
      structure.cancelMatterCommissioning()
      Logger.error("Failed to complete MatterAddDeviceRequest: \(error).")
    }
    
  4. Создайте App Group ID в консоли разработчика Apple, чтобы разрешить приложению взаимодействовать с расширением MatterAddDevice при вводе устройства в эксплуатацию.

    Вам также потребуется обновить идентификатор пакета приложения и профили подготовки, чтобы использовать этот идентификатор группы.

  5. При инициализации настройте экземпляр Home на использование идентификатора группы.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions
    launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
      Home.configure {
        $0.sharedAppGroup = "group.com.sample.app.commissioning"
      }
    
      return true
    }
    
  6. Внедрите расширение приложения iOS Matter от Apple.

    В примере кода показан пример реализации подкласса API MatterAddDeviceExtensionRequestHandler от Apple.

    Как минимум, добавьте фреймворк GoogleHomeMatterCommissionerSDK к целевому объекту расширения и переопределите три метода для вызова API HomeMatterCommissioner Google Home platform .

    • commissionDevice
    • rooms
    • configureDevice
    import MatterSupport
    import GoogleHomeMatterCommissionerSDK
    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 {
        Logger.info("Commission Matter device with payload: '\(onboardingPayload)'.")
    
        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()
          Logger.info("Returning \(fetchedRooms.count) fetched rooms.")
          return fetchedRooms
        } catch {
          Logger.info("Failed to fetch rooms with error: \(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 {
        Logger.info("Configure Device name: '\(name)', room: \(room?.displayName ?? "").")
        do {
          let homeMatterCommissioner = try HomeMatterCommissioner(appGroup: RequestHandler.appGroup)
          await homeMatterCommissioner.configureMatterDevice(
            deviceName: name, roomName: room?.displayName)
        } catch {
          Logger.info("Configure Device failed with error: \(error).")
        }
      }
    }