إضافة أجهزة Matter جديدة إلى منزل

تستخدِم واجهات برمجة التطبيقات Home APIs لنظام التشغيل iOS مركز Matter لتشغيل جهاز على شبكة. أثناء عملية التشغيل، يُرسِل التطبيق أمرًا إلى حزمة تطوير البرامج (SDK)، ثم إلى المركز.

إعداد مشروع Xcode

قبل تنفيذ واجهة برمجة التطبيقات Commissioning API، تأكَّد من إضافة الإمكانات والأذونات وخصائص Info.plist المطلوبة إلى أهداف Xcode:

الأذونات

أدرِج الإدخالات التالية في هدف التطبيق الرئيسي وملفات .entitlements للإضافة:

  • إدارة بيانات اعتماد شبكة Thread:

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

    لاستخدام هذا الإذن في إصدار موزَّع، عليك إرسال نموذج طلب إذن إلى Apple. تطلب Apple إثبات العضوية في Thread Group والتحقّق من أنّ جهاز توجيه الحدود في شبكة Thread معتمَد من Thread Group.

  • معلومات شبكة Wi-Fi:

    <key>com.apple.developer.networking.wifi-info</key>
    <true/>
    
  • مجموعات التطبيقات: أضِف مجموعة تطبيقات مشترَكة للسماح لتطبيقك الرئيسي وإضافة Matter Add Device Extension بالتواصل (على سبيل المثال، group.com.yourdomain.appgroupname). ينشئ المطوّر رقم التعريف هذا ويسجّله في Apple Developer Console، ويجب أن يتطابق مع مجموعة التطبيقات التي تم ضبطها في إمكانات الهدف في Xcode. تستخدِم حزمة تطوير البرامج (SDK) من Google Home رقم التعريف هذا في كلا الهدفَين لمزامنة حالة التشغيل وبيانات اعتماد الشبكة وقوائم الغرف تلقائيًا باستخدام حاوية UserDefaults مشترَكة.

مشاركة سلسلة المفاتيح (اختياري)

إذا كانت إضافة تطبيقك بحاجة إلى استرداد بيانات الاعتماد أو رموز الوصول التي يخزّنها التطبيق الرئيسي باستخدام UserInfo.authorizationToken()، عليك ضبط مجموعة وصول مشترَكة إلى سلسلة المفاتيح لكلّ من التطبيق الرئيسي وأهداف إضافة التطبيق في ملفات entitlements plist:

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

خصائص Info.plist

أدرِج مفاتيح الوصف التالية في Info.plist لهدف التطبيق الرئيسي:

  • وصف استخدام الموقع الجغرافي:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Your custom message explaining why location access is needed to read the current Wi-Fi SSID</string>
    
  • خدمات Bonjour: ضِمن NSBonjourServices، أدرِج الخدمات المطلوبة لاكتشاف Matter وThread محليًا:

    <key>NSBonjourServices</key>
    <array>
        <string>_matter._tcp</string>
        <string>_matterc._udp</string>
        <string>_matterd._udp</string>
        <string>_meshcop._udp</string>
    </array>
    
  • وصف استخدام الشبكة المحلية: أدرِج المفتاح NSLocalNetworkUsageDescription مع رسالة توضّح أذونات اكتشاف الشبكة المحلية.

تشغيل جهاز

لتشغيل جهاز Matter:

  1. أرسِل إشعارًا إلى Home APIs iOS SDK للاستعداد لطلبات Matter تشغيل باستخدام structure.prepareForMatterCommissioning(). سينفّذ هذا الأمر ما يلي:

    • التحقّق من منح الإذن
    • التأكّد من أنّ المركز متصل بالإنترنت ويمكن الوصول إليه
    • التأكّد من عدم وجود جلسة تشغيل نشطة أخرى قيد التنفيذ
    do {
      try await structure.prepareForMatterCommissioning()
    } catch {
      // Failed to prepare for Matter Commissioning
      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 {
      // 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. أنشِئ App Group ID في Apple Developer Console للسماح للتطبيق بالتواصل مع إضافة 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.

    يعرض الرمز النموذجي مثالاً على تنفيذ فئة فرعية من واجهة برمجة التطبيقات MatterAddDeviceExtensionRequestHandler من Apple.

    كحدّ أدنى، أضِف إطار GoogleHomeMatterCommissionerSDK Framework إلى هدف الإضافة وألغِ ثلاث طرق لاستدعاء Google Home platformHomeMatterCommissioner واجهات برمجة التطبيقات.

    • 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
        }
      }
    }