1# Sensor Development (C/C++) 2 3 4## When to Use 5 6With the sensor module, a device can obtain sensor data. For example, the device can subscribe to data of the orientation sensor to detect its own orientation, and data of the pedometer sensor to learn the number of steps the user walks every day. 7 8For details about the APIs, see [Sensor API Reference](../../reference/apis-sensor-service-kit/_sensor.md). 9 10## Function Description 11 12| Name | Description | 13| ------------------------------------------------------------ | ------------------------------------------------------------ | 14| OH_Sensor_GetInfos(Sensor_Info **infos, uint32_t *count) | Obtains information about all sensors on the device. | 15| OH_Sensor_Subscribe(const Sensor_SubscriptionId *id, const Sensor_SubscriptionAttribute *attribute, const Sensor_Subscriber *subscriber) | Subscribe to sensor data. The system will report sensor data to the subscriber at the specified frequency.<br>To subscribe to data of acceleration sensors, request the **ohos.permission.ACCELEROMETER** permission.<br>To subscribe to data of gyroscope sensors, request the **ohos.permission.GYROSCOPE** permission.<br>To subscribe to data of pedometer-related sensors, request the **ohos.permission.ACTIVITY_MOTION** permission.<br>To subscribe to data of health-related sensors, such as heart rate sensors, request the **ohos.permission.READ_HEALTH_DATA** permission. Otherwise, the subscription fails.<br>You do not need to request any permission to subscribe to data of other types of sensors.| 16| OH_Sensor_Unsubscribe(const Sensor_SubscriptionId *id, const Sensor_Subscriber *subscriber) | Unsubscribes from sensor data.<br>To unsubscribe from data of acceleration sensors, request the **ohos.permission.ACCELEROMETER** permission.<br>To unsubscribe from data of gyroscope sensors, request the **ohos.permission.GYROSCOPE** permission.<br>To unsubscribe from data of pedometer-related sensors, request the **ohos.permission.ACTIVITY_MOTION** permission.<br>To unsubscribe from data of health-related sensors, request the **ohos.permission.READ_HEALTH_DATA** permission. Otherwise, the unsubscription fails.<br>You do not need to request any permission to unsubscribe from data of other types of sensors.| 17| OH_Sensor_CreateInfos(uint32_t count) | Creates an array of instances with the given number. For details, see [Sensor_Info](../../reference/apis-sensor-service-kit/_sensor.md).| 18| OH_Sensor_DestroyInfos(Sensor_Info **sensors, uint32_t count) | Destroys the array of instances and reclaims the memory. For details, see [Sensor_Info](../../reference/apis-sensor-service-kit/_sensor.md).| 19| OH_SensorInfo_GetName(Sensor_Info *sensor, char *sensorName, uint32_t *length) | Obtains the sensor name. | 20| OH_SensorInfo_GetVendorName(Sensor_Info* sensor, char *vendorName, uint32_t *length) | Obtains the sensor's vendor name. | 21| OH_SensorInfo_GetType(Sensor_Info* sensor, Sensor_Type *sensorType) | Obtains the sensor type. | 22| OH_SensorInfo_GetResolution(Sensor_Info* sensor, float *resolution) | Obtains the sensor resolution. | 23| OH_SensorInfo_GetMinSamplingInterval(Sensor_Info* sensor, int64_t *minSamplingInterval) | Obtains the minimum data reporting interval of a sensor. | 24| OH_SensorInfo_GetMaxSamplingInterval(Sensor_Info* sensor, int64_t *maxSamplingInterval) | Obtains the maximum data reporting interval of a sensor. | 25| OH_SensorEvent_GetType(Sensor_Event* sensorEvent, Sensor_Type *sensorType) | Obtains the sensor type. | 26| OH_SensorEvent_GetTimestamp(Sensor_Event* sensorEvent, int64_t *timestamp) | Obtains the timestamp of sensor data. | 27| OH_SensorEvent_GetAccuracy(Sensor_Event* sensorEvent, Sensor_Accuracy *accuracy) | Obtains the accuracy of sensor data. | 28| OH_SensorEvent_GetData(Sensor_Event* sensorEvent, float **data, uint32_t *length) | Obtains sensor data.<br>The data length and content depend on the sensor type. The format of the sensor data reported is as follows:<br>- SENSOR_TYPE_ACCELEROMETER: data[0], data[1], and data[2], indicating the acceleration around the x, y, and z axes of a device, respectively, in m/s².<br>- SENSOR_TYPE_GYROSCOPE: data[0], data[1], and data[2], indicating the angular velocity of rotation around the x, y, and z axes of a device, respectively, in rad/s.<br>- SENSOR_TYPE_AMBIENT_LIGHT: data[0], indicating the ambient light intensity, in lux. Since API version 12, two extra data records are returned, where **data[1]** indicates the color temperature (in kelvin), and **data[2]** indicates the infrared luminance (in cd/m²).<br> - SENSOR_TYPE_MAGNETIC_FIELD: data[0], data[1], and data[2], indicating the magnetic field strength around the x, y, and z axes of a device, respectively, in μT.<br>- SENSOR_TYPE_BAROMETER: data[0], indicating the atmospheric pressure, in hPa.<br>- SENSOR_TYPE_HALL: data[0], indicating the opening/closing state of the flip cover. The value **0** means that the flip cover is opened, and a value greater than 0 means that the flip cover is closed.<br>- SENSOR_TYPE_PROXIMITY: data[0], indicates the approaching state. The value **0** means the two objects are close to each other, and a value greater than 0 means that they are far away from each other.<br>- SENSOR_TYPE_ORIENTATION: data[0], data[1], and data[2], indicating the rotation angles of a device around the z, x, and y axes, respectively, in degree.<br>- SENSOR_TYPE_GRAVITY: data[0], data[1], and data[2], indicating the gravitational acceleration around the x, y, and z axes of a device, respectively, in m/s².<br>- SENSOR_TYPE_ROTATION_VECTOR: data[0], data[1] and data[2], indicating the rotation angles of a device around the x, y, and z axes, respectively, in degree. data[3] indicates the rotation vector.<br>- SENSOR_TYPE_PEDOMETER_DETECTION: data[0], indicating the pedometer detection status. The value **1** means that the number of detected steps changes.<br>- SENSOR_TYPE_PEDOMETER: data[0], indicating the number of steps a user has walked.<br>- SENSOR_TYPE_HEART_RATE: data[0], indicating the heart rate value.| 29| OH_Sensor_CreateSubscriptionId(void) | Creates a **Sensor_SubscriptionId** instance. | 30| OH_Sensor_DestroySubscriptionId(Sensor_SubscriptionId *id) | Destroys a **Sensor_SubscriptionId** instance and reclaims memory. | 31| OH_SensorSubscriptionId_GetType(Sensor_SubscriptionId *id, Sensor_Type *sensorType) | Obtains the sensor type. | 32| OH_SensorSubscriptionId_SetType(Sensor_SubscriptionId* id, const Sensor_Type sensorType) | Sets the sensor type. | 33| OH_Sensor_CreateSubscriptionAttribute(void) | Creates a **Sensor_SubscriptionAttribute** instance. | 34| OH_Sensor_DestroySubscriptionAttribute(Sensor_SubscriptionAttribute *attribute) | Destroys a **Sensor_SubscriptionAttribute** instance and reclaims memory. | 35| OH_SensorSubscriptionAttribute_SetSamplingInterval(Sensor_SubscriptionAttribute* attribute, const int64_t samplingInterval) | Sets the interval for reporting sensor data. | 36| OH_SensorSubscriptionAttribute_GetSamplingInterval(Sensor_SubscriptionAttribute* attribute, int64_t *samplingInterval) | Obtains the interval for reporting sensor data. | 37| OH_Sensor_CreateSubscriber(void) | Creates a **Sensor_Subscriber** instance. | 38| OH_Sensor_DestroySubscriber(Sensor_Subscriber *subscriber) | Destroys a **Sensor_Subscriber** instance and reclaims memory. | 39| OH_SensorSubscriber_SetCallback(Sensor_Subscriber* subscriber, const Sensor_EventCallback callback) | Sets a callback function to report sensor data. | 40| OH_SensorSubscriber_GetCallback(Sensor_Subscriber* subscriber, Sensor_EventCallback *callback) | Obtains the callback function used to report sensor data. | 41 42 43## How to Develop 44 45The following uses the acceleration sensor as an example to describe the development procedure. 46 471. Create a native C++ project. 48 49  50 512. Check whether the corresponding permission has been configured. For details, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md). 52 53 ```json 54 "requestPermissions": [ 55 { 56 "name": "ohos.permission.ACCELEROMETER", 57 }, 58 ] 59 ``` 60 613. Add the dynamic dependency libraries into the **CMakeLists.txt** file. 62 63 ```c 64 target_link_libraries(entry PUBLIC libace_napi.z.so) 65 target_link_libraries(entry PUBLIC libhilog_ndk.z.so) 66 target_link_libraries(entry PUBLIC libohsensor.so) 67 ``` 68 694. Import the module. 70 71 ```c 72 #include "sensors/oh_sensor.h" 73 #include "napi/native_api.h" 74 #include "hilog/log.h" 75 #include <thread> 76 ``` 77 785. Define constants. 79 80 ```c 81 const int GLOBAL_RESMGR = 0xFF00; 82 const char *TAG = "[Sensor]"; 83 constexpr Sensor_Type SENSOR_ID { SENSOR_TYPE_ACCELEROMETER }; 84 constexpr uint32_t SENSOR_NAME_LENGTH_MAX = 64; 85 constexpr int64_t SENSOR_SAMPLE_PERIOD = 200000000; 86 constexpr int32_t SLEEP_TIME_MS = 1000; 87 constexpr int64_t INVALID_VALUE = -1; 88 constexpr float INVALID_RESOLUTION = -1.0F; 89 Sensor_Subscriber *g_user = nullptr; 90 ``` 91 926. Define a callback function to receive sensor data. 93 94 ```c 95 void SensorDataCallbackImpl(Sensor_Event *event) { 96 if (event == nullptr) { 97 OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, TAG, "event is null"); 98 return; 99 } 100 int64_t timestamp = INVALID_VALUE; 101 int32_t ret = OH_SensorEvent_GetTimestamp(event, ×tamp); // Obtain the timestamp of sensor data. 102 if (ret != SENSOR_SUCCESS) { 103 return; 104 } 105 Sensor_Type sensorType; 106 ret = OH_SensorEvent_GetType(event, &sensorType); // Obtain the sensor type. 107 if (ret != SENSOR_SUCCESS) { 108 return; 109 } 110 Sensor_Accuracy accuracy = SENSOR_ACCURACY_UNRELIABLE; 111 ret = OH_SensorEvent_GetAccuracy(event, &accuracy); // Obtain the accuracy of sensor data. 112 if (ret != SENSOR_SUCCESS) { 113 return; 114 } 115 float *data = nullptr; 116 uint32_t length = 0; 117 ret = OH_SensorEvent_GetData(event, &data, &length); // Obtain sensor data. 118 if (ret != SENSOR_SUCCESS) { 119 return; 120 } 121 OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, TAG, "sensorType:%{public}d, dataLen:%{public}d, accuracy:%{public}d", sensorType, length, accuracy); 122 for (uint32_t i = 0; i < length; ++i) { 123 OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, TAG, "data[%{public}d]:%{public}f", i, data[i]); 124 } 125 } 126 ``` 127 1287. Obtain information about all sensors on the device. 129 130 ```c 131 static napi_value GetSensorInfos(napi_env env, napi_callback_info info) 132 { 133 uint32_t count = 0; 134 int32_t ret = OH_Sensor_GetInfos(nullptr, &count); // Obtain the number of all sensors on the device. 135 if (ret != SENSOR_SUCCESS) { 136 return nullptr; 137 } 138 Sensor_Info **sensors = OH_Sensor_CreateInfos(count); // Create an array of instances with the given number. 139 if (ret != SENSOR_SUCCESS) { 140 return nullptr; 141 } 142 ret = OH_Sensor_GetInfos(sensors, &count); // Obtain information about all sensors on the device. 143 if (ret != SENSOR_SUCCESS) { 144 return nullptr; 145 } 146 for (uint32_t i = 0; i < count; ++i) { 147 char sensorName[SENSOR_NAME_LENGTH_MAX] = {}; 148 uint32_t length = SENSOR_NAME_LENGTH_MAX; 149 ret = OH_SensorInfo_GetName(sensors[i], sensorName, &length); // Obtain the sensor name. 150 if (ret != SENSOR_SUCCESS) { 151 return nullptr; 152 } 153 char vendorName[SENSOR_NAME_LENGTH_MAX] = {}; 154 length = SENSOR_NAME_LENGTH_MAX; 155 ret = OH_SensorInfo_GetVendorName(sensors[i], vendorName, &length); // Obtain the manufacturer name of the sensor. 156 if (ret != SENSOR_SUCCESS) { 157 return nullptr; 158 } 159 Sensor_Type sensorType; 160 ret = OH_SensorInfo_GetType(sensors[i], &sensorType); // Obtain the sensor type. 161 if (ret != SENSOR_SUCCESS) { 162 return nullptr; 163 } 164 float resolution = INVALID_RESOLUTION; 165 ret = OH_SensorInfo_GetResolution(sensors[i], &resolution); // Obtain the sensor resolution. 166 if (ret != SENSOR_SUCCESS) { 167 return nullptr; 168 } 169 int64_t minSamplePeriod = INVALID_VALUE; 170 ret = OH_SensorInfo_GetMinSamplingInterval(sensors[i], &minSamplePeriod); // Obtain the minimum data reporting interval of a sensor. 171 if (ret != SENSOR_SUCCESS) { 172 return nullptr; 173 } 174 int64_t maxSamplePeriod = INVALID_VALUE; 175 ret = OH_SensorInfo_GetMaxSamplingInterval(sensors[i], &maxSamplePeriod); // Obtain the maximum data reporting interval of a sensor. 176 if (ret != SENSOR_SUCCESS) { 177 return nullptr; 178 } 179 } 180 OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, TAG, "GetSensorInfos sucessful"); 181 ret = OH_Sensor_DestroyInfos(sensors, count); // Destroy an array of instances and reclaim the memory. 182 if (ret != SENSOR_SUCCESS) { 183 return nullptr; 184 } 185 } 186 ``` 187 1888. Subscribe to and unsubscribe from sensor data. 189 190 ```c 191 static napi_value Subscriber(napi_env env, napi_callback_info info) 192 { 193 g_user = OH_Sensor_CreateSubscriber(); // Create a Sensor_Subscriber instance. 194 int32_t ret = OH_SensorSubscriber_SetCallback(g_user, SensorDataCallbackImpl); // Set a callback function to report sensor data. 195 if (ret != SENSOR_SUCCESS) { 196 return nullptr; 197 } 198 199 Sensor_SubscriptionId *id = OH_Sensor_CreateSubscriptionId(); // Create a Sensor_SubscriptionId instance. 200 ret = OH_SensorSubscriptionId_SetType(id, SENSOR_ID); // Set the sensor type. 201 if (ret != SENSOR_SUCCESS) { 202 return nullptr; 203 } 204 205 Sensor_SubscriptionAttribute *attr = OH_Sensor_CreateSubscriptionAttribute(); // Create a Sensor_SubscriptionAttribute instance. 206 ret = OH_SensorSubscriptionAttribute_SetSamplingInterval(attr, SENSOR_SAMPLE_PERIOD); // Set the interval for reporting sensor data. 207 if (ret != SENSOR_SUCCESS) { 208 return nullptr; 209 } 210 211 ret = OH_Sensor_Subscribe(id, attr, g_user); // Subscribe to sensor data. 212 if (ret != SENSOR_SUCCESS) { 213 return nullptr; 214 } 215 OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, TAG, "Subscriber successful"); 216 std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS)); 217 ret = OH_Sensor_Unsubscribe(id, g_user); // Unsubscribe from sensor data. 218 if (ret != SENSOR_SUCCESS) { 219 return nullptr; 220 } 221 if (id != nullptr) { 222 OH_Sensor_DestroySubscriptionId(id); // Destroy the Sensor_SubscriptionId instance and reclaim the memory. 223 } 224 if (attr != nullptr) { 225 OH_Sensor_DestroySubscriptionAttribute(attr); // Destroy the Sensor_SubscriptionAttribute instance and reclaim the memory. 226 } 227 if (g_user != nullptr) { 228 OH_Sensor_DestroySubscriber(g_user); // Destroy the Sensor_Subscriber instance and reclaim the memory. 229 g_user = nullptr; 230 } 231 } 232 ``` 233 2349. Introduce the NAPI APIs to the **index.d.ts** file in **types/libentry**. 235 236 ```c 237 export const getSensorInfos: () => number; 238 export const subscriber: () => number; 239 ``` 240 24110. Write JavaScript test cases to test the APIs. 242