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
    • 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 Versions and GitHub Sync Note Insights 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # The First message ###### tags: `CHIP` `Matter` `Firmware` `Engineer` > 2022/04/16 > CHIP git hash code 67b4746ad8 I like to learn stuff by taking them apart, so I think a walk through on the message path would be a good idea to undetstand how CHIP works. ## Setup - Python controller running on MAC - Lock-app running on thunderboard sense 2 - OpenThread(Not going to use this, but still) ## connect -ble Usually, the first message would be the controller trying to connect to device over BLE so that they could start the first handshaking process(PASE). In this case, we can use command "connect -ble" on python contoller to simulate. In this file controller/python/chip-device-ctrl.py, we have the function do_connect and can find this: ```python = 578 elif args[0] == "-ble" and len(args) >= 3: self.devCtrl.ConnectBLE(int(args[1]), int(args[2]), nodeid) ``` We will start with this line of code. ### EstablishPASEConnection From the above function, it's quite easy to follow the calling stack to this function: DeviceCommissioner::EstablishPASEConnection in controller/CHIPDeviceController.cpp. :::info For each function we are going to read later, I cannot check each line of code, but I will try to give you a brief idea of each function and focus on the "path". ::: In this function, it's preparing two things: 1. the session object which will be our handshaking session. 2. the device, as its type suggests, you can image this object is the proxy of the device we are going to committed. As you go along this function, you will find this line of code: ```cpp=854 err = device->GetPairing().Pair(params.GetPeerAddress(), params.GetSetupPINCode(), keyID, Optional<ReliableMessageProtocolConfig>::Value(mMRPConfig), exchangeCtxt, this); ``` This is acutallly asking the PASE session object to start the pairing process. To understand the arguments, please read the comment on this API in protocols/secure_channel/PASESession.h. ### Pair PASESession::Pair is a pretty short function, it just initializes itself and sends the first request of the PEAK process. So the next funciton is PASESession::SendPBKDFParamRequest. ### SendPBKDFParamRequest In this function, it would put all the data to the message buffer as you can see there is a TLVWriter. :::info TLV = Tag-Length-Value, please check lib/core/CHIPTLV.h for more information ::: After finalizing the message buffer, it would use the exchange context object to send out the message. ```cpp=398 ReturnErrorOnFailure( mExchangeCtxt->SendMessage(MsgType::PBKDFParamRequest, std::move(req), SendFlags(SendMessageFlags::kExpectResponse))); ``` ### SendMessage(ExchangeContext) In this function, it would decide if there is an ack to deal with and send the message out by dispatch object. ```cpp=164 CHIP_ERROR err = mDispatch->SendMessage(mSession.Get(), mExchangeId, IsInitiator(), GetReliableMessageContext(), reliableTransmissionRequested, protocolId, msgType, std::move(msgBuf)); ``` #### Who is the mDispatch In the ctor of ExchangeContext class, we can find out that the dispatch comes from delegate, and delegate comes from the argument of the ctor. ```cpp=251 ExchangeContext::ExchangeContext(ExchangeManager * em, uint16_t ExchangeId, SessionHandle session, bool Initiator, ExchangeDelegate * delegate) { ... ... dispatch = delegate->GetMessageDispatch(em->GetReliableMessageMgr(), em->GetSessionManager()); } ``` And in DeviceCommissioner::EstablishPASEConnection, we can find this: ```cpp=845 exchangeCtxt = mSystemState->ExchangeMgr()->NewContext(session.Value(), &device->GetPairing()); ``` So, voilà, the dispatch comes from the PASE sessioin object itself(&device->GetPairing()). And it's pretty reasonable because PASE is the only session for now. Next, if you check the definiion of PASESession, you will find this: ```cpp=94 class DLL_EXPORT PASESession : public Messaging::ExchangeDelegate, public PairingSession ``` So the PASESession has this function(in protocols/secure_channel/PASESession.h): ```cpp=232 Messaging::ExchangeMessageDispatch * GetMessageDispatch(Messaging::ReliableMessageMgr * rmMgr,SessionManager * sessionManager) override { return &mMessageDispatch; } ... SessionEstablishmentExchangeDispatch mMessageDispatch; ``` And the definition of SessionEstablishmentExchangeDispatch is ```cpp=32 class SessionEstablishmentExchangeDispatch : public Messaging::ExchangeMessageDispatch ``` Since SessionEstablishmentExchangeDispatch doesn't override or overload SendMessage and Messaging::ExchangeMessageDispatch has implemented the SendMessage, we have this: ``` mDispatch->SendMessage ``` = ``` Messaging::ExchangeMessageDispatch::SendMessage ``` ### SendMessage(Messaging::ExchangeMessageDispatch) In this function, it would check if there is another messages we shuold send before the current message. For instance, piggyback ack. After that, it would call this function: ```cpp=86 CHIP_ERROR err = SendPreparedMessage(session, entryOwner->retainedBuf); ``` ### SendPreparedMessage(SessionEstablishmentExchangeDispatch) Nothing special ### SendPreparedMessage(SessionManager) This function would decide the destination of the message from given session handler and call this: ```cpp=259 return mTransportMgr->SendMessage(*destination, std::move(msgBuf)); ``` ### SendMessage(BLEBase) :::info If you don't know how we jump into this class(BLEBase), please check this note [Transport classes](/Z_moHsElR9GWjd1R0_WJww) ::: It simply calls the Send of BLEEndpoint. ### Send It would queue up the messsage and try to send it out by calling DriveSending. ### DriveSending This function is really long and hard to understand(thanks to the BtpEngine). But if you look into it carefully, you will find something we need now: ```cpp=1011 else if (mBtpEngine.TxState() == BtpEngine::kState_Idle) // Else send next message fragment, if any. { // Fragmenter's idle, let's see what's in the send queue... if (!mSendQueue.IsNull()) { /* * The queue has the message we just queued in the above step(Send), * and the TxState should be idle because this is the very first message */ // Transmit first fragment of next whole message in send queue. ReturnErrorOnFailure(SendNextMessage()); } else { // Nothing to send! } } ``` ### SendNextMessage It would dequeue the message from queue and calls this: ```cpp=745 ReturnErrorOnFailure(SendCharacteristic(mBtpEngine.BorrowTxPacket())); ``` ### SendCharacteristic Simply call this: ``` SendWrite(std::move(buf)) ``` ### SendWrite We have this: ```cpp=1405 return mBle->mPlatformDelegate->SendWriteRequest(mConnObj, &CHIP_BLE_SVC_ID, &mBle->CHIP_BLE_CHAR_1_ID, std::move(buf)); ``` The mBle is the BleLayer object, so CHIP stack will jump into platform specific implementation. Bacause of that, the following functions are just for my setup(Python controller on MAC because this command is sent out by controller). #### who is mPlatformDelegate :::info You may want to review this: [CHIP stack initialization](/s92NzALfTUuoo5fdWt6Skg) ::: In include/platform/internal/GenericPlatformManagerImpl.cpp , ``` GenericPlatformManagerImpl<ImplClass>::_InitChipStack() ``` we have this: ``` err = BLEMgr().Init(); ``` go to platform/Darwin/BLEManagerImpl.cpp, we have this ``` BlePlatformDelegateImpl * platformDelegate = new BlePlatformDelegateImpl(); err = BleLayer::Init(platformDelegate, connDelegate, appDelegate, &DeviceLayer::SystemLayer()); ``` This is where BleLayer gets initialized, and the delegate is the BlePlatformDelegateImpl class. ### SendWriteRequest We can indeed find this function in platform/Darwin/BlePlatformDelegateImpl.mm. But the rest is really not all about CHIP stack and I am not familiar with MAC BLE framework. So I will stop here. ## The end I know it's kind of confusing if we simply just check the calling stack, but it's a way to understand the entire CHIP stack. We got to start at some point. I will try to have some class/structure diagrams to help us understand this calling stack better next time.

    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