CYSE
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Exchange Context [![hackmd-github-sync-badge](https://hackmd.io/oiu658t8T5KCHsRmHGPLQg/badge)](https://hackmd.io/oiu658t8T5KCHsRmHGPLQg) ###### tags: `CHIP` `Matter` `Firmware` `Engineer` > 2022/07/30 > CHIP git hash code 67b4746ad8 ## What is it I would like to consider Exchange Context(EC) as a "channel" in each seassion. Every device/controller would hold a peer's session if they are connected. However, there are many different types of messages would be sent between controller/device, so we need a specified channel to handle each type of message. ![](https://i.imgur.com/nllpfKh.jpg) In addition, these ECs have been running in a session, so they could use all the resource of the session. That is, EC is not like session which has extreme complicated establishment process. A lot of time, CHIP stack would create a new EC just for one message. Thus, EC is also kind of a temporary channel. ## How EC works Assume we are using python controller to commit a device by BLE. Let's start with the very first message: SendPBKDFParamRequest. ### Send PBKDFParamRequest At the beginning of PASE, there is a PASE session to handle the PASE handshaking. So, the EC would be created in this session. Here is how the controller creates the EC. In DeviceCommissioner::EstablishPASEConnection, we can find that the controller creates the EC with the current session, which is PASE session. ```cpp=845 /* the second parameter is the delegate, which would be used by the EC later */ exchangeCtxt = mSystemState->ExchangeMgr()->NewContext(session.Value(), &device->GetPairing()); ``` After creating this EC, controller would call Pair with the pointer of this EC. ```cpp=854 err = device->GetPairing().Pair(params.GetPeerAddress(), params.GetSetupPINCode(), keyID,Optional<ReliableMessageProtocolConfig>::Value(mMRPConfig), exchangeCtxt, this); ``` In the Pair function, it will prepare many things for PASE, and call SendPBKDFParamRequest. In SendPBKDFParamRequest, we have this: ```cpp=398 mExchangeCtxt->SendMessage(MsgType::PBKDFParamRequest, std::move(req), SendFlags(SendMessageFlags::kExpectR... ``` The mExchangeCtxt is exactly the exchangeCtxt the controller created in EstablishPASEConnection. And if we go along with the calling stack, we will find that the CHIP stack would add the ID of this EC to the message in ExchangeMessageDispatch::SendMessage: ```cpp=51 payloadHeader.SetExchangeID(exchangeId).SetMessageType(protocol, type).SetInitiator(isInitiator); ``` Remember that there is an exchange ID in the message, we are going to use this later. ### Receive PBKDFParamRequest On the device side, we can first look at ExchangeManager::OnMessageReceived. In this function, it will 1. Try to find an existed EC which has the same ID in the message. 2. If not, create a new EC to handle this message if nedded.(with the current session, this ExchangeManager knows the current session) And, this is the first message this device ever gets, so it would of course create a new EC to handle this PBKD param request. But, this device will **create the EC with the ID in the message.** ```cpp=289 mContextPool.CreateObject(this, payloadHeader.GetExchangeID(), session, !payloadHeader.IsInitiator(), delegate); ``` At this moment, controller and device have a EC established by a common EC ID. After that, the device will hand over the message to the EC and send out SendPBKDFParamResponse. ### Recive SendPBKDFParamResponse On the controller side, we also look at the ExchangeManager::OnMessageReceived. This time, the controller will **find an existed EC with the same ID from device**, and bypass the message to the found EC. ### The log If you open the detail option in the makefile on the controller or device project, you will find the EC ID is the same during the PASE. For example, on the contoller side, ```shell Prepared plaintext message 0x70000d319ae0 to 0x0000000000000000 (0) of type 0x20 and protocolId (0, 0) on exchange 35571i with ... Received message of type 0x21 with protocolId (0, 0) and MessageCounter:856765985 on exchange 35571i ... Prepared plaintext message 0x70000d296f60 to 0x0000000000000000 (0) of type 0x22 and protocolId (0, 0) on exchange 35571i ... Received message of type 0x23 with protocolId (0, 0) and MessageCounter:856765986 on exchange 35571i ... ``` But later on, it created another EC to handle the certification exchange: ```shell= Prepared encrypted message 0x70000d31a0a0 to 0x000000000000001F (1) of type 0x8 and protocolId (0, 1) on exchange 35572i with Mes... ``` ### when does EC get freed? Currently, we just keep creating ECs. But there must be somewhere these ECs are deleted from heap. And this is how the CHIP stack frees the ECs in ExchangeContext::HandleMessage: ```cpp=425 auto deferred = MakeDefer([&]() { // The alreadyHandlingMessage check is effectively a workaround for the fact that SendMessage() is not calling // MessageHandled() yet and will go away when we fix that. if (alreadyHandlingMessage) { // Don't close if there's an outer HandleMessage invocation. It'll deal with the closing. return; } // We are the outermost HandleMessage invocation. We're not handling a message anymore. mFlags.Clear(Flags::kFlagHandlingMessage); // Duplicates and standalone acks are not application-level messages, so they should generally not lead to any state // changes. The one exception to that is that if we have a null mDelegate then our lifetime is not application-defined, // since we don't interact with the application at that point. That can happen when we are already closed (in which case // MessageHandled is a no-op) or if we were just created to send a standalone ack for this incoming message, in which case // we should treat it as an app-level message for purposes of our state. if ((isStandaloneAck || isDuplicate) && mDelegate != nullptr) { return; } MessageHandled(); }); ``` This lambda would be executed after the control flow goes out of this function(HandleMessage). ```cpp=495 void ExchangeContext::MessageHandled() { #if CONFIG_DEVICE_LAYER && CHIP_DEVICE_CONFIG_ENABLE_SED UpdateSEDPollingMode(); #endif if (mFlags.Has(Flags::kFlagClosed) || IsResponseExpected() || IsSendExpected()) { return; } Close(); } ``` And in the MessageHandled, the EC would be released if no one needs this EC anymore. ## Conclusion The above is how controller and device talk to each other on the same EC. Although, most of time, EC would just bypass all the works to the delegate object and actually do nothing to the message, it is still important key factor to handle all the messages independently between controller and device.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully