无线连接知识库

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 

Wireless Connectivity Knowledge Base

讨论

排序依据:
I want to share with you the information that I found about Indication and notification. I hope this information help you to understand more about these topics. Indication and notifications are commands that could be send through the attribute(ATT) protocol. So, there are two roles defined at the ATT layer: Client devices access remote resources over a BLE link using the GATT protocol. Usually, the master is also the client but this is not required or mandatory. Server devices have the GATT database, access control methods, and provide resources to the remote client. Usually, the slave is also the server. BLE standard define two ways to transfer data for the server to the client: notification and indication. Maximum data payload size defined by the specification in each message is 20 bytes. Notifications and indications are initiated by the Server but enabled by the Client. Notification don't need acknowledged, so they are faster. Hence, server does not know if the message reach to the client. Indication need acknowledged to communicated. The client sent a confirmation message back to the server, this way server knows that message reached the client. One interesting thing defined by the ATT protocol is that a Server can't send two consecutive indications if the confirmation was not received. In other words, you have to wait for the confirmation of each indication in order to send the next indication. Figure 1. Indication/Notification Nevertheless, server are not able to send indications or notifications at the beginning of the communication. First, client must enable notifications and indications permissions on the server side, so, the server is allowed to send indications or notifications. This procedure involves the client to write the Client Characteristic Configuration Descriptor (CCCD) of the characteristic that will be notified/indicated. In other words, the client may request a notification for a particular characteristic from the server. Once the client enabled the notifications for such characteristic in the server, server can send the value to the client whenever it becomes available. For example, thinking in a heart rate sensor application connecting to Heart Rate smartphone application. Heart Rate Service can notify its Heart Rate Measurement Characteristic.  In this case, the sensor is the server while the smartphone is the client. Once devices are connected, smartphone application must set the notifications permissions of the Heart Rate Measurement Characteristic through its CCCD. Then, when smartphone application(client) set the CCCD withe notifications enabled, Heart Rate Sensor (server) is able to send notifications whenever a heart rate measurement is available. This same procedure is needed if the characteristic has indication properties.  At the end, the client is the one that allow the server to indicate or notify a characteristic. Finally, it is worth to comment that unlike notification, the indication is more reliable, but slower, because the server sends the data but the client must to confirm when data is received.
查看全文
View the Webinar Recording
查看全文
This Document describes the additional changes needed for JN-AN-1229 ZigBee PRO Application Template for ZigBee version 1002 to be able to compile correctly with the latest update SDK JN-SW-4170 Version 1745 and JN-SW-4270 Version 1746. Note:  These modifications can be also found in the JN516x ZigBee 3.0 SDK Release Notes v1745 (Chapter 4.3 Modifications Required) Tool modifications The .zpscfg file contains all the information available of the setup of the ZigBee network, this file it’s located in C:\...\...\workspace\ JN-AN-1229\Common The first step is to add the MAC Interface List to The ZigBee devices (Co-ordinator, Router, and Sleeping End Device) in the .zpscfg file. Then, add the MAC Interface selecting the New Child option. In the Properties tab, the Co-ordinator and the Router should have the Router Allowed option set to True. Stack modifications The new stack has support for better throughput and automatic buffering of data packets during route discovery. This requires the addition of a new queue in the application. Open the app_common.h file which it’s located in the Common folder. This queue should be tied to the stack definition: extern PUBLIC tszQueue zps_msgMcpsDcfm; After that, open the app_router.c and app_sleeping_enddevice.c. The ZPS_tsAplAib structure has been changed, so, the vStartup function should be modified Old version /* Set channel to scan and start stack */ ZPS_psAplAibGetAib()->apsChannelMask = 1 << u8Channel; Update needed /* Set channel to scan and start stack */ ZPS_psAplAibGetAib()->pau32ApsChannelMask[0] = 1 << u8Channel; Add the next code to the app_start.c(Coordinator and Router) and app_start_SED.c(Sleeping End Device) The buffer of the Router device should be modified. The size of the queue is defined as: #define MCPS_DCFM_QUEUE_SIZE 5 The storage of the queue must be defined: PRIVATE MAC_tsMcpsVsCfmData asMacMcpsDcfm[MCPS_DCFM_QUEUE_SIZE]; In the APP_vInitResources function an additional queue must be added: ZQ_vQueueCreate(&zps_msgMcpsDcfm, MCPS_DCFM_QUEUE_SIZE,  sizeof(MAC_tsMcpsVsCfmData),(uint8*)asMacMcpsDcfm);  
查看全文
The SMAC & IEEE 802.15.4 protocol stacks are a KSDK add-on, therefore you need the installation of the KSDK 1.2 before installing these connectivity stacks. Install the Kinetis SDK 1.2: Software Development Kit for Kinetis MCUs|Freescale After installing the KSDK 1.2, download the desired protocol stack. The connectivity software for this platform can be found in the board webpage, in the downloads tab: Modular Reference Boards for Kinetis KW0x|Freescale The installation window will guide you through an easy way to install the software. Best regards, Luis Burgos.
查看全文
One of the most difficult part of creating connected medical applications is, actually, keep it connected. Different protocols are available to transmit information from a medical device to a database or user interface. Sometimes integrating our application to the current communication protocols can be as difficult as developing the device itself. Freescale has launched its Bluetooth® Low Energy (BLE) chips, and with them, a complete software stack that integrates most of the available profiles for BLE oriented applications. Using this set, it becomes easy to integrate your current medical application to use BLE as communications method. Freescale Connectivity Software Examples The connectivity software includes examples to demonstrate BLE communications with a smartphone device. Using these examples as a base facilitates the integration with an existing application and reduces the required time it takes to have a fully connected application. This post uses as an example the Heart Rate Monitor demo to show how these applications can be customized. Modifying general device information The BLE services information reported by the device is stored in a file named “gatt_db.h”. This services information is what is shown on a smartphone when the device has connected. The Generic Access Profile service includes the device name reported when advertising. To change it just replace the device name between “” and update the character count. Detailed device information is accessed via the Device Information Service including the manufacturer name, model and serial number etcetera. This information can also be adjusted to the custom device requirements by modifying the string between “” and updating the character number. Adapting example code to report application data The connectivity software includes some predefined services that can be used to customize the server to report our application data. These predefined services already include structures with the information that needs to be reported to the client. On the application example file app.c some of these services are configured. For the heart rate service, a variable of type hrsConfig_t is created containing configuration information of the heart rate sensor such as the supported characteristics and sensor location. All of these characteristics are described in the heart rate service file heart_rate_interface.h /* Service Data*/ static basConfig_t      basServiceConfig = {service_battery, 0}; static disConfig_t      disServiceConfig = {service_device_info}; static hrsUserData_t    hrsUserData; static hrsConfig_t hrsServiceConfig = {service_heart_rate, TRUE, TRUE, TRUE, gHrs_BodySensorLocChest_c, &hrsUserData}; static uint16_t cpHandles[1] = { value_hr_ctrl_point }; /*! Heart Rate Service - Configuration */ typedef struct hrsConfig_tag {     uint16_t             serviceHandle;     bool_t               sensorContactSupported;     bool_t               sensorContactDetected;     bool_t               energyExpandedEnabled;     hrsBodySensorLoc_t   bodySensorLocation;     hrsUserData_t        *pUserData; } hrsConfig_t; This information is used to configure the server when the function BleApp_Config is called. /* Start services */ hrsServiceConfig.sensorContactDetected = mContactStatus; #if gHrs_EnableRRIntervalMeasurements_d    hrsServiceConfig.pUserData->pStoredRrIntervals = MEM_BufferAlloc(sizeof(uint16_t) * gHrs_NumOfRRIntervalsRecorded_c); #endif    Hrs_Start(&hrsServiceConfig); basServiceConfig.batteryLevel = BOARD_GetBatteryLevel(); Bas_Start(&basServiceConfig); /* Allocate application timers */ mAdvTimerId = TMR_AllocateTimer(); Once the server is configured, the application is stated by entering the device in advertising state in order to make it visible for clients. This is done by calling the function BleApp_Advertise that configures the server to start advertising. void BleApp_Start(void) { /* Device is not connected and not advertising*/ if (!mAdvState.advOn) { #if gBondingSupported_d if (mcBondedDevices > 0) { mAdvState.advType = fastWhiteListAdvState_c; } else { #endif mAdvState.advType = fastAdvState_c; #if gBondingSupported_d } #endif BleApp_Advertise(); } #if (cPWR_UsePowerDownMode)    PWR_ChangeDeepSleepMode(1); /* MCU=LLS3, LL=DSM, wakeup on GPIO/LL */ PWR_AllowDeviceToSleep(); #endif       } Once the server has been found and a connection has been stablished with the client, the configured services must be started. This is done by calling the “subscribe” function for each service. For heart rate sensor, the function Hrs_Suscribe must be called. This function is available from the heart_rate_interface files. /* Subscribe client*/ Bas_Subscribe(peerDeviceId);        Hrs_Subscribe(peerDeviceId); #if (!cPWR_UsePowerDownMode)  /* UI */            During connection, the application measurements can be reported to the client by using the “record measurement” functions included in the service interfaces. For the heart rate sensor this is the Hrs_RecordHeartRateMeasurement function. static void TimerMeasurementCallback(void * pParam) { uint16_t hr = BOARD_GetPotentiometerLevel(); hr = (hr * mHeartRateRange_c) >> 12; #if gHrs_EnableRRIntervalMeasurements_d    Hrs_RecordRRInterval(&hrsUserData, (hr & 0x0F)); Hrs_RecordRRInterval(&hrsUserData,(hr & 0xF0)); #endif if (mToggle16BitHeartRate) { Hrs_RecordHeartRateMeasurement(service_heart_rate, 0x0100 + (hr & 0xFF), &hrsUserData); } else { Hrs_RecordHeartRateMeasurement(service_heart_rate, mHeartRateLowerLimit_c + hr, &hrsUserData); } Hrs_AddExpendedEnergy(&hrsUserData, 100); #if (cPWR_UsePowerDownMode) PWR_SetDeepSleepTimeInMs(900); PWR_ChangeDeepSleepMode(6); PWR_AllowDeviceToSleep();    #endif } This updates the current measurement and sends a notification to the client indicating that a new measurement report is ready. Many profiles are implemented in the connectivity software to enable already developed medical applications with BLE connectivity. APIs are easy to use and can significantly reduce the development times.
查看全文
802.15.4 wireless sniffers like the USB-KW41Z are capable of capturing over-the-air traffic. The captured packets are passed to a network protocol decoder like Wireshark over a network interface tunnel built by the Kinetis Protocol Analyzer.   Hardware  One USB-KW41Z preloaded with sniffer firmware ( instructions found at www.nxp.com/usb-kw41z )  Software Download & Install Thread Wireshark from wireshark.org which is an open-source network protocol analyzer capable of debugging over the air communication between Thread devices. Kinetis Protocol Analyzer is a software that provides a bridge between the USB-KW41 and Wireshark.  Wireshark Configuration  Open Wireshark from the Program Files Click Edit and select Preferences  Click Protocols to expand a list of protocols Select IEEE 802.15.4, click the Decryption Keys Edit... button Create a new key entry by pressing the plus button, then set the following values and click OK       Decryption key = 00112233445566778899aabbccddeeff      Decryption key index = 1      Key hash = Thread hash Find CoAP and configure it with CoAP UDP port number = 5683 Click Thread and select Decode CoAP for Thread  with Thread sequence counter = 00000000 as shown below At the 6LoWPAN preferences, add the Context 0 value of fd00:0db8::/64 Click OK and close Wireshark Configure Kinetis Protocol Analyzer  Connect the USB-KW41Z to one of the USB ports on your computer Open the device manager and look for the device connected port Open the "Kinetis Protocol Analyzer Adapter" program Make sure, you have a USB-KW41Z connected to your PC when opening the program because the Kinetis Protocol Adapter will start looking for kinetis sniffer hardware. Once the USB-KW41Z is detected, the previously identify COM port will be displayed Select the desired IEEE 802.15.4 channel to scan in the Kinetis Protocol Analyzer window. This guide selects channel 12 as an example  Click on the Wireshark icon to open Wireshark Network Protocol Analyzer An error may appear while opening Wireshark, click OK and continue Wireshark Sniffing Wireshark Network Analyzer will be opened. On the "Capture" option of the main window, select the Local Area Connection that was created by the Kinetis Protocol Analyzer, in this example, Kinetis Protocol Analyzer created "Local Area Connection 2", then click "Start" button. USB-KW41Z will start to sniff and upcoming data will be displayed in the "Capture" window of the Wireshark Network Protocol Analyzer.
查看全文
This document describes how to add additional cluster to the router application in the AN12061-MKW41Z-AN-Zigbee-3-0-Base-Device Application Note.   The Router application's main endpoint contains Basic, Groups, Identify and OnOff server. The steps below describe how to add two clusters to Router: Temperature Measurement server and OnOff client. Note that these changes only go as far as making the new clusters added and discoverable, no functionality has been added to these clusters. Router/app_zcl_cfg.h The first step is to update the application ZCL Configuration file to add the new clusters (OnOff Client, Temperature Measurement Server) to the Router application endpoint. The HA profile already contains few clusters but Temperature Measurement cluster was added:   /* Profile 'HA' */ #define HA_ILLUMINANCEMEASUREMENT_CLUSTER_ID (0x0400) #define HA_DEFAULT_CLUSTER_ID                (0xffff) #define HA_OTA_CLUSTER_ID                    (0x0019) #define HA_TEMPMEASUREMENT_CLUSTER_ID        (0x0402) Router/app_zcl_globals.c The OnOff client was already present in Router endpoint but made discoverable and the Temperature Measurement cluster was added and made discoverable into Router application endpoint.The clusters are added to the Input cluster list (Server side) and output cluster list (Client side) and made discoverable using DiscFlag only for the cluster list for which it is enabled. So, assuming you need to add OnOff cluster client, you would need to use add the cluster id (0x0006 for OnOff) into input cluster list (Server side of cluster) and output cluster list (Client side of the cluster) and make it discoverable for output cluster list as it is a client cluster. For temperature measurement, you need to make it discoverable for input Cluster list as below: PRIVATE const uint16 s_au16Endpoint1InputClusterList[6] = { 0x0000, 0x0004, 0x0003, 0x0006, HA_TEMPMEASUREMENT_CLUSTER_ID , 0xffff, }; PRIVATE const PDUM_thAPdu s_ahEndpoint1InputClusterAPdus[6] = { apduZCL, apduZCL, apduZCL, apduZCL, apduZCL, apduZCL, }; PRIVATE uint8 s_au8Endpoint1InputClusterDiscFlags[1] = { 0x1f }; PRIVATE const uint16 s_au16Endpoint1OutputClusterList[5] = { 0x0000, 0x0004, 0x0003, 0x0006, HA_TEMPMEASUREMENT_CLUSTER_ID, }; PRIVATE uint8 s_au8Endpoint1OutputClusterDiscFlags[1] = { 0x08 }; Now update Simple Descriptor structure (see the declaration of zps_tsAplAfSimpleDescCont and ZPS_tsAplAfSimpleDescriptor structures to understand how to correctly fill the various parameters) to reflect the input cluster and output cluster list correctly as below : PUBLIC zps_tsAplAfSimpleDescCont s_asSimpleDescConts[2] = { {    {       0x0000,       0,       0,       0,       84,       84,       s_au16Endpoint0InputClusterList,       s_au16Endpoint0OutputClusterList,       s_au8Endpoint0InputClusterDiscFlags,       s_au8Endpoint0OutputClusterDiscFlags,    },    s_ahEndpoint0InputClusterAPdus,    1 }, {    {       0x0104,       0,       1,       1,       6,       5,       s_au16Endpoint1InputClusterList,       s_au16Endpoint1OutputClusterList,       s_au8Endpoint1InputClusterDiscFlags,       s_au8Endpoint1OutputClusterDiscFlags,    },    s_ahEndpoint1InputClusterAPdus,    1 }, }; Router/zcl_options.h This file is used to set the options used by the ZCL. Enable Clusters The cluster functionality for the router endpoint was enabled: /****************************************************************************/ /*                             Enable Cluster                               */ /*                                                                          */ /* Add the following #define's to your zcl_options.h file to enable         */ /* cluster and their client or server instances                             */ /****************************************************************************/ #define CLD_BASIC #define BASIC_SERVER #define CLD_IDENTIFY #define IDENTIFY_SERVER #define CLD_GROUPS #define GROUPS_SERVER #define CLD_ONOFF #define ONOFF_SERVER #define ONOFF_CLIENT #define CLD_TEMPERATURE_MEASUREMENT #define TEMPERATURE_MEASUREMENT_SERVER Enable any optional Attributes and Commands for the clusters /****************************************************************************/ /* Temperature Measurement Cluster - Optional Attributes */ /* */ /* Add the following #define's to your zcl_options.h file to add optional */ /* attributes to the time cluster. */ /****************************************************************************/ #define CLD_TEMPMEAS_ATTR_TOLERANCE /****************************************************************************/ /* Basic Cluster - Optional Commands */ /* */ /* Add the following #define's to your zcl_options.h file to add optional */ /* commands to the basic cluster. */ /****************************************************************************/ #define CLD_BAS_CMD_RESET_TO_FACTORY_DEFAULTS /****************************************************************************/ /* OnOff Cluster - Optional Commands */ /* */ /* Add the following #define's to your zcl_options.h file to add optional */ /* commands to the OnOff cluster. */ /****************************************************************************/ #define CLD_ONOFF_CMD_OFF_WITH_EFFECT  Add the cluster creation and initialization into ZigBee Base device definitions The cluster functionality for some of the clusters (like OnOff Client) is already present on ZigBee Base Device. For Temperature Measurement cluster the functionality was added into ZigBee Base Device. <SDK>/middleware/wireless/Zigbee_3_0_6.0.6/core/ZCL/Devices/ZHA/Generic/Include/base_device.h The first step was including the Temperature Measurement header files into base device header file as shown below:  #ifdef CLD_TEMPERATURE_MEASUREMENT #include "TemperatureMeasurement.h" #endif The second step was adding cluster instance (tsZHA_BaseDeviceClusterInstances) into base device Instance as shown below: /* Temperature Measurement Instance */ #if (defined CLD_TEMPERATURE_MEASUREMENT) && (defined TEMPERATURE_MEASUREMENT_SERVER) tsZCL_ClusterInstance sTemperatureMeasurementServer; #endif The next step was to define the cluster into the base device structure (tsZHA_BaseDevice) as below: #if (defined CLD_TEMPERATURE_MEASUREMENT) && (defined TEMPERATURE_MEASUREMENT_SERVER) tsCLD_TemperatureMeasurement sTemperatureMeasurementServerCluster; #endif <SDK>/middleware/wireless/Zigbee_3_0_6.0.6/core/ZCL/Devices/ZHA/Generic/Include/base_device.c The cluster create function for Temperature Measurement cluster for server was called in ZigBee base device registration function:   #if (defined CLD_TEMPERATURE_MEASUREMENT) && (defined TEMPERATURE_MEASUREMENT_SERVER)    /* Create an instance of a Temperature Measurement cluster as a server */    if(eCLD_TemperatureMeasurementCreateTemperatureMeasurement(&psDeviceInfo->sClusterInstance.sTemperatureMeasurementServer,                                                    TRUE,                                                    &sCLD_TemperatureMeasurement,                                                    &psDeviceInfo->sTemperatureMeasurementServerCluster,                                                    &au8TemperatureMeasurementAttributeControlBits[0]) != E_ZCL_SUCCESS)   {       return E_ZCL_FAIL;    } #endif Router/app_zcl_task.c Temperature Measurement Server Cluster Data Initialization - APP_vZCL_DeviceSpecific_Init() The default attribute values for the Temperature Measurement clusters are initialized: PRIVATE void APP_vZCL_DeviceSpecific_Init(void) {    sBaseDevice.sOnOffServerCluster.bOnOff = FALSE;    FLib_MemCpy(sBaseDevice.sBasicServerCluster.au8ManufacturerName, "NXP", CLD_BAS_MANUF_NAME_SIZE);    FLib_MemCpy(sBaseDevice.sBasicServerCluster.au8ModelIdentifier, "BDB-Router", CLD_BAS_MODEL_ID_SIZE);    FLib_MemCpy(sBaseDevice.sBasicServerCluster.au8DateCode, "20150212", CLD_BAS_DATE_SIZE);    FLib_MemCpy(sBaseDevice.sBasicServerCluster.au8SWBuildID, "1000-0001", CLD_BAS_SW_BUILD_SIZE);    sBaseDevice.sTemperatureMeasurementServerCluster.i16MeasuredValue = 0;    sBaseDevice.sTemperatureMeasurementServerCluster.i16MinMeasuredValue = 0;    sBaseDevice.sTemperatureMeasurementServerCluster.i16MaxMeasuredValue = 0; }
查看全文
I was investigating about how to create a current profile and I found interesting information I would like to share with the community. So, I decided to create an example to accomplish this task using BLE stack included in the MKW40Z Connectivity Software package. The demo to create is an Humidity Collector which make use of the Humidity custom profile and is based on the Temperature Collector demonstration application. The first thing to know is that the Generic Attribute Profile (GATT) establishes in detail how to exchange all profile and user data over a BLE connection. GATT deals only with actual data transfer procedures and formats. All standard BLE profiles are based on GATT and must comply with it to operate correctly. This makes GATT a key section of the BLE specification, because every single item of data relevant to applications and users must be formatted, packed, and sent according to the rules.                                      GATT defines two roles: Server and Client. The GATT server stores the data transported over the Attribute Protocol (ATT) and accepts Attribute Protocol requests, commands and confirmations from the GATT client. The GATT client accesses data on the remote GATT server via read, write, notify, or indicate operations. Notify and indicate operations are enabled by the client but initiated by the server, providing a way to push data to the client. Notifications are unacknowledged, while indications are acknowledged. Notifications are therefore faster, but less reliable. Figure 1. GATT Client-Server      GATT Database establishes a hierarchy to organize attributes. These are the Profile, Service, Characteristic and Descriptor. Profiles are high level definitions that define how services can be used to enable an application and Services are collections of characteristics. Descriptors defined attributes that describe a characteristic value. To define a GATT Database several macros are provided by the GATT_DB API in the Freescale BLE Stack, which is part KW40Z Connectivity Software package. Figure 2. GATT database      To know if the Profile or service is already defined in the specification, you have to look for in Bluetooth SIG profiles and check in the ble_sig_defines.h file if this is already declared in the code. In our case, the service is not declared, but the characteristic of the humidity is declared in the specification. Then, we need to check if the characteristic is already included in ble_sig_defines.h. Since, the characteristic is not included, we need to define it as shown next: /*! Humidity Charactristic UUID */ #define gBleSig_Humidity_d                      0x2A6F      The Humidity Collector is going to have the GATT client; this is the device that will receive all information from  the GATT server. Demo provided in this post works like the Temperature Collector. When the Collector enables the notifications from the sensor, received notifications will be printed in the serial terminal. In order to create the demo we need to define or develop a service that has to be the same as in the GATT Server, this is declared in the gatt_uuid128.h.If the new service is not the same, they will never be able to communicate each other. All macros function or structures in BLE stack of KW40Z Connectivity Software have a common template. Hence, we need to define this service in the gatt_uuid128.h as shown next: /* Humidity */ UUID128(uuid_service_humidity, 0xfe ,0x34 ,0x9b ,0x5f ,0x80 ,0x00 ,0x00 ,0x80 ,0x00 ,0x10 ,0x00 ,0x02 ,0x00 ,0xfa ,0x10 ,0x10)      During the scanning process is when the client is going to connect with the Server. Hence, function CheckScanEvent can help us to ensure that peer device or server device support the specified service, in this case, it will be the humidity service we just created in the previous step. Then, CheckScanEvent needs to check which device is on advertising mode and with MatchDataInAdvElementList to verify if it is the same uuid_service_humidity, if the service is not in the list, client is not going to connect. CheckScanEvent function should look as shown next: static bool_t CheckScanEvent(gapScannedDevice_t* pData) { uint8_t index = 0; uint8_t name[10]; uint8_t nameLength; bool_t foundMatch = FALSE; while (index < pData->dataLength) {         gapAdStructure_t adElement;                 adElement.length = pData->data[index];         adElement.adType = (gapAdType_t)pData->data[index + 1];         adElement.aData = &pData->data[index + 2];          /* Search for Humidity Custom Service */         if ((adElement.adType == gAdIncomplete128bitServiceList_c) ||           (adElement.adType == gAdComplete128bitServiceList_c))         {             foundMatch = MatchDataInAdvElementList(&adElement, &uuid_service_humidity, 16);         }                 if ((adElement.adType == gAdShortenedLocalName_c) ||           (adElement.adType == gAdCompleteLocalName_c))         {             nameLength = MIN(adElement.length, 10);             FLib_MemCpy(name, adElement.aData, nameLength);         }                 /* Move on to the next AD elemnt type */         index += adElement.length + sizeof(uint8_t); } if (foundMatch) {         /* UI */         shell_write("\r\nFound device: \r\n");         shell_writeN((char*)name, nameLength-1);         SHELL_NEWLINE();         shell_writeHex(pData->aAddress, 6); } return foundMatch; } The humidity_interface.h file should define the client structure and the server structure. For this demo, we only need the client structure, however, both are defined for reference. The Client Structure has all the data of the Humidity Service, in this case is a Service, characteristic, descriptor and CCCD handle and the format of the value. /*! Humidity Client - Configuration */ typedef struct humcConfig_tag { uint16_t    hService; uint16_t    hHumidity; uint16_t    hHumCccd; uint16_t    hHumDesc; gattDbCharPresFormat_t  humFormat; } humcConfig_t; The next configuration structure is for the Server; in this case we don’t need it. /*! Humidity Service - Configuration */ typedef struct humsConfig_tag { uint16_t    serviceHandle; int16_t     initialHumidity;        } humsConfig_t;     Now that the Client Structure is declared, go to the app.c and modify some functions. There are functions that help to store all the data of the humidity service. In our case they are 3 functions for the service, characteristic and descriptor. You have to be sure that the service that you create and the characteristics of humidity are in the functions. The Handle of each data is stored in the structure of the client. The three functions that need to be modify are the next: BleApp_StoreServiceHandles() stores handles for the specified service and characteristic. static void BleApp_StoreServiceHandles (     gattService_t   *pService ) {     uint8_t i;           if ((pService->uuidType == gBleUuidType128_c) &&         FLib_MemCmp(pService->uuid.uuid128, uuid_service_humidity, 16))     {         /* Found Humidity Service */         mPeerInformation.customInfo.humClientConfig.hService = pService->startHandle;                 for (i = 0; i < pService->cNumCharacteristics; i++)         {             if ((pService->aCharacteristics[i].value.uuidType == gBleUuidType16_c) &&                 (pService->aCharacteristics[i].value.uuid.uuid16 == gBleSig_Humidity_d))             {                 /* Found Humidity Char */                 mPeerInformation.customInfo.humClientConfig.hHumidity = pService->aCharacteristics[i].value.handle;             }         }     } } BleApp_StoreCharHandles() handles the descriptors. static void BleApp_StoreCharHandles (     gattCharacteristic_t   *pChar ) {     uint8_t i;         if ((pChar->value.uuidType == gBleUuidType16_c) &&         (pChar->value.uuid.uuid16 == gBleSig_Humidity_d))     {            for (i = 0; i < pChar->cNumDescriptors; i++)         {             if (pChar->aDescriptors[i].uuidType == gBleUuidType16_c)             {                 switch (pChar->aDescriptors[i].uuid.uuid16)                 {                     case gBleSig_CharPresFormatDescriptor_d:                     {                         mPeerInformation.customInfo.humClientConfig.hHumDesc = pChar->aDescriptors[i].handle;                         break;                     }                     case gBleSig_CCCD_d:                     {                         mPeerInformation.customInfo.humClientConfig.hHumCccd = pChar->aDescriptors[i].handle;                         break;                     }                     default:                         break;                 }             }         }     } } BleApp_StoreDescValues() stores the format of the value. static void BleApp_StoreDescValues (     gattAttribute_t     *pDesc ) {     if (pDesc->handle == mPeerInformation.customInfo.humClientConfig.hHumDesc)     {         /* Store Humidity format*/         FLib_MemCpy(&mPeerInformation.customInfo.humClientConfig.humFormat,                     pDesc->paValue,                     pDesc->valueLength);     }   }      After we store all the data of the Humidity Service, we need to check the notification callback. Every time the Client receives a notification with the BleApp_GattNotificationCallback(),  call the BleApp_PrintHumidity() function and check the Format Value; in this case is 0x27AD  that mean percentage and also have to be the same on the GATT server. static void BleApp_GattNotificationCallback (     deviceId_t serverDeviceId,     uint16_t characteristicValueHandle,     uint8_t* aValue,     uint16_t valueLength ) { /*Compare if the characteristics handle Server is the same of the GATT Server*/     if (characteristicValueHandle == mPeerInformation.customInfo.humClientConfig.hHumidity)     {            BleApp_PrintTemperature(*(uint16_t*)aValue);     }  } BleApp_PrintHumidity() print the value of the Humidity, but first check if the format value is the same. static void BleApp_PrintHumidity (     uint16_t humidity ) {     shell_write("Humidity: ");     shell_writeDec(humidity);      /*If the format value is the same, print the value*/     if (mPeerInformation.customInfo.humClientConfig.humFormat.unitUuid16 == 0x27AD)     {         shell_write(" %\r\n");     }     else     {         shell_write("\r\n");     } } Step to include the file to the demo. 1. Create a clone of the Temperature_Collector with the name of Humidity_Collector 2. Unzip the Humidity_Collector.zip file attached to this post. 3. Save the humidity folder in the fallowing path: <kw40zConnSoft_install_dir>\ConnSw\bluetooth\profiles . 4. Replaces the common folder in the next path: <kw40zConnSoft_install_dir>\ConnSw\examples\bluetooth\humidity_sensor\common . Once you already save the folders in the corresponding path you must to indicate in the demo where they are and drag the file in the humidity folder to the workspace. For test the demo fallow the next steps: Compile the project and run. Press SW1 for the advertising/scanning mode, and wait to connect it. Once the connection finish, press the SW1 of the Humidity Sensor board to get and print the data. Enjoy the demo! NOTE: This demo works with the Humidity Sensor demo. This means that you need one board programmed with the Humidity Sensor application and a second board with the Humidity Collector explained in this post. Figure 3. Example of the Humidity Collector using the Humidity Sensor.
查看全文
All FSCI packets contain a checksum field to verify data integrity. Every time a FSCI packet is created (by the Host or a Kinetis device) a new CRC is calculated based on every data byte in the FSCI frame. Compute CRC for TX packet The CRC field is calculated by XORing each byte contained in the FSCI command (opcode group, opcode, payload length and payload data). Checksum field then, accumulates the result of every XOR instruction.    In the firmware, the CRC is calculated in the 'FSCI_transmitPayload()' function wich is located in '<HSDK project>/framework/FSCI/Source/FsciCommunication.c' file. See FSCI_computeChecksum(). Example: TX: AspSetXtalTrim.Request 02 95 0A 01 30 AE    Sync            [1 byte] = 02    OpGroup     [1 byte] = 95    OpCode      [1 byte] = 0A    Length         [1 byte] = 01    trimValue     [1 byte] = 30    CRC            [1 byte] = AE     <------- (0x95) XOR (0A) XOR (0x01) XOR (0x30) = 0xAE Disable CRC field validation Every time a FSCI packet is received, the device verifies the checksum value.  The next changes will allow the board to receive FSCI packets without verifying the CRC field. However, the board will send the FSCI responses to the Host with this CRC field. Go to 'FsciCommunication.c' file. Search for 'fsci_packetStatus_t FSCI_checkPacket( clientPacket_t *pData, uint16_t bytes, uint8_t* pVIntf )' function. Comment all line codes related to checksum verifying. The image below shows what has to be commented. Compile project and load it to the board. Verify functionality with Test Tool. Select any command and check Raw Data checkbox. Delete the CRC data field and send the FSCI message pressing Send Raw. The loaded command set will vary depending on the demo you are using (Thread, ZigBee, BLE, etc.). The FSCI message is sent without a CRC field and the board responses to the command successfully.
查看全文
Overview The Bluetooth specification defines 4 Generic Access Profile (GAP) roles for devices operating over a Low Energy physical transport [1]: Peripheral Central Broadcaster Observer The Bluetooth Low Energy Host Stack implementation on the Kinetis KW40Z offers devices the possibility to change between any of the 4 roles at run time. This article will present the interaction with the Bluetooth Low Energy Host API needed to implement a GAP multiple role device. General Procedure instructions Running the GAP roles requires the application to go through the following 3 steps: Configuration - Stack configuration for the desired GAP role The application needs to configure the stack parameters, e.g. advertising parameters, advertising data, scan parameters, callbacks. Note that configuration of the advertising parameters or scanning response and advertising data can be done only once if the values don’t change at runtime. The configuration is always made in the Link Layer Standby state. Start - Running the role The application needs to start advertising, scanning or initiate connection. Stop - Return to Standby state When changing between roles, the Link layer must always go through the Link Layer Standby state. Running as a GAP Broadcaster or GAP Peripheral The GAP Broadcaster or Peripheral sends advertising events. Additionally, the GAP Peripheral will accept the establishment of a LE link. This is why the GAP Observer will only support the Non Connectable Advertising mode (gAdvNonConnectable_c). Both roles requires configuration of advertising data, advertising parameters. The configuration (gAppAdvertisingData, gAppScanRspData and gAdvParams) usually resides in app_config.c. The confirmation events for setting these parameters is received in BleApp_GenericCallback. The confirmation event for the changing state of advertising is received in BleApp_AdvertisingCallback. Configuration /* Setup Advertising and scanning data */ Gap_SetAdvertisingData(&gAppAdvertisingData, &gAppScanRspData); /* Setting only for GAP Broadcaster role */ gAdvParams. advertisingType = gAdvNonConnectable_c; /* Set advertising parameters*/ Gap_SetAdvertisingParameters(&gAdvParams); Start App_StartAdvertising(BleApp_AdvertisingCallback, BleApp_ConnectionCallback); Stop Gap_StopAdvertising(); Running as a GAP Observer The GAP Observer receives advertising events. Unlike the GAP Peripheral or Broadcaster, it does not need to set scanning parameters separately. It passes the configuration with the start procedure. The configuration (gAppScanParams) usually resides in app_config.c. The confirmation event for the changing state of scanning is received in BleApp_ScanningCallback. Configuration and Start App_StartScanning(&gAppScanParams, BleApp_ScanningCallback); Stop Gap_StopScanning (); Running as a GAP Central The GAP Central initiates the establishment of the LE link. Like the GAP Observer, it passes the configuration with the start procedure. The configuration (gConnReqParams) usually resides in app_config.c. The confirmation event for the changing state of link is received in BleApp_ConnectionCallback. Configuration and Start Gap_Connect(&gConnReqParams, BleApp_ConnectionCallback); Stop Gap_Disconnect(deviceId); Example An out-of-the box example for multiple role is attached. The application named blood_pressure_multi_role implements a Blood Pressure GATT client and server and can switch between the following GAP roles: Peripheral, Observer and Central. The contents of the archive needs to be copied to the following location: <Installer Path>\KW40Z_Connectivity_Software_1.0.1\ConnSw\examples\bluetooth\ The application can be found at: <Install Path specified>\KW40Z_Connectivity_Software_1.0.1\ConnSw\examples\bluetooth\blood_pressure_multi_role\frdmkw40z\bare_metal\build\iar\blood_pressure_multi_role.eww Running as GAP Peripheral Press SW4. LED1 will start flashing and the console will show that the Link Layer enters Advertising. If the Link Layer was in a previous state, it will go through Standby. static void BleApp_Advertise(void) {     /* Ensure Link Layer is in Standby */     BleApp_GoToStandby();         shell_write(" GAP Role: Peripheral\n\r");     mGapRole = gGapPeripheral_c;         /* Start GAP Peripheral */     App_StartAdvertising(BleApp_AdvertisingCallback, BleApp_ConnectionCallback); } Running as GAP Observer Press SW3. A chasing LED pattern will start and the console will show that the Link Layer enters Scanning. If the Link Layer was in a previous state, it will go through Standby. static void BleApp_Scan(void) {     /* Ensure Link Layer is in Standby */     BleApp_GoToStandby();         shell_write(" GAP Role: Observer\n\r");     mGapRole = gGapObserver_c;         /* Start GAP Observer */     App_StartScanning(&gAppScanParams, BleApp_ScanningCallback); } Running as GAP Central If the Link Layer is in scanning and finds a Blood Pressure Sensor, it will go through Standby and initiate connection. static void BleApp_Connect(void) {     /* Ensure Link Layer is in Standby */     BleApp_GoToStandby();         shell_write(" GAP Role: Central\n\r");     mGapRole = gGapCentral_c;         /* Start GAP Central */     Gap_Connect(&gConnReqParams, BleApp_ConnectionCallback); } Returning to Standby Pressing SW3 for more than 2 seconds, brings the Link Layer back in Standby. static void BleApp_GoToStandby(void) {     /* Check if connection is on */     if (mPeerInformation.deviceId != gInvalidDeviceId_c)     {         /* Stop GAP Central or Peripheral */         Gap_Disconnect(mPeerInformation.deviceId);     }     if (mAdvOn)     {         /* Stop GAP Peripheral or Bradcaster */         Gap_StopAdvertising();     }         if (mScanningOn)     {         /* Stop GAP Observer */         Gap_StopScanning();     } } References [1] BLUETOOTH SPECIFICATION Version 4.2 [Vol 3, Part C], 2.2 PROFILE ROLES
查看全文
Document Purpose This post entry provides an example of a hybrid application (Wireless_UART + GFSK Advertising) by covering Bluetooth Low Energy multiple node connections in parallel with GFSK (Generic Frequency Shift Keying) communication.  This is an additional example for the SDK where we have defined a Hybrid application for Bluetooth LE advertising and scanning in parallel with GFSK communication. Audience The goal of this post is to serve as a guide for software developers who want to use, adapt and integrate GFSK functionality in a Bluetooth Low Energy application.    Setting up the development environment Toolchain:           - IAR Embedded Workbench 8.32 or newer;            https://www.iar.com/iar-embedded-workbench/   SDK:          - This version of firmware has been tested using SDK_2.2.1_FRDM-KW36, that can be downloaded using the following link: https://mcuxpresso.nxp.com/en/select            (please consider to select as Toolchain/IDE: All toolchains);             Hardware:       - 2 to 5 FRDM-KW36 development board:  FRDM-KW36 Development Kit KW36/35 MCUs | NXP  Implementation This demo application is design for the FRDM-KW36 platform and can be easily integrated into any board that is using KW35/36 MCU family. The functionality is based on the coexistence mechanism available on the SDK (Mobile Wireless System - MWS module). Based on the HW link-layer implementation, the Bluetooth Low Energy has a higher priority than the GFSK protocol and as the effect, the GFSK communication is executed during the Idle states (inactive periods) of the Bluetooth LE.  For more details related to the MWS module, please refer to connectivity framework documentation from SDK (Connectivity Framework Reference Manual.pdf). As for functionality on the Bluetooth low energy, both roles, central and peripheral, are supported.  Integration to the KW36 SDK - download the attached file and unzip to ...\SDK_2.2.1_FRDM-KW36\boards\frdmkw36\wireless_examples\hybrid folder: - open IAR project (SDK_2.2.1_FRDM-KW36_2019_07_19\boards\frdmkw36\wireless_examples\hybrid\ble_w_uart_gfsk\freertos\iar\ble_w_uart_gfsk_freertos.eww). - the project is organized like below: Functionality Switches functionality:     - functionality is defined in main.c file, BleApp_Handle Keys function;    - on the FRDM-KW36 we have:                 - SW2 - start scanning - Central device;                 - Long SW2 - start advertising - Peripheral device; (long SW2 - SW2 pressed for more than 3 seconds)                 - SW3 - start/stop GFSK TX operation (advertising);                 - Long SW3 - start/stop GFSK RX operation (long SW3 - SW3 pressed for more than 3 seconds) Logs:    - Serial events for different states of the board;    - BaudRate 115200; Validation The solution has been validated using 1 Master and 4 Slave devices as below: 1. Create the network:     a. Open serial communication of all devices. After reset you will see the following message:    b. On the Central device press SW2 to start scanning;    c. On the Peripheral device press Long SW2 to start advertising and wait for the confirmation on the serial port:   d. Repeat steps b. and c. for all of the slave devices.   e. When the network is completed on the Central device you will see something like below:   f. Check the over the air connections (connection interval = 312.5 ms): 2. Validate functionality on the Bluetooth LE: - from each slave (Peripheral) serial terminal write a message (e.g: testslaveX) and check that the message is printed on the master serial port. - do the same test from the master (Central) serial terminal. - Below is an example of this step:   - over the air log: 3. Initiate GFSK communication: - in one of the board's press SW3 to start GFSK TX operation (Advertising packet with AdvAddress = 0909090909); At every 1 second (gGenFskApp_TxInterval_c), an ADV packet will be sent over the air. - Select other board and press Long Sw3 to initiate GFSK RX operation (RX interval = 100ms = gGenFskApp_RxInterval_c); - Each time an ADV packet from address = 0909090909 is received this will be listed on the serial port as below: - over the air the GFSK TX packets will be listed as a ADV_NONCONN_IND: 4. Validate Bluetooth LE in parallel with GFSK: - write a message on the Master (Central) serial terminal and check the feedback on the slave(Peripheral) serial terminals: Attached is the source code for this application. Regards, Ovidiu
查看全文
By default the clock configuration on the KW2xD demos is set to PLL Engaged External (PEE). In this mode the system clock is derived from the output of the PLL and controlled by an external reference clock. The modem provides a programmable clock source output CLK_OUT that can be used as the external reference clock for the PLL. In the Figure 1 we can see that the CLK_OUT modem signal is internally connected to EXTAL0 in the MCU.   The CLK_OUT output frequency is controlled by programming the modem 3-bit field CLK_OUT_DIV [2:0] in the CLK_OUT_CTRL Register. The default frequency is either 32.787 kHz or 4 MHz depending on the state of the modem GPIO5 at reset determined by the MCU. See section 4.4.2 and 5.6.2 from the MKW2xD Reference Manual for more information on the clock output feature. If the GPIO5 modem pin is low upon POR, then the frequency will be 4 MHz. If this GPIO5 modem pin is high upon POR, then the frequency will be 32.78689 kHz.   In the KW2xD demos, the GPIO5 (PTC0) is held low during the modem reset so the CLK_OUT has a frequency of 4MHz. The clock configuration structure g_defaultClockConfigRun is defined in board.c. Figure 1. Internal Functional Interconnects   In this example project, another clock configuration will be added to the Connectivity Test Project: FLL Engaged Internal (FEI). In this mode, the system clock is derived from the FLL clock that is controlled by the 32kHz Internal reference clock.   In FEI mode the MCU doesn’t need the clock source output CLK_OUT from the modem, so we can disable the radio’s clock output and then set the radio to Hibernate to save power when we are not using the radio.   If the low-power module from the connectivity framework is used to go to a low-power mode, the clock configuration is changed automatically when entering a sleep mode (See the Connectivity Framework Reference Manual for more information about the low-power library).   System Requirements Kinetis MKW2xD and MCR20A Connectivity Software (REV 1.0.0) TWR-KW24D512 IAR Embedded Workbench for ARM 7.60.1 or later Attached project files Application Description The clock configuration can be changed with shortcuts on the serial console: Press “c” to use the PEE clock configuration (default). Press “v” to use the FEI clock configuration and set the radio to Autodoze. Press “b” to use the FEI clock configuration and set the radio to Hibernate.   You must be in the main menu in order to change the radio mode, the mode automatically changes to Autodoze when entering a test menu.   Hibernate mode can only be changed when in FEI mode. This is because in hibernate the radio disables the CLK_OUT and the PEE configuration needs this clock.   Current Measurements The following measurements were done in a TWR-KW24D256 through J2 5-6 to measure the radio current. Table 1. Radio Current Measurements Clock mode/Radio mode Radio Current PEE/Autodoze 615µA FEI/Autodoze 417µA FEI/Hibernate 0.3µA   Code Modifications The following modifications to the source files were made: \boards\twrkw24d512\Board.c Added clock user configuration Added array of clock configs and configuration struct for clock callback   \boards\twrkw24d512\Board.h Include for fsl_clock_manager.h Declaration of clock callback and configuration array used in CLOCK_SYS_Init() function.   \boards\twrkw24d512\Hardware_init.c Added calibration code after BOARD_ClockInit(), this is to calibrate internal clock using the bus clock.   \examples\smac\Connectivity_Test\common\Connectivity_TestApp.c Initialize the clock manager. Disable PTC0 because it is only used at modem reset to select the CLK_OUT default frequency (4MHz). Return clock configuration on idle state. Prepare radio to go to Autodoze when entering a test menu.   \examples\smac\Connectivity_Test\twrkw24d512\common\Connectivity_Test_Platform.c Changed length of the lines to be erased in PrintTestParameters() from 65 to 80 Added clock config and radio mode to be printed in the test parameters. Added the cases in the shortcut parser to change the clock and radio configuration with the keys “c”, “v” and “b”. Added functions at end of file (Explained in the next section).   \examples\smac\Connectivity_Test\twrkw24d512\common\Connectivity_Test_Platform.h Macros for the clock and radio modes. Function prototypes from the source file.   \examples\smac\Connectivity_Test\twrkw24d512\common\ConnectivityMenus.c Shortcuts descriptions.   The modified source files can be found attached to this document.   Functions added The functions PWRLib_Radio_Enter_Hibernate() and PWRLib_Radio_Enter_AutoDoze() were taken from the file PWRLib.c located at <Connectivity_Software_Path>\ConnSw\framework\LowPower\Source\KW2xD. The PWRLib.c file is part of the low-power library from the connectivity framework.   The Clock_Callback() function was implemented to handle when the clock configuration is updated. Inside the function there is a case to handle before and after the clock configuration is changed. Before the clock configuration is changed, the UART clock is disabled and if the clock configuration is PEE, the radio is set to AutoDoze and the CLK_OUT is enabled. After the clock configuration has changed, the Timer module is notified that the clock has changed, the UART is re-initialized and if the clock configuration is FEI, the CLK_OUT is disabled. This behavior is shown in Figure 2. Figure 2. Clock callback diagram   The prepareRadio() function is used when entering a test mode to make sure the radio is set to AutoDoze in case it was in hibernate. The restoreRadio() function is used when leaving the test menu and going to hibernate if it was previously set.
查看全文
Customer is designing QN9090 module. They have IQxel non-signaling equipment and ask if QN9090 can be tested with IQxel-MW. We co-work with ACE Solution Taiwan Co.Ltd. to Integrate QN9090 and IQxel to perform 1M bps, 2M bps and Frame error rate test. This document will address the QN9090 setup and IQxel connection setup. Finally we show the 1M bps, 2M bps and packet error rate results.
查看全文
Different 802.11 standards are used in Wi-Fi and they differ in terms of operating frequency and data rates. This post provides information about the different terms used in Wi-Fi, 802.11 standards and the three types of 802.11 MAC frames.   Wi-Fi Standard basic terms Station (STA): Stations comprise of all devices that are connected to the wireless LAN. Station is any device that contains 802.11-compliant MAC and PHY interface to the wireless medium. A station may be a laptop, desktop PC, Access Point (AP) or smartphone. A station may be fixed, mobile or portable. Access Point (AP): An access point is a device that creates a wireless local area network. It has station functionality and provides access to the distribution services via the wireless medium. An access point is a device that allows Wi-Fi clients and Wi-Fi enabled routers to connect to a wired network. Access point connects to a wired router, switch or hub via an Ethernet cable and projects Wi-Fi signal to the defined area. An access point receives data by wired Ethernet, and converts to a 2.4GHz or 5GHz wireless signal. It communicates with nearby wireless clients. In a Wi-Fi network, wireless client communicate to other wireless clients via the AP. Client: A device that connects to a Wi-Fi (wireless) network. Any device that transmits and receives Wi-Fi signals, such as a laptop, printer, smartphone is a Wi-Fi client. Basic Service Set (BSS): A group of stations that are successfully synchronized for 802.11 communications. BSS contains one AP and one or more client stations. In BSS, stations have layer 2 connection with AP and are known as associated. Basic Service Set Identifier (BSSID): All basic service sets can be identified by a 48-bit (6-octet) MAC address known as the Basic Service Set Identifier (BSSID). The BSSID address is the layer 2 identifier of each individual basic service set. Most often the BSSID address is the MAC address of the access point. Distribution System (DS): A system that interconnects a set of basic service sets and integrated Local Area Networks (LANs) to create an Extended Service Set (ESS). It is used to extend wireless network coverage. Extended Service Set (ESS): In extended service set, one or more basic service sets are connected. An extended service set is a collection of multiple access points and their associated clients. Independent Basic Service Set (IBSS): An IBSS consists only of client stations that do peer-to-peer communications. An IBSS is a self-contained network that does not have an access point. SSID/ESSID: The logical network name of an Extended Service Set (ESS) is often called a Service Set Identifier (SSID). This name allows stations to connect to the desired network when multiple independent networks operate in the same physical area. Roaming: It is a process of a client moving from one access point to another access point within the same Extended Service Set (ESS) without losing connection. It is described in detail in 802.11 connection disconnection process post: [802.11] Wi-Fi Connection/Disconnection process .   Below figure shows DS, AP, Station, BSS, SSID, BSSID and ESS. Figure 1. Overview of Distribution system   802.11 Standards / Wi-Fi Generations 802.11 standard defines an over the air communication interface between the wireless base station and clients. The 802.11 family has various specifications and it has been categorized in several versions as shown in table below. Details of Wi-Fi generations with 802.11 specifications   Table 1. Wi-Fi Generation Overview Generation Technology Operating Frequency Data rates - 802.11b 2.4 GHz 1 - 11 Mbps - 802.11a 5 GHz Up to 54 Mbps - 802.11g 2.4 GHz Up to 54 Mbps Wi-Fi 4 802.11n 2.4 and 5 GHz Up to 600 Mbps Wi-Fi 5 802.11ac 2.4 and 5 GHz Up to 3.5 Gbps Wi-Fi 6 802.11ax 2.4 and 5 GHz Up to 9.6 Gbps   802.11b: This technology is focused on achieving higher data rates within the 2.4GHz ISM band and that is achieved by using a different spreading/coding technique called Complementary Code Keying (CCK) and modulation methods using the phase properties of the RF signal. 802.11b devices support data rates of 1, 2, 5.5 and 11 Mbps. 802.11a: This technology uses 5GHz frequency band. It supports data rate up to 54Mbps with the use of a spread spectrum technology called Orthogonal Frequency Division Multiplexing (OFDM). 802.11a can coexist in the same physical space with 802.11b and 802.11g devices as these devices are using different frequency ranges (5GHz and 2.4GHz respectively). 802.11g: This Technology is an enhancement of 802.11b Physical layer to achieve the greater bandwidth yet remain compatible with 802.11 MAC. The technology that was originally defined by the 802.11g amendment is called Extended Rate Physical (ERP), So the term ERP can be used in the place of 802.11g. Data rate differs with different 802.11g PHY technology, there are two mandatory ERP PHYs and two optional ERP PHYs. The First mandatory PHY technology called Extended Rate Physical-OFDM (ERP-OFDM) is used to achieve data rate up to 54Mbps. Second mandatory PHY technology called Extended Rate Physical DSSS (ERP-DSSS/CCK) is used to maintain backward compatibility and achieve data rate up to 11Mbps. ERP-PBCC and DSSS-OFDM are the two optional PHYs. ERP-PBCC PHY offers same data rates as the ERP-DSSS/CCK physical layer. It is used to provide higher performance in the range (the 5.5 and 11 Mbps rates) by using DSSS technology with Packet Binary Convolution Code (PBCC) scheme. DSSS-OFDM PHY is a hybrid combination of DSSS and OFDM. The transmission of packet physical header is done by DSSS, whereas the transmission of packet payload is performed by OFDM. Usage of this physical layer is to cover interoperability aspects. 802.11n: This Technology is an improvement of the 802.11 standard to get the higher throughput. 802.11n has a new operation known as High Throughput (HT) which provides MAC and PHY enhancements to provide data rates up to 600Mbps. 802.11n supports Multiple-Input Multiple-Output (MIMO) technology in unison with OFDM technology. MIMO uses multiple radios and transmitting and receiving antennas called radio chains. It capitalizes on the effects of multipath as opposed to compensating for or eliminating them. Transmit Beamforming can be used in MIMO system to steer beams & provide greater range & throughput. 802.11ac: Wi-Fi certified 802.11ac devices are dual band, operating in both 2.4 GHz and 5 GHz. 802.11ac is built on the foundation of 802.11n. 802.11ac devices use the 5 GHz band, while 802.11n products use the 2.4 GHz frequency band, so 802.11b and 802.11g compatibility can be achieved with 802.11ac. 802.11ac provides high-performance through Multi-User Multiple Input Multiple Output (multi-user MIMO), wider channels, and support for four spatial streams. 802.11ax: Wi-Fi certified 802.11ax provides improved data rates, power efficiency and support for eight spatial streams. Target Wake Time (TWT) feature helps to improve battery performance.   802.11 Frame types 802.11 frames are used for wireless communication and is much more involved because the wireless medium requires several management features and corresponding frame types that are not found in wired networks. There are three major frame types that are discussed below. For details regarding 802.11 layer architecture, please refer to [802.x.x] IEEE 802.x.x and Wi-Fi basics.   Management Frames Management frames are used by wireless stations to join and leave the basic service set. 802.11 management frame is also called Management MAC Protocol Data Unit (MMPDU). It has a MAC header, a frame body, and a trailer. It doesn’t carry any upper layer information. There is no MAC Service Data Unit (MSDU) encapsulated in the MMPDU frame body, it carries only layer 2 information fields and information elements, it does not carry higher layer (Layer 3 to 7 of OSI model) data. A management frame must have fixed length information fields and it may have information elements that are variable in length. Management/MMPDU frame body content depends on the sub type field, based on the sub type field it has payload like Status/Reason code, device capability information etc. Few of the management frames i.e. Beacon, Authentication, Association are described in the Connection setup process post [802.11] Wi-Fi Connection/Disconnection process. Below figure shows management frame structure.   Figure 2. Management Frame structure   Type field available in frame control field, that is set to 00 for the management frame. Management frames have 24-bytes long MAC header and header contains three addresses. DA field is the destination address of the frame, it can be broadcast or unicast depending upon frame subtype. SA field is MAC address of the station transmitting the frame. BSSID is MAC address of AP. Frame body is variable size. Size and content of the body depend on the management frame subtype.   Figure 3. Management Frame   Table 2. Management Frame description Frame SubType SubType Value [B7 B6 B5 B4] Initiator (AP/Station) Association request 0 Station Association response 1 AP Reassociation request 10 Station Reassociation response 11 AP Probe request 100 Station Probe response 101 AP/Station Beacon 1000 AP Announcement Traffic Indication Message (ATIM) 1001 Station (IBSS) Disassociation 1010 AP Authentication 1011 Station Deauthentication 1100 AP/Station Action 1101 AP/Station Action no ack 1110 AP/Station   Control Frames Control frames are associated with the delivery of data and management frames, it does not have a frame body. Control frames contain PHY, preamble, layer 2 header and trailer. Control frames can be transmitted at different data rates as they perform many different functions. All control frames use the same Frame Control field that is shown in the figure below.   Figure 4. Control Frame structure   Figure 5. Control Frame   The type field value for the control frame is 01 and subtype fields identify the function of a frame. Table below shows the different types of control frames.   Table 3. Control Frame description Subtype description Subtype value [B7 B6 B5 B4] Reserved 0000 - 0110 Control wrapper 0111 Block ack request (BlockAckReq) 1000 Block ack (BlockAck) 1001 PS-Poll 1010 RTS 1011 CTS 1100 ACK 1101 CF-End 1110 CF-End and CF-Ack 1111   Data Frames Data frames carry the higher level protocol data in the frame body. Data frames are categorized according to function. Total 15 sub types of data frames are defined in 802.11 standard. Type field value for the data frames is 10. One such distinction is between frame that carries data and frame that does not carry data (perform management function). Figure below shows data frame structure.   Figure 6. Data Frame structure   Figure 7. Data Frame   Each bit of the SubType field available in the frame control field has specific meaning as below. Bit 4 (B4): Changing it from 0 to 1 indicates the data subtype includes +CF-Ack. Bit 5 (B5): Changing it from 0 to 1 indicates the data sub type include +CF-Poll. Bit 6 (B6): Changing it from 0 to 1 indicates that the frame contains no data, specifically, that it contains no Frame Body field. Bit 7 (B7): Changing it from 0 to 1 indicates Quality of Service (QoS) data frame.   Data frames that appear only in the contention-free period can never be used in an IBSS. Below is the list of data frames.   Table 4.Data Frame Details Frame SubType SubType Value B7 B6 B5 B4 Consists Data Contention Free Service Data (simple data frame) 0 Yes No Data + CF-Ack 1 Yes Yes Data + CF-Poll 10 Yes Yes(AP only) Data + CF-Ack + CF-Poll 11 Yes Yes(AP only) Null 100 No It can be contention based and free both CF-Ack 101 No Yes CF-Poll 110 No Yes(AP only) CF-Ack + CF-Poll 111 No Yes(AP only) QoS Data 1000 Yes No QoS Data + CF-Ack 1001 Yes Yes QoS Data + CF-Poll 1010 Yes Yes(AP only) QoS Data + CF-Ack + CF-Poll 1011 Yes Yes(AP only) Qos Null 1100 No It can be contention based and free both QoS CF-Poll 1110 No Yes(AP only) QoS CF-Ack + CF-Poll 1111 No Yes(AP only)   References 802.11 Specification: https://ieeexplore.ieee.org/document/7786995 Certified Wireless Analysis Professional: https://www.oreilly.com/library/view/cwap-certified-wireless/9781118075234/ Community posts [802.x.x] IEEE 802.x.x and Wi-Fi basics   [802.11] Wi-Fi Connection/Disconnection process
查看全文
Thread is a secure, wireless, simplified IPv6-based mesh networking protocol developed by industry leading technology companies, including Freescale, for connecting devices to each other, to the internet and to the cloud. Before starting a Thread Network implementation, users should be familiar with some concepts and how they are related to Thread protocol. IPv6 Addressing Devices in the Thread stack support IPv6 addressing IPv6 addresses are 128-bit identifiers (IPv4 is only 32-bit) for interfaces and sets of interfaces.  Thread supports the following types of addresses: Unicast:  An identifier for a single interface.  A packet sent to a unicast address is delivered to the interface identified by that address. Multicast: An identifier for a set of interfaces (typically belonging to different nodes).  A packet sent to a multicast address is delivered to all interfaces identified by that address. NOTES There are no broadcast addresses in IPv6, their function being superseded by multicast addresses. Each device joining the Thread Network is also assigned a 16-bit short address as specified in IEEE 802.15.4. 6LoWPAN All Thread devices use 6LoWPAN 6LoWPAN stands for “IPv6 over Low Power Wireless Personal Networks”. 6LoWPAN is a set of standards defined by the Internet Engineering Task Force (IETF), which enables the efficient use of IPv6 over low-power, low-rate wireless networks on simple embedded devices through an adaptation layer and the optimization of related protocols. Its main goal is to send/receive IPv6 packets over 802.15.4 links. Next figure compares IP and 6LoWPAN protocol stacks: The following concepts would explain the transport layer. ICMP Thread devices support the ICMPv6 (Internet Control Message Protocol version 6) protocol and ICMPv6 error messages, as well as the echo request and echo reply messages. The Internet Control Message Protocol (ICMP) is an error reporting and diagnostic utility and is considered a required part of any IP implementation. ICMPs are used by routers, intermediary devices, or hosts to communicate updates or error information to other routers, intermediary devices, or hosts. For instance, ICMPv6 is used by IPv6 nodes to report errors encountered in processing packets, and to perform other internet-layer functions, such as diagnostics. ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems, nor is it regularly employed by end-user network applications.  The ICMPv6 messages have the following general format: The type field indicates the type of the message.  Its value determines the format of the remaining data. The code field depends on the message type.  It is used to create an additional level of message granularity. The checksum field is used to detect data corruption in the ICMPv6 message and parts of the IPv6 header. ICMPv6 messages are grouped into two classes: error messages and informational messages.  Error messages are identified as such by a zero in the high-order bit of their message Type field values.  Thus,   error messages have message types from 0 to 127; informational messages have message types from 128 to 255. UDP The Thread stack supports UDP for messaging between devices. This User Datagram Protocol  (UDP)  is defined  to  make available  a datagram   mode of  packet-switched   computer communication  in  the environment  of an  interconnected  set  of  computer  networks, assuming that the Internet  Protocol (IP) is used as the underlying protocol. With UDP, applications can send data messages to other hosts on an IP network without prior communications to set up special transmission channels or data paths. UDP is suitable for purposes where error checking and correction is either not necessary or is performed in the application, avoiding the overhead of such processing at the network interface level. The UDP format is as follows: Source Port is an optional field, when meaningful, it indicates the port of the sending  process,  and may be assumed  to be the port  to which a reply should be addressed  in the absence of any other information.  If not used, a value of zero is inserted. Destination Port has a meaning within the context of a particular internet destination address. Length is the length in octets of this user datagram including this header and the data.   (This means the minimum value of the length is eight.) Checksum is the 16-bit one's complement of the one's complement sum of a pseudo header of information from the IP header, the UDP header, and the data, padded  with zero octets at the end (if  necessary)  to  make  a multiple of two octets. References White papers available at http://threadgroup.org/ “6LoWPAN: The Wireless Embedded Internet” by Zach Shelby and Carsten Bromann RFC 4291, RFC 4944, RFC 4443 and RFC 768 from https://www.ietf.org
查看全文
Brief Description NXP Tire Pressure Monitoring Sensors (TPMS) were preloaded the firmware libraries and test software for a variety of customer use cases. The preloaded TPMS bootloader provides wireless software update function for the aftermarket. This demo uses Kinetis KW01 and Low Frequency emitter to accomplish TPMS over-the-air software update.   Reference Picture   Block Diagram   Features 315 MHz RF 125 KHz LF FSK modulation Manchester Encoding Timer/PWM Modules IAR Embedded Workbench for ARM 7.40 CodeWarrior V6.3   NXP Parts Used MRB-KW019032 (MKW01Z128CHN) TPMS870911 (FXTH870911DT1) LF Emitter Board   Get Software MKW01_TPMS_bootloader.rar MPXY8702_TPMS_bootloader.rar TPMS-MKW01-IAR7v4-Project.zip   General Stage Prototype Launched for Alpha customers     Demo Setup   Hardware Requirements MRB-KW019032 x 2         MRB-KW019032 Board A: Connected with LF Emitter Board         MRB-KW019032 Board B: Standalone TPMS879011 x 1 LF Emitter Board x 1   Hardware Connection   Pin function MRB-KW019032 LF Emitter Board TPM1_CH0 PTB0 (J15-9) J5-20 TPM1_CH1 PTB1 (J14-8) J5-28 GND GND (J15-2) J6-4   Demo Description A prebuild TPMS870911 firmware is stored in MRB-KW019032 Board A and this firmware will be sent to TPMS870911 via 125kHz LF signal. After TPMS870911 completes the firmware update, TPMS870911 will send the information of pressure sensor to MRB-KW019032 Board B via 315 MHz RF signal.   Demo Procedure Download MKW01_TPMS_bootloader into MRB-KW019032 Board A with IAR 7.40 Download TPMS-MKW01-IAR7v4-Project into MRB-KW019032 Board B with IAR 7.40 Download MPXY8702_TPMS_bootloader into TPMS870911 with CodeWarrior V6.3 Connect USB cable between PC and both of MRB-KW019032 boards, and open the terminal with the following settings • 115200 baud rate • 8 data bits • No parity • One stop bit • No flow control    5. Press the reset button on both of MRB-KW019032 boards and then the demo message will be shown on the terminal.     6. Short Pin19 of J15 (PTD6) on MRB-KW019032 Board A as SW3 press to start TPMS870911 over-the-air software update. 7. After TPMS870911 completes software update, MRB-KW019032 Board B will print the received RF message which was sent from TPMS870911 on the terminal.                         Original Attachment has been moved to: TPMS-MKW01-IAR7v4-Project.zip Original Attachment has been moved to: MPXY8702_TPMS_bootloader.rar Original Attachment has been moved to: MKW01_TPMS_bootloader.rar
查看全文
A network is basically a set of devices connected to one another and communicating using wired or wireless mediums. There are several standard network frameworks defined for wired and wireless communication by IEEE. This post provides information about the IEEE 802 standard and network modes.   802 Standard The 802 standard is a family of IEEE standards dealing with local and metropolitan area networks. The protocol specified in the 802 standard covers lower two layers of the OSI model that are Physical and Data Link layers. In the 802 standard, the Data link layer (Layer 2 of the OSI model) has been divided into two parts Logical Link Control (LLC) and Media Access Control (MAC) as shown in figure below.   Figure 1. Layer architecture   The active 802 standards are listed below.   Table 1. 802 standards description Standard Name Description 802.1 Internetworking It ensures the management of the Local Area Network (LAN) / Metropolitan Area Network (MAN) network and monitors network capabilities. MAC bridging, data encryption/encoding, and network traffic management services are also provided. 802.3 Ethernet Ethernet based technology that is primarily used for LAN, it can also be used for MAN and Wide Area Network (WAN).     802.3 defines the Physical and MAC sublayer of the Data Link layer that is used in wired networks. Uses Carrier Sense Multiple Access with Collision Detection (CSMA/CD) for collision detection. Data rates can be from 10Mbps to 10Gbps. 802.11 WLAN, Wi-Fi Wireless LAN uses high radio frequencies instead of cables to connect the devices in the network. Portability and setup cost is cheaper compared to wired networks but speed and security are better in wired communication. It uses Carrier Sense Multiple Access with Collision Avoidance (CSMA/CA) for collision avoidance. 802.15 WPAN This covers various protocol definitions for the personal area network like Bluetooth, ZigBee & sensors networks.   WLAN and Wi-Fi Introduction Wireless Local Area Network (WLAN) or Wireless LAN, is a network that links two or more devices using wireless communication to form a local area network within a limited area such as a home, campus, and office building. A WLAN can be built on various wireless technologies i.e. Wi-Fi, Infrared. Wi-Fi is a type of WLAN that follows IEEE 802.11 standards and one of the most commonly used WLAN today. Wi-Fi as a name for the standard is a trademark of the Wi-Fi Alliance. Wi-Fi or WLAN networks use radio waves to exchange information between devices. These radio waves are transmitted on specific frequencies - 2.4 GHz and 5 GHz, depending on the 802.11 standard (IEEE 802.11a/b/g/n/ac/ax) that the device uses. A Wi-Fi connection is established using a wireless adapter to create hotspots – areas in the vicinity of a wireless router that is connected to the network and allow users to access internet services. All Wi-Fi versions uses license free bands (ISM bands) across the globe.   Network Modes Ad-Hoc Mode In this mode wireless nodes communicate to peer nodes directly. It does not use Access Point (AP) instead it uses Mesh topology. It is also called peer to peer mode. An ad-hoc wireless network is more cost-effective than its alternative, since it does not require the installation of an AP to operate. In addition, it also needs less time to set up. Figure 2. Ad-Hoc mode   Infrastructure Mode In this mode, devices can communicate with each other first going through AP. In infrastructure mode, the wireless devices can communicate with each other or can communicate with a wired network as it’s communicating through AP. This mode is the most commonly used network mode. Compared to Ad-Hoc wireless networks, infrastructure mode offers the advantages of scale, centralized security management, and improved reach. Infrastructure mode has half throughput compared to Ad-Hoc mode.   Figure 3. Infrastructure mode   Repeater Mode When two wireless host devices have to be connected and the distance between them is long for the direct connection or obstruction is present, at that time repeater mode is used to bridge the gap. Repeater operates at the physical layer of the OSI model. As a Wireless Repeater, an AP node extends the range of the wireless network by repeating the wireless signal of the remote AP. The Ethernet MAC address of the remote AP is required for the AP to act as a wireless range extender. The repeater mode has certain drawbacks. Throughput is reduced by at least 50% as wireless interference is at least doubled. The bandwidth of any device connected to it is halved. This is due to the repeater receiving the signal, processing it, and then rebroadcasting it in both directions, from the router to the device and vice versa. The Repeater must be kept in the range of AP, but not too close to the AP. Distance between AP and repeater depends on the range of the AP and repeater should be kept in such a way that maximum possible area coverage can be achieved.   Figure 4. Repeater mode   Bridge Mode Bridge connects two or more networks to each other. It operates on the Data link layer of the OSI Model. Bridge mode allows the AP to communicate with another AP capable of point-to-point bridging. An example of this is connecting two buildings through a wireless connection.   Figure 5. Bridge mode
查看全文
Many applications make use of 32 kHz clocks to keep tracking of real-time or to have a low power time reference for the system. Most of the systems might use a 32.768 kHz XTAL for this purpose. However, there might be some exceptions in which the application requires compensate the frequency of this clock due to temperature changes, aging, or just because the clock provides from a source which frequency is close to the ideal 32.768 kHz, but it presents some variations. QN908x devices require a 32 kHz clock source for some applications like running the BLE stack in low power. 32.768 kHz XTALs are more accurate so they are used to generate a 32 kHz source by compensating for the ppm difference. This provides us with tools to compensate for any external 32 kHz source by first obtaining the ppm difference from the ideal frequency. The solution consists in determining how off is the external clock input frequency from the ideal 32 kHz by making a comparison with a trusted clock in the system, typically the 32 MHz / 16 MHz XTAL. This process is executed in the background in an interrupt-based system so the application can initialize or run other processes in the meantime. Then, the results of the ppm calculation are reported to the main application to compensate for the changes and provide for a more accurate clock source. This example makes use of the following peripherals in the QN908x RTC Seconds Timer CTIMER DMA The RTC Seconds Timer uses the 32 kHz clock source as a reference. It contains an internal 32000 cycles counter that increases each 32 kHz clock period. On overflow, it rises the SEC_INT flag to indicate that one second has elapsed. The CTIMER makes use of the APB clock which derives from the 32 MHz / 16 MHz clock. This timer is used in free-running mode with a Prescaler value of 1 to count the number of APB pulses. The algorithm consists of counting the amount of APB pulses (trusted clock reference) elapsed by the time the RTC SEC_INT flag is set. Ideally, if both clocks are in the right frequency, the number of APB pulses must be equal to the reference clock frequency. For example, if the APB clock is 16 MHz, by the time the SEC_INT flag sets, the CTIMER counter must have a value of 16 x 10 6 counts. Assuming our reference clock is ideal, the difference between the CTIMER counter value and 16 x 10 6 can be used to obtain the ppm difference given the following formula. Where f 0 is the ideal APB frequency (16 MHz) and f 1 is the real measured frequency (CTIMER counter value). Since the pulses counted using the CTIMER correspond to the time it took to the RTC Seconds Timer to count one second, we can extrapolate the obtained ppm value as a difference in the 32 kHz clock source from the ideal 32 kHz. To prevent from any application or task servicing latency, the algorithm makes use of the DMA to automatically capture the CTIMER Counter value when the SEC_INT flag is set. The program flow is described in the diagram below. As a way of demonstrating this algorithm, two APIs were implemented to calculate the ppm value and apply the compensation to the system. Both APIs are included in the file fsl_osc_32k_cal .c and .h files. OSC_32K_CAL_GetPpm (osc_32k_cal_callback_t pCallbackFnc): Initializes the required timers and DMA and starts with the CTIMER capture. A callback is passed so it can be executed once the ppm calculation sequence completes. OSC_32_CAL_ApplyPpm (int32_t ppmMeasurement): Uses the previously calculated ppm passed as an input parameter to compensate the RTC and the BLE timer used during sleep mode. OSC_32K_CAL_GetPpm is called every time the ppm value of the 32 kHz source clock needs to be calculated. It takes around one second to complete (depending on how off the 32 kHz source clock is from the ideal frequency) and the application cannot enter into low power state during this time. The registered callback function is executed once the calculation is complete. The ppm calculation is performed into the DMA callback. It consists of obtaining the CTIMER counter difference and use it as f 1 in the formula shown before. The ppm values are calculated using floating point unit. /* Calculate PPMs */ ppmResult = (float)((float)1-((float)ApbClockFreq/(float)ApbCountDiff)); ppmResult *= (float)1048576;‍‍‍‍‍‍ Then OSC_32_CAL_ApplyPpm must be called using the ppm value obtained after calling OSC_32K_CAL_GetPpm. This API programs the necessary values in the RTCàCAL register and the BLE Sleep timer registers to compensate for the differences in the 32 kHz source clock. Finally, the user must account for all those other APIs that make use of the 32 kHz clock frequency and update the values accordingly. For the particular case of the NXP BLE Stack, there are two APIs that need to be updated to return the clock frequency after the calibration has been applied. uint32_t PWRLib_LPTMR_GetInputFrequency(void) { uint32_t result = 32000; int32_t ppm = 0; if ( RTC->CTRL & RTC_CTRL_CAL_EN_MASK) /* is calibration enabled ? */ { /* Get the current calibration value */ if (RTC->CAL & RTC_CAL_DIR_MASK) { /* Backward calibration */ ppm -= (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } else { /* Forward calibration */ ppm += (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } /* Obtain the uncalibrated clock frequency using the formula * fUncal = 32000 - (ppm*0.03125) where 0.03125 is the number * of Hz per PPM digit obtained from (768 Hz/0x6000 PPM) */ result -= (float) ppm * (float) 0.03125; } else { #if (defined(BOARD_XTAL1_CLK_HZ) && (BOARD_XTAL1_CLK_HZ == CLK_XTAL_32KHZ)) result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,768Khz crystal is used */ #else result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,000Khz internal RCO is used */ #endif } return result; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍ uint32_t StackTimer_GetInputFrequency(void) { uint32_t prescaller = 0; uint32_t refClk = 0; uint32_t result = 0; #if FSL_FEATURE_SOC_FTM_COUNT refClk = BOARD_GetFtmClock(gStackTimerInstance_c); prescaller = mFtmConfig.prescale; result = refClk / (1 << prescaller); #elif FSL_FEATURE_RTC_HAS_FRC int32_t ppm = 0; (void)prescaller; /* unused variables */ (void)refClk; /* suppress warnings */ result = 32000; if ( RTC->CTRL & RTC_CTRL_CAL_EN_MASK) /* is calibration enabled ? */ { /* Get the current calibration value */ if (RTC->CAL & RTC_CAL_DIR_MASK) { /* Backward calibration */ ppm -= (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } else { /* Forward calibration */ ppm += (int32_t) (RTC->CAL & RTC_CAL_PPM_MASK); } /* Obtain the uncalibrated clock frequency using the formula * fUncal = 32000 - (ppm*0.03125) where 0.03125 is the number * of Hz per PPM digit obtained from (768 Hz/0x6000 PPM) */ result -= (float) ppm * (float) 0.03125; } else { #if (defined(BOARD_XTAL1_CLK_HZ) && (BOARD_XTAL1_CLK_HZ == CLK_XTAL_32KHZ)) result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,768Khz crystal is used */ #else result = CLOCK_GetFreq(kCLOCK_32KClk); /* 32,000Khz internal RCO is used */ #endif } #elif FSL_FEATURE_SOC_CTIMER_COUNT refClk = BOARD_GetCtimerClock(mCtimerBase[gStackTimerInstance_c]); prescaller = mCtimerConfig[gStackTimerInstance_c].prescale; result = refClk / (prescaller + 1); #else refClk = BOARD_GetTpmClock(gStackTimerInstance_c); prescaller = mTpmConfig.prescale; result = refClk / (1 << prescaller); #endif return result; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
查看全文
1.    Introduction   1.1 Document Purpose This post entry provides a detailed description of how to integrate the NFC Reader Library to a KW3x Bluetooth Low Energy application.   1.2 Audience The goal of this post is to serve as a guide for software developers who want to use, adapt and integrate the NFC Reader Library to an SDK wireless connectivity example.   1.3 References and Resources - NFC Reader Library:  nxp.com/pages/:NFC-READER-LIBRARY - NCF3320: nxp.com/products/:NCx3320  - CLRC663 plus: nxp.com/products/:CLRC66303HN - FRDM-KW36 board: nxp.com/demoboard/FRDM-KW36 - KW35/KW36 SDK: https://mcuxpresso.nxp.com/en/select - MCUXpresso IDE: nxp.com/products/: MCUXpresso-IDE   2. NFC Reader Library Overview   The NXP NFC Reader Library is a modular software library written in C language, which provides an API that enables customers to create their own software stack and applications for the NXP contactless reader ICs: - PN512; - CLRC633 family; - PN7462 family; - PN5180; This API facilitates the most common operations required in NFC applications such as: - reading or writing data into contactless cards or tags; - exchanging data with other NFC-enabled devices; - allowing NFC reader ICs to emulate cards. The NFC Reader Library is designed in a way to be easily portable to many different microcontrollers with a multi-layered architecture:   As main blocks, we have: - Application Layer (AL) - implements the command sets to interact with MIFARE cards and NFC tags. - NFC activity - implements a configurable Discovery loop for the detection of contactless cards, NFC tags or other NFC devices. - HCE and P2P components, for the emulation of Type 4 tags and P2P data exchange respectively. - Protocol abstraction layer (PAL) - contains the RF protocol implementation of the ISO14443, Felica, vicinity and NFC standards. - Hardware abstraction layer (HAL) - implements the drivers for controlling the NFC frontends RF interface and capabilities. - Driver Abstraction Layer (DAL) - implements the GPIO pinning, the timer configuration and the physical interface (BAL) between the host MCU and the reader IC. - OSAL module, in charge of abstracting the OS or RTOS specifics (tasks events, semaphores, and threads)   3. The KW3x Wireless Microcontroller Overview The KW3x wireless microcontrollers (MCU are highly integrated single-chip devices that enable Bluetooth Low Energy (Bluetooth LE) and Generic FSK connectivity for automotive, industrial and medical/healthcare embedded systems.   The KW36/35 Wireless MCU integrates an Arm® Cortex®-M0+ CPU with up to 512 KB flash and 64 KB SRAM and a 2.4 GHz radio that supports Bluetooth LE 5.0 and Generic FSK modulations. The Bluetooth LE radio supports up to 8 simultaneous connections in any master/slave combination. The KW36A/36Z includes an integrated FlexCAN module enabling seamless integration into an automotive or industrial CAN communication network, enabling communication with external control and sensor monitoring devices over Bluetooth LE.   For more details please refer to the NXP website information: https://www.nxp.com/products/wireless/bluetooth-low-energy:BLUETOOTH-LOW-ENERGY-BLE.   4. NFC Reader Library – integration with FRDM-KW36 The current NFC Reader Library v5.21.01 is not containing support for Kinetis KW3x MCU. We will use a reference the K82 NFC Reader Library package: www.nxp.com/pages/:NFC-READER-LIBRARY. The steps required to integrate the library are: - Hardware preparation (the connection between FRDM-KW36 and NFC reader board); - Setting up the development environment (SDK download, workspace); - Preparing adaptation files for FRDM-KW3x board; - Integrating NFC application to Wireless_UART Bluetooth LE example; - Running the demo;   4.1 Hardware preparation Hardware required: - NCF3320 Antenna v1.0 board as an NFC transceiver; - FRDM-KW36 board as host MCU, used to load and run the Bluetooth Low Energy Stack and NFC application logic;   The communication between the boards will be via the SPI communication using the following pin configuration: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Master board (FRDM-KW36)         Connects to            Slave board (NCF3320 Antenna v1.0)           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PTB0  (J2-pin10)                                      -                    IRQ PTB1  (J2-pin9)                                         -                    Reset PTA16 (J2-pin1 - SPI1_Sout)                   -                    MOSI PTA17 (J1-pin5 - SPI1_Sin)                     -                    MISO PTA18 (J1-pin7 - SPI1_SCK)                   -                    SCK PTA19 (J2-pin3 - SPI1_CS)                     -                    CS GND   (J3-pin7)                                        -                    GND ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   4.2 Setting up the development environment   Install MCUXpresso IDE (for this example we are using v10.2.0 build 759)   - Go to MCUXpresso-IDE webpage and download the latest version of IDE: www.nxp.com/products/: MCUXpresso-IDE. - Install the IDE;     Get the latest NFC Reader Library release (for this example we are using v5.21.00) - Go to NXP NFC Reader Library webpage (www.nxp.com/pages/:NFC-READER-LIBRARY) - Go to the Downloads tab and click on the download button - Download the NFC Reader Library for Kinetis K82F package:     Generate a downloadable SDK package for FRDM-KW36 board (SDK_2.2.1_FRDM-KW36) - Navigate to https://mcuxpresso.nxp.com/en/select and select FRDM-KW36 board; - Select Build MCUXpresso SDK. - As toolchain, please make sure that the MCUXpresso IDE is selected. - Use Download SDK button to start downloading SDK package:   Create MCUXpresso workspace - Open MCUXpresso IDE and create a workspace; - Drag and drop the SDK_2.2.1_FRDM-KW36 into the installed SDKs tab of the MCUXpresso IDE;   - Import Wireless_Uart Example to the current workspace:     4.3 Preparing adaptation files for FRDM-KW3x board This chapter describes the Driver Abstraction Layer (DAL) changes required for FRDM-KW36: - unzip the NFC Reader Library and navigate to boards folder:   - Create an equivalent file for FRDM-KW36 (Board_FRDM_KW36FRc663.h) by setting the right configuration for GPIOs and handlers; - Below are the differences required for FRDM-KW36 board in comparation with a FRDM-K82F board:   - Add the FRMD-KW36 to …DAL\cfg\BoardSelection.h file:   #ifdef PHDRIVER_FRDM_KW36FRC663_BOARD #include <Board_FRDM_KW36FRc663.h> #endif   - In KinetisSDK folder, update the following dependencies: o PIT Driver IRQ name:   o Open drain and pin lock configuration: - phDriver_KinetisSDK.c:   - phbalReg_KinetisSpi.c:   - add PHDRIVER_FRDM_KW36FRC663_BOARD define to …\NxpNfcRdLib\types\ph_NxpBuild_Platform.h file to enable the right NFC transceiver:     4.4  Integrating NFC application to Wireless_UART Bluetooth LE example In this chapter we will integrate the BasicDiscoveryLoop NFC example to Wireless_UART Bluetooth LE application. For this, the following steps are required: - On the wireless_uart project location create an “nfc” folder:   - Copy from modified NFC Reader Library the DAL, NxpNfcRdLib and phOsal folders:   - On the wireless_uart project location, “source” folder create a new “nfc” subfolder to integrate the BasicDiscovery loop files:   - Some changes will be required on the BasicDiscoveryLoop files: o Main function renamed to NFC_BasicDiscoveryLoop_Start; o Removed drivers/OS initialization; (all the changes can be observed in the attachment) - Update MCUXpresso workspace by pressing F5 to see the latest changes:   - Update the linker information (Project Properties -> C/C++ Build -> Settings) and preprocessor defines (Project Properties -> C/C++ Build -> Preprocessor):     - Add dependencies: o PIT module/ PIT module initialization; o Update LED, SW configuration; o Increase heap size (gTotalHeapSize_c); o Add functionality for NFC in wireless_uart.c application; (all the changes can be observed in the attachment);   Considering the attached ZIP archive, we can be easily dragged and drop, frdmkw36_w_uart_ncf3320_basic_discovery.zip file, to the MCUXpresso workspace:       4.5 Running the demo - Create hardware connection based on chapter 4.1; - Open a serial terminal on the corresponding COM port for FRDM-KW36 board. The BaudRate used is 115200. - Press SW2 on FRDM-KW36 to start advertising. - Open Mobile APP - IOT toolbox - Wirreless UART.  The FDRM-KW36 board will be listed as NXP_WU:   - Create Bluetooth LE connection. The serial log will contain the log for Bluetooth LE operations:     - Use NFC Cards close to NCF3320 Antenna v1.0 board to initiate discovery demo. - Once the card is detected, an event is sent to the mobile application including technology and UUID of the card: (https://www.youtube.com/watch?v=wCCz5zDIwHE&feature=youtu.be)     Attached is the source code for this example application (frdmkw36_w_uart_ncf3320_basic_discovery).
查看全文
In 802.11 standards, the connection procedure includes three major steps that shall be performed to make the device part of the Wi-Fi network and communicate in the network. Those three steps are device discovery (scanning), device authentication (checking compatibility-capability etc. before connection) and then finally establishment of connection (Association). Going forward, this post provides details for each step. The message exchange in connection procedure is shown below.   Figure 1. Connection Process in open system   Figure 2. Messages exchange in Connection Process   Figure 2 shows Wi-Fi sniffer log for messages exchange procedure between Client and AP device at the time of connection, here Client device is Xiaomi and AP is Marvell device.   Connection Setup Process 1. Scanning To join any network first client or station needs to find it the network. In the wired network, just plugging the cable or jack will find the network. In the wireless world, this requires identification of the compatible network before joining process can begin. This identification process of the network is referred as scanning. Several parameters are needed in the scanning process. These parameters are BSSType, BSSID, channel list, scantype, MinChannelTime and MaxChannelTime. The parameters are set as default depending upon manufacturer Wi-Fi driver, but it can be modified by the user i.e. if the requirement is for hidden network then we can set scantype parameter as passive scan because the active scan is not useful for the hidden network (networks that do not broadcast their SSID). There are two scanning methods, passive scanning and active scanning. By default, radios perform both the types of scanning on all the channels allowed by the country of operation.  While both the types of scanning are available by default, active scanning is performed only by those channels that are allowed to transmit by regional government regulations. Channels that are not authorized for unlicensed use are excluded from active scanning. Passive scan: In Passive Scanning, WLAN station moves to each channel as per the channel list and waits for beacon frames. Beacon frames are used by the access points (and stations in an IBSS) to communicate or to announce themselves. The access point tries to send the beacon at defined interval that is called Target Beacon Transmission Time (TBTT) Nevertheless, access points are just like the any wireless device in the cell. They cannot send if the network is busy. When the time comes for an AP to send a beacon & the network is busy, the AP will delay its beacon transmission until it can gain access to the media. In 802.11, network is busy or not can be checked using CSMA/CA protocol. In CSMA/CA when a frame is ready, the transmitting device checks whether the channel is idle or busy to avoid the collision. If the channel is busy the transmitting device will wait for random duration and check again whether the channel is idle or not. If channel is idle it will send the frame. The Beacon frame structure is as shown below.   Figure 3. Beacon Frame   Description of mandatory field of a Beacon Frame. Timestamp: After receiving the beacon frame, all the stations update their local clocks with this timestamp. This helps with synchronization. Beacon Interval: Represents the number of Time Units (TUs) between Target Beacon Transmission Times (TBTT). Default value is 100TU (102.4 milliseconds). Capability information: It contains information about capability of the device/network SSID: It contains Service set ID of the network. Supported rates: This field contains information of supported data rates by the access point. Notice that this information is not only used by potential clients during passive scanning but also by clients that are already associated to the BSS. A passive scan generally takes more time, since the client must listen and wait for a beacon versus actively probing to find an AP. Another limitation with a passive scan is that if the client does not wait long enough on a channel, then the client may miss an AP beacon.   Active scan: Discovering the network by scanning all possible channels and listening to beacons is not considered to be very efficient. To enhance this discovery process, stations often use what is called active scanning. In the active scanning mode, stations still go through each channel in turn, but instead of passively listening to the signals from AP, stations send a probe request management frame aimed at asking what network is available on this channel. If any AP or active station in an IBSS is presenting that frequency, they should answer with the probe response frame.   Figure 4. Scanning Methods   Once the probe request is sent by the emitting station, it starts a Probe Timer countdown and waits for answers. This Probe Timer value is usually a lot shorter than a beacon interval. Common values are in the 10-millisecond range. At the end of the timer, the station processes the answers it has received. If no answer was received, the station moves to the next channel (on different frequency) and repeats the same discovery process. The purpose of a probe request is typically to discover APs and their supported networks (SSIDs and/or BSSIDs).   Figure 5. Probe Request/Response Frame   This frame contains mainly two fields, the SSID and the rates supported by the mobile station. Stations that receive Probe Request use the information to determine whether the requesting station can join the network. The Probe Response frame fields are very similar to Beacon frame fields that enable mobile stations to match parameters and join the network.   2. Authentication After having performed a network discovery through the probe request/probe response exchange or by listening to beacons, a station wanting to join a network goes through an authentication process, exchanging authentication frames with the access point. On reception of the authentication frame, AP sends acknowledgement and then Authentication Response. The initial purpose of the ‘authentication’ frames to validate the device type, in other words, verify that the requesting station has proper 802.11 capabilities to join the network. Open system authentication: Information related to capabilities are exchanged between station and AP using Authentication Request. If request is accepted, AP sends “success” in Authentication Response. Shared key authentication: IEEE 802.11-1997 standard included a WEP shared key exchange authentication mechanism Called “Shared Key”. This shared key exchange adds two more frames to the default Open System authentication, resulting in a four-frame exchange. This latter method is called Shared Key authentication, requires the use of WEP encryption, and is not widely used (and not recommended) today. First phase of authentication is described above but when WPA or WPA2 is used then second phase of authentication (i.e. 4-way handshaking process) takes place after the device gets associated. The details regarding Open System authentication and Shared-Key authentication is available in 802.11 security post <Link TBD>.   Figure 6. Authentication frame   As shown above, the Authentication Frame consist of the following fields. Authentication Algorithm Number: 0 for Open System & 1 for Shared Key. Authentication Transaction Sequence Number: Indicate current state of progress. Status Code: 0 for Success & 1for Unspecified failures. Challenge Text: Used in Shared Key Authentication frame.   3. Association If the 802.11 authentication phase completes with a Success result, the station moves to the Association phase. The purpose of this exchange is for the station to join the network and obtain an Association ID [AID]. Association request: The first frame sent in the association phase is from the requesting station to the AP (or a station in an IBSS). This frame is the association request frame and the response of this frame is association response frame. Association request is unicast management frame and is always acknowledged.   Figure 7. Association Request   Association response: Once the Association request is acknowledged, the AP examine each field of the request & verify they all match its own 802.11 parameters (refer Figure 6). In case of parameter mismatch, AP checks whether the difference is a blocking or not and based on that AP sends authentication response. -    If the parameter difference is blocking, then response with status code 1 will be sent (to reject the association). -    In case of non-blocking difference/No difference in the parameters, response with status code 0(success) and AP’s own parameters will be sent to the requesting station. Station must be compatible with the AP’s capability otherwise it will drop the association process and start looking for another AP.   Figure 8. Association Response   Connection Teardown Disassociation: Once a station is associated to an AP, either side can terminate the association at any time by sending a disassociation frame. A station can send Disassociation frame before leaving the current network to roam/join another AP. An AP can send this frame in multiple cases like, if the station tries to use invalid parameters, AP itself under configuration change, hackers attack, etc. The disassociation frame (DA) can be the unicast MAC address of the station to disassociate or a broadcast address if the AP needs to disassociate all the stations in its network. In case of unicast frame, the frame will get acknowledge by receiving station and the broadcast frames are not acknowledged.   Figure 9. Disassociation Frame The Disassociation frame is quite small. It contains only one field “Reason code”. A disassociated station is still authenticated. It can try to re-associate by sending a new Association request frame, keeping its authenticated status. A station roaming to another cell may also choose to use a disassociation frame, to be able to keep its authenticated status and accelerate the process when roaming back to the same cell before its authentication timeout expires.   Figure 10. Disassociation Frame Exchange   This frame is also used when parameters change and the station or the AP needs to renegotiate the communications parameters.   De-authentication: The station or AP can also send a de-authentication frame. This frame is used when all communications are terminated, for example, because the AP has to reboot or because the station stops its Wi-Fi communications. It is also used when a frame is received before authentication has completed. For example, a station trying to send an association request or a data frame before having performed the authentication sequence then station will receive a Deauthentication frame from the AP, indicating that authentication must be performed first. The frame format is same as disassociation frame.   Figure 11. Deauthentication Frame Exchange   Roaming Roaming, in the context of an 802.11 wireless network, is the process of a client moving an established Wi-Fi network association from one access point to another access point within the same Extended Service Set (ESS) without losing connection (e.g. within a defined time interval, usually in the range of a few seconds). The roaming time should be smaller for the better performance. In the roaming process, the mobile device will send the disassociation frame to the previously associated Access Point (AP), and will start re-association process by exchanging 802.11 frames with another access point to which the device wants to connect. The client device scans the another AP then exchange authentication frames after that it will send re-association request, here instead of association re-association request is used and the first 2 steps of connection process remains the same.   Figure 12. Message Exchange in Roaming Process     Figure 13. Roaming representation   Wi-Fi APIs used in Connection and Disconnection process Table below shows some of the available APIs in NXP i.MX RT SDK for connection and disconnection process.   Table 1. APIs Available in SDK API Description Can be called from wifi_send_scan_cmd Used for scanning the available network. It supports only single SSID based scan. We can extend this to a list of multiple SSIDs. Station and AP wlan_add_network Add specific network profile to the list of known networks. Station and AP wlan_remove_network Remove specific network profile from the list of known networks. Station and AP wlan_connect Connect with specific network (AP). Station wlan_disconnect Disconnect the station from network (AP). Station wlan_start_network Start specific network. AP wlan_stop_network Stop specific network. AP   For more details on such APIs refer the document “MCUXpresso_SDK_WLAN_Driver_Reference_Manual.pdf” available at location <SDK Documentation>/docs/wifi.
查看全文