WWDC Quick Look 💓 By SwiftGGTeam
Add support for Matter in your smart home app

Add support for Matter in your smart home app

Watch original video

Highlight

Apple has integrated Matter into HomeKit in iOS, iPadOS and tvOS 15 developer preview, and provided new setup API and CHIP.framework so that smart home apps can configure, pair and control Matter accessories.

Core Content

Smart home apps have to face a real problem in the past: the same home may have lights, sockets, sensors and central controls from different manufacturers. Each manufacturer maintains its own protocol, and App developers also have to write a lot of proprietary logic for connection, pairing, status reading, and remote control.

Matter (a standard for smart home connectivity) wants to fix this. It was developed by Apple and other industry players with the goal of letting smart home accessories work together using a unified protocol. It was mentioned in the speech that the early name of Matter was Connected Home over IP, or CHIP for short, so you will still see it in the sample API.CHIPname.

Apple’s approach is two-tiered.

The first layer is HomeKit. In the iOS 15 developer preview, HomeKit will access Matter as a parallel protocol. Existing HomeKit Apps continue to call the original API, QR code scanners begin to recognize Matter QR codes, and status reading, writing, notifications, remote access, scenes, and automation also follow the HomeKit model.

The second layer is the new setup API. Some apps require Matter accessories to be connected to their own smart home hub. Apple provides system UI, topology objects, and App Extension callbacks. The App tells the system which homes and rooms it manages. The system is responsible for scanning, page flow and error handling, and the extension is responsible for completing pairing and configuration using CHIP.framework.

Connect to Matter via HomeKit

The value of HomeKit is to shield the underlying protocol. Users use the same process to add accessories, and the App uses the same set of APIs to manage accessories. Developers do not need to first determine whether this is a HAP device or a Matter device.

This solves the most common access cost: existing HomeKit apps don’t need to rewrite accessory addition points. The user scans the Matter QR code, and the system continues with the familiar HomeKit setup process.

Connect to your own hub through setup API

If your app manages its own home hub, you need to tell the system which homes and rooms the app manages. The system UI displays these choices. After the user completes the selection, iOS calls the extensionHMCHIPServiceRequestHandlersubclass to let the extension do three things: pair accessories, return a list of rooms, and configure names and rooms.

In this way, the app retains its own topology and hub logic while getting Apple’s system-level accessory adding experience.

Use CHIP.framework to control accessories

Matter’s data model consists of endpoint, cluster, attribute and action. A light may have an endpoint representing the light itself, which contains an on-off cluster, and the cluster contains attributes representing the switch status. CHIP.framework exposes these concepts as code interfaces.

After developers get the paired device, they can create a cluster object and then perform operations such as toggle and read attribute. The lecture uses a light bulb switch as an example to show the complete path from the device ID to reading the status.

Detailed Content

1. Existing HomeKit API starts to recognize Matter QR code

04:58

In the speech, Apple first showed off the existing HomeKit access to add accessories. In the iOS 15 developer preview, the QR code scanner called by this portal will recognize the HAP QR code and the Matter QR code.

home.addAndSetupAccessories() { error in
    if let error = error {
         print("Error occurred in accessory setup \(error)")
    } else {
         print("Successfully added accessory to HomeKit")
    }
}

Key points:

  • home.addAndSetupAccessories()Start the HomeKit system addition process.
  • in closureerrorIndicates whether the adding process failed. -if let error = errorHandle errors during scanning, pairing, or setup. -elseThe branch indicates that the accessory has been successfully added to HomeKit.
  • In iOS 15 developer preview, the same scanning process will start to recognize Matter QR code.

The key point of this code is that “no new entry is needed”. If you already have a HomeKit app and have added HAP accessories using this API, you can use the same entry point to start testing Matter accessories.

2. Start Matter setup API with topology object

09:12

When the App needs to connect Matter accessories to its own home hub, it must first hand over the home list managed by the App to the system. The system displays the selection page based on this topology.

let homes = proprietaryHomeStorage.homes.map { home in
    HMCHIPServiceHome(uuid: home.uuid, name: home.name)
}

let topology = HMCHIPServiceTopology(homes: homes)
let setupManager = HMAccessorySetupManager()

do {
    try await setupManager.addAndSetUpAccessories(for: topology)
    print("Successfully added accessory to my app")
} catch {
    print("Error occurred in accessory setup \(error)")
}

Key points:

  • proprietaryHomeStorage.homesIt is the family list saved by the app itself. -mapConvert your own home toHMCHIPServiceHome,reserveuuidandname
  • HMCHIPServiceTopology(homes:)Describes the collection of homes that this App can manage. -HMAccessorySetupManager()Create a system accessory settings manager. -try await setupManager.addAndSetUpAccessories(for:)Start the Matter accessory addition process and use Swift async/await to handle the results. -catchCatching errors in the setup process.

The speech mentioned that if the topology has only one home, the system will skip the home selection card because the user’s intention is already clear. If there are multiple homes, the system will ask the user to choose which home to add to.

3. Extension responsible for matchmaking, room list and configuration

11:27

The system UI of the setup API is responsible for scanning and page flow. The actual pairing and configuration is done by the App Extension. Extensions require inheritanceHMCHIPServiceRequestHandler, and override three methods.

class RequestHandler: HMCHIPServiceRequestHandler, CHIPDevicePairingDelegate {

    override func rooms(in: HMCHIPServiceHome) async throws -> [HMCHIPServiceRoom] {
        // iOS is querying for rooms that match the given home.  These rooms will be shown in system UI and the selection will be vended back to your extension's `configureAccessory` function
   }

    override func pairAccessory(in: HMCHIPServiceHome, onboardingPayload: String) async throws -> Void {
        // iOS is instructing the extension to pair the accessory via CHIP.framework
   }

    override func configureAccessory(named accessoryName: String, room accessoryRoom: HMCHIPServiceRoom) async throws -> Void {
       // iOS is instructing the extension to apply configuration via CHIP.framework.
    }
}

Key points:

  • RequestHandlerIs the main request processing class of the extension. -HMCHIPServiceRequestHandlerReceive setup requests from iOS. -CHIPDevicePairingDelegateUsed to participate in the CHIP.framework pairing process. -rooms(in:)Returns the list of rooms under the specified home, and the system UI will display these rooms to the user. -pairAccessory(in:onboardingPayload:)Receive the scanned Matter onboarding payload and establish a secure pairing via CHIP.framework. -configureAccessory(named:room:)Receive the accessory name and room entered by the user, and write the configuration through CHIP.framework.

The speech clearly stated that after developers implement these three methods, UI display, step switching and error handling are handled by the system. This allows apps to focus their code on their home hub and Matter pairing logic.

4. Understand the Matter data model

12:29

Matter accessories expose capabilities through the data model. The speech is explained in four layers: endpoint (endpoint), cluster (capability collection), attribute (status value) and action (action).

// Matter data model used in the session:
// Accessory
// └── Endpoint: lightEndpoint
//     └── Cluster: CHIPOnOff
//         └── Attribute: OnOff
//             ├── Action: toggle
//             └── Action: readAttributeOnOff

Key points:

  • EndpointRepresents an individually addressable logical function in an accessory, such as an information endpoint or a light endpoint. -ClusterRepresents some capability of the endpoint, such as brightness, color, or power control. -AttributeIndicates the status of accessories, such as the switch status of a light. -ActionRepresents the operations supported by the attribute, such as reading, writing, and reporting.
  • The speech compared cluster to HomeKit service and attribute to HomeKit characteristic.

This structure helps understand the control code that follows. You first find the device, then locate the endpoint, then create the cluster, and finally initiate an operation on the attribute.

5. Use CHIP.framework to control the switch state of the light

14:27

Apple demonstrates how to interact with light accessories via the CHIP.framework. The code starts from the shared controller, gets the paired device, then creates the on-off cluster, and finally performs toggle and reads the status.

let controller = CHIPDeviceController.shared()
do {
    let device = try controller.getPairedDevice(accessoryDeviceID)
    let onOffCluster = CHIPOnOff(device: device,
                               endpoint: lightEndpoint,
                                  queue: DispatchQueue.main)
    onOffCluster?.toggle({ (error, values) in
        // Error handling code here
    })
    onOffCluster?.readAttributeOnOff(responseHandler: { error, response in
        if let state = response?[VALUE_KEY] as? NSInteger {
           updateLightState(state: state)
        }
    })
} catch {
    print("Error occurred in accessory control \(error)")
}

Key points:

  • CHIPDeviceController.shared()Get the shared controller of CHIP.framework. -controller.getPairedDevice(accessoryDeviceID)Gets the accessory handle using the device ID assigned when pairing. -CHIPOnOff(device:endpoint:queue:)Creates an on-off cluster handle for the specified light endpoint. -DispatchQueue.mainSpecify the callback queue, which is used in the example to update the application interface status. -onOffCluster?.toggleRequests to switch the state of the on-off attribute. -readAttributeOnOffRequests to read the current status of the on-off attribute. -response?[VALUE_KEY] as? NSIntegerGet the status value from the response dictionary. -updateLightState(state:)Update the app’s internal state or interface with the read results. -catchHandle control errors such as failure to obtain paired devices.

This code corresponds to the actual use of the Matter data model: device ID positioning accessory, endpoint positioning light, cluster positioning power control capability, attribute operation completion status reading and control.

6. Manage multiple connected admins

15:29

Matter allows multiple admins to connect to the same accessory at the same time. The Home app therefore adds a Connected Services area, allowing users to view which admins an accessory is currently connected to, and re-enable pairing mode to allow new admins to access.

// Home app management model described in the session:
// 1. Show connected admins under Connected Services.
// 2. Let users manage connected admins.
// 3. Let users turn on pairing mode again.

Key points:

  • Connected ServicesIs the area in the Home app where connected admins are displayed.
  • Multiple admin allows users to connect the same Matter accessory to multiple ecosystems or hubs.
  • After re-enabling pairing mode, new admins can connect to the same accessory.
  • This part of the capability is demonstrated by the Home app, and the third-party API code is not given in the speech.

This is important for app design. Accessories may be managed by multiple systems, and the App’s status page should be able to accept the reality that “the same device is managed by other parties.”

Core Takeaways

  1. What to do: Add an entry to the existing HomeKit App to add Matter accessories. Why it’s worth doing:addAndSetupAccessories()Matter QR code will start to be recognized in iOS 15 developer preview. How ​​to get started: Check the existing HomeKit add flow in your app to make sure it callshome.addAndSetupAccessories(), and then use the developer profile and Matter developer preview environment to test the scan code.

  2. What to do: Perform system-level Matter accessory setup process for your own smart home hub. Why it’s worth doing:HMAccessorySetupManagerYou can use the system UI to scan the code and select home, and the extension only handles business logic. How ​​to start: Convert your own home toHMCHIPServiceHome,createHMCHIPServiceTopology, calladdAndSetUpAccessories(for:), then realizeHMCHIPServiceRequestHandlerExtension.

  3. What to do: Make a Matter light bulb control page. Why it’s worth doing: CHIP.framework exposes controller, device, cluster and attribute operation paths. How ​​to start: UseCHIPDeviceController.shared()To get the controller, usegetPairedDeviceGet the device and then passCHIPOnOffimplementtoggleandreadAttributeOnOff

  4. What to do: Display the room and configuration status of accessories on the device details page. Why is it worth doing: The setup API will let the user chooseHMCHIPServiceRoomand the accessory name to the extension. How ​​to start: InconfigureAccessory(named:room:)Write the name, room and accessory ID to the App’s own storage, and the device details page reads this data.

  5. What to do: Prompt the user that “there may be other managers for this accessory”. Why it’s worth doing: Matter supports multiple admins, and the Home app will display Connected Services. How ​​to start: Design the connected services area on the device management page to indicate that accessories can be managed by multiple admins; the specific available APIs are subject to Apple’s subsequent documents and Matter open source API.

Comments

GitHub Issues · utterances