# 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.