1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "sensor_if_service.h"
17#include <refbase.h>
18#include <cinttypes>
19#include "sensor_uhdf_log.h"
20#include "sensor_type.h"
21#include "sensor_callback_vdi.h"
22#include "callback_death_recipient.h"
23#include "sensor_hdi_dump.h"
24#include "devhost_dump_reg.h"
25
26constexpr int DISABLE_SENSOR = 0;
27constexpr int REPORT_INTERVAL = 0;
28constexpr int UNREGISTER_SENSOR = 0;
29constexpr int REGISTER_SENSOR = 1;
30constexpr int ENABLE_SENSOR = 1;
31constexpr int COMMON_REPORT_FREQUENCY = 1000000000;
32constexpr int COPY_SENSORINFO = 1;
33
34enum BatchSeniorMode {
35        SA = 0,
36        SDC = 1
37};
38
39#define HDF_LOG_TAG uhdf_sensor_service
40
41namespace OHOS {
42namespace HDI {
43namespace Sensor {
44namespace V2_0 {
45namespace {
46    constexpr int32_t CALLBACK_CTOUNT_THRESHOLD = 1;
47    using CallBackDeathRecipientMap = std::unordered_map<IRemoteObject *, sptr<CallBackDeathRecipient>>;
48    CallBackDeathRecipientMap g_callBackDeathRecipientMap;
49}
50
51SensorIfService::SensorIfService()
52{
53    int32_t ret = GetSensorVdiImpl();
54    if (ret != HDF_SUCCESS) {
55        HDF_LOGE("%{public}s: get sensor vdi instance failed", __func__);
56    }
57}
58
59SensorIfService::~SensorIfService()
60{
61    if (vdi_ != nullptr) {
62        HdfCloseVdi(vdi_);
63    }
64    RemoveDeathNotice(TRADITIONAL_SENSOR_TYPE);
65    RemoveDeathNotice(MEDICAL_SENSOR_TYPE);
66}
67
68void SensorIfService::RegisteDumpHost()
69{
70    int32_t ret = DevHostRegisterDumpHost(GetSensorDump);
71    if (ret != HDF_SUCCESS) {
72        HDF_LOGE("%{public}s: DevHostRegisterDumpHost error", __func__);
73    }
74    return;
75}
76
77int32_t SensorIfService::GetSensorVdiImpl()
78{
79    struct OHOS::HDI::Sensor::V1_1::WrapperSensorVdi *wrapperSensorVdi = nullptr;
80    uint32_t version = 0;
81    vdi_ = HdfLoadVdi(HDI_SENSOR_VDI_LIBNAME);
82    if (vdi_ == nullptr || vdi_->vdiBase == nullptr) {
83        HDF_LOGE("%{public}s: load sensor vdi failed", __func__);
84        return HDF_FAILURE;
85    }
86
87    version = HdfGetVdiVersion(vdi_);
88    if (version != 1) {
89        HDF_LOGE("%{public}s: get sensor vdi version failed", __func__);
90        return HDF_FAILURE;
91    }
92
93    wrapperSensorVdi = reinterpret_cast<struct OHOS::HDI::Sensor::V1_1::WrapperSensorVdi *>(vdi_->vdiBase);
94    sensorVdiImpl_ = wrapperSensorVdi->sensorModule;
95    if (sensorVdiImpl_ == nullptr) {
96        HDF_LOGE("%{public}s: get sensor impl failed", __func__);
97        return HDF_FAILURE;
98    }
99
100    return HDF_SUCCESS;
101}
102
103int32_t SensorIfService::Init()
104{
105    if (sensorVdiImpl_ == nullptr) {
106        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
107        return HDF_FAILURE;
108    }
109    int32_t ret = sensorVdiImpl_->Init();
110    if (ret != SENSOR_SUCCESS) {
111        HDF_LOGE("%{public}s Init failed, error code is %{public}d", __func__, ret);
112    } else {
113        ret = GetAllSensorInfo(hdfSensorInformations);
114        if (ret != SENSOR_SUCCESS) {
115            HDF_LOGE("%{public}s GetAllSensorInfo failed, error code is %{public}d", __func__, ret);
116        }
117    }
118#ifdef SENSOR_DEBUG
119    RegisteDumpHost();
120#endif
121    return ret;
122}
123
124sptr<SensorCallbackVdi> SensorIfService::GetSensorCb(int32_t groupId, const sptr<ISensorCallback> &callbackObj,
125    bool cbFlag)
126{
127    SENSOR_TRACE_PID;
128    if (groupId == TRADITIONAL_SENSOR_TYPE) {
129        if (cbFlag) {
130            traditionalCb = new SensorCallbackVdi(callbackObj);
131        }
132        return traditionalCb;
133    }
134    if (cbFlag) {
135        medicalCb = new SensorCallbackVdi(callbackObj);
136    }
137    return medicalCb;
138}
139
140int32_t SensorIfService::GetAllSensorInfo(std::vector<HdfSensorInformation> &info)
141{
142    SENSOR_TRACE_PID;
143    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
144    HDF_LOGI("%{public}s: serviceId = %{public}d", __func__, serviceId);
145    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
146    if (sensorVdiImpl_ == nullptr) {
147        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
148        return HDF_FAILURE;
149    }
150
151    std::vector<OHOS::HDI::Sensor::V1_1::HdfSensorInformationVdi> sensorInfoVdi = {};
152    SENSOR_TRACE_START("sensorVdiImpl_->GetAllSensorInfo");
153    int32_t ret = sensorVdiImpl_->GetAllSensorInfo(sensorInfoVdi);
154    SENSOR_TRACE_FINISH;
155    if (ret != SENSOR_SUCCESS) {
156        HDF_LOGE("%{public}s GetAllSensors failed, error code is %{public}d", __func__, ret);
157        return ret;
158    }
159
160    if (sensorInfoVdi.empty()) {
161        HDF_LOGE("%{public}s no sensor info in list", __func__);
162        return HDF_FAILURE;
163    }
164
165    for (const auto &it : sensorInfoVdi) {
166        struct HdfSensorInformation sensorInfo = {};
167        sensorInfo.sensorName = it.sensorName;
168        sensorInfo.vendorName = it.vendorName;
169        sensorInfo.firmwareVersion = it.firmwareVersion;
170        sensorInfo.hardwareVersion = it.hardwareVersion;
171        sensorInfo.sensorTypeId = it.sensorTypeId;
172        sensorInfo.sensorId = it.sensorId;
173        sensorInfo.maxRange = it.maxRange;
174        sensorInfo.accuracy = it.accuracy;
175        sensorInfo.power = it.power;
176        sensorInfo.minDelay = it.minDelay;
177        sensorInfo.maxDelay = it.maxDelay;
178        sensorInfo.fifoMaxEventCount = it.fifoMaxEventCount;
179        info.push_back(std::move(sensorInfo));
180
181        SensorClientsManager::GetInstance()->CopySensorInfo(info, COPY_SENSORINFO);
182    }
183
184    return HDF_SUCCESS;
185}
186
187int32_t SensorIfService::Enable(int32_t sensorId)
188{
189    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId));
190    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
191    HDF_LOGI("%{public}s: sensorId %{public}d, serviceId = %{public}d", __func__, sensorId, serviceId);
192    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
193    if (!SensorClientsManager::GetInstance()->IsUpadateSensorState(sensorId, serviceId, ENABLE_SENSOR)) {
194        return HDF_SUCCESS;
195    }
196
197    if (sensorVdiImpl_ == nullptr) {
198        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
199        return HDF_FAILURE;
200    }
201
202    SENSOR_TRACE_START("sensorVdiImpl_->Enable");
203    int32_t ret = sensorVdiImpl_->Enable(sensorId);
204    SENSOR_TRACE_FINISH;
205    if (ret != SENSOR_SUCCESS) {
206        HDF_LOGE("%{public}s failed, error code is %{public}d, sensorId = %{public}d, serviceId = %{public}d", __func__,
207                 ret, sensorId, serviceId);
208    } else {
209        SensorClientsManager::GetInstance()->OpenSensor(sensorId, serviceId);
210    }
211
212    return ret;
213}
214
215int32_t SensorIfService::Disable(int32_t sensorId)
216{
217    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId));
218    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
219    HDF_LOGI("%{public}s: sensorId %{public}d, serviceId = %{public}d", __func__, sensorId, serviceId);
220    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
221    if (!SensorClientsManager::GetInstance()->IsUpadateSensorState(sensorId, serviceId, DISABLE_SENSOR)) {
222        HDF_LOGE("%{public}s There are still some services enable", __func__);
223        return HDF_SUCCESS;
224    }
225
226    if (sensorVdiImpl_ == nullptr) {
227        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
228        return HDF_FAILURE;
229    }
230
231    int32_t ret;
232    if (SensorClientsManager::GetInstance()->IsExistSdcSensorEnable(sensorId)) {
233        SENSOR_TRACE_START("sensorVdiImpl_->SetSaBatch");
234        ret = sensorVdiImpl_->SetSaBatch(sensorId, REPORT_INTERVAL, REPORT_INTERVAL);
235        SENSOR_TRACE_FINISH;
236        if (ret != SENSOR_SUCCESS) {
237            HDF_LOGE("%{public}s SetSaBatch failed, error code is %{public}d, sensorId = %{public}d, serviceId = "
238                     "%{public}d", __func__, ret, sensorId, serviceId);
239            return ret;
240        }
241        return HDF_SUCCESS;
242    }
243
244    SENSOR_TRACE_START("sensorVdiImpl_->Disable");
245    ret = sensorVdiImpl_->Disable(sensorId);
246    SENSOR_TRACE_FINISH;
247    if (ret != SENSOR_SUCCESS) {
248        HDF_LOGE("%{public}s failed, error code is %{public}d, sensorId = %{public}d, serviceId = %{public}d", __func__,
249                 ret, sensorId, serviceId);
250    }
251
252    return ret;
253}
254
255int32_t SensorIfService::SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval)
256{
257    SENSOR_TRACE;
258    HDF_LOGD("%{public}s: sensorId is %{public}d, samplingInterval is [%{public}" PRId64 "], \
259        reportInterval is [%{public}" PRId64 "].", __func__, sensorId, samplingInterval, reportInterval);
260    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
261    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
262
263    int32_t ret = SetBatchSenior(serviceId, sensorId, SA, samplingInterval, reportInterval);
264    if (ret != SENSOR_SUCCESS) {
265        HDF_LOGE("%{public}s SetBatch failed, error code is %{public}d", __func__, ret);
266    }
267
268    return ret;
269}
270
271int32_t SensorIfService::SetBatchSenior(int32_t serviceId, int32_t sensorId, int32_t mode, int64_t samplingInterval,
272                                        int64_t reportInterval)
273{
274    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId) + "mode " +
275        std::to_string(mode) + "samplingInterval " + std::to_string(samplingInterval) + "reportInterval " +
276        std::to_string(reportInterval));
277    HDF_LOGI("%{public}s: serviceId is %{public}d, sensorId is %{public}d, mode is %{public}d, samplingInterval is "
278             "[%{public}" PRId64 "], reportInterval is [%{public}" PRId64 "].", __func__, serviceId, sensorId, mode,
279             samplingInterval, reportInterval);
280    if (sensorVdiImpl_ == nullptr) {
281        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
282        return HDF_FAILURE;
283    }
284    SensorClientsManager::GetInstance()->SetClientSenSorConfig(sensorId, serviceId, samplingInterval, reportInterval);
285
286    int64_t saSamplingInterval = samplingInterval;
287    int64_t saReportInterval = reportInterval;
288    int64_t sdcSamplingInterval = samplingInterval;
289    int64_t sdcReportInterval = reportInterval;
290
291    SensorClientsManager::GetInstance()->SetSensorBestConfig(sensorId, saSamplingInterval, saReportInterval);
292    SensorClientsManager::GetInstance()->SetSdcSensorBestConfig(sensorId, sdcSamplingInterval, sdcReportInterval);
293
294    samplingInterval = saSamplingInterval < sdcSamplingInterval ? saSamplingInterval : sdcSamplingInterval;
295    reportInterval = saReportInterval < sdcReportInterval ? saReportInterval : sdcReportInterval;
296
297    SENSOR_TRACE_START("sensorVdiImpl_->SetBatch");
298    int32_t ret = sensorVdiImpl_->SetBatch(sensorId, samplingInterval, reportInterval);
299    SENSOR_TRACE_FINISH;
300    if (ret != SENSOR_SUCCESS) {
301        HDF_LOGE("%{public}s SetBatch failed, error code is %{public}d", __func__, ret);
302        return ret;
303    }
304    if (mode == SA) {
305        SetDelay(sensorId, saSamplingInterval, saReportInterval);
306        SensorClientsManager::GetInstance()->UpdateSensorConfig(sensorId, saSamplingInterval, saReportInterval);
307        SensorClientsManager::GetInstance()->UpdateClientPeriodCount(sensorId, saSamplingInterval, saReportInterval);
308    }
309    if (mode == SDC) {
310        SensorClientsManager::GetInstance()->UpdateSdcSensorConfig(sensorId, sdcSamplingInterval, sdcReportInterval);
311    }
312    SensorClientsManager::GetInstance()->GetSensorBestConfig(sensorId, samplingInterval, reportInterval);
313    SENSOR_TRACE_START("sensorVdiImpl_->SetSaBatch");
314    ret = sensorVdiImpl_->SetSaBatch(sensorId, samplingInterval, samplingInterval);
315    SENSOR_TRACE_FINISH;
316    if (ret != SENSOR_SUCCESS) {
317        HDF_LOGE("%{public}s SetSaBatch failed, error code is %{public}d", __func__, ret);
318    }
319
320    return ret;
321}
322
323int32_t SensorIfService::SetDelay(int32_t sensorId, int64_t &samplingInterval, int64_t &reportInterval)
324{
325    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId) + "samplingInterval " +
326                         std::to_string(samplingInterval) + "reportInterval " + std::to_string(reportInterval));
327    HDF_LOGD("%{public}s: sensorId is %{public}d, samplingInterval is [%{public}" PRId64 "], reportInterval is "
328             "[%{public}" PRId64 "].", __func__, sensorId, samplingInterval, reportInterval);
329    for (auto it = hdfSensorInformations.begin(); it != hdfSensorInformations.end(); ++it) {
330        if (it->sensorId == sensorId) {
331            if (samplingInterval < it->minDelay) {
332                samplingInterval = it->minDelay;
333                HDF_LOGI("%{public}s samplingInterval has been set minDelay %{public}s", __func__,
334                         std::to_string(samplingInterval).c_str());
335                return SENSOR_SUCCESS;
336            }
337            if (samplingInterval > it->maxDelay && it->maxDelay != REPORT_INTERVAL) {
338                samplingInterval = it->maxDelay;
339                HDF_LOGI("%{public}s samplingInterval has been set maxDelay %{public}s", __func__,
340                         std::to_string(samplingInterval).c_str());
341                return SENSOR_SUCCESS;
342            }
343        }
344    }
345    HDF_LOGD("%{public}s samplingInterval not change", __func__);
346    return SENSOR_SUCCESS;
347}
348
349int32_t SensorIfService::SetMode(int32_t sensorId, int32_t mode)
350{
351    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId) + "mode " + std::to_string(mode));
352    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
353    HDF_LOGI("%{public}s: sensorId is %{public}d, mode is %{public}d, serviceId = %{public}d", __func__, sensorId, mode,
354             serviceId);
355    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
356    if (sensorVdiImpl_ == nullptr) {
357        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
358        return HDF_FAILURE;
359    }
360
361    SENSOR_TRACE_START("sensorVdiImpl_->SetMode");
362    int32_t ret = sensorVdiImpl_->SetMode(sensorId, mode);
363    SENSOR_TRACE_FINISH;
364    if (ret != SENSOR_SUCCESS) {
365        HDF_LOGE("%{public}s SetMode failed, error code is %{public}d", __func__, ret);
366    }
367
368    return ret;
369}
370
371int32_t SensorIfService::SetOption(int32_t sensorId, uint32_t option)
372{
373    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId) + "option " + std::to_string(option));
374    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
375    HDF_LOGI("%{public}s: sensorId is %{public}d, option is %{public}d, serviceId = %{public}d", __func__, sensorId,
376             option, serviceId);
377    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
378    if (sensorVdiImpl_ == nullptr) {
379        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
380        return HDF_FAILURE;
381    }
382
383    SENSOR_TRACE_START("sensorVdiImpl_->SetOption");
384    int32_t ret = sensorVdiImpl_->SetOption(sensorId, option);
385    SENSOR_TRACE_FINISH;
386    if (ret != SENSOR_SUCCESS) {
387        HDF_LOGE("%{public}s SetOption failed, error code is %{public}d", __func__, ret);
388    }
389
390    return ret;
391}
392
393int32_t SensorIfService::Register(int32_t groupId, const sptr<ISensorCallback> &callbackObj)
394{
395    SENSOR_TRACE_PID;
396    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
397    HDF_LOGI("%{public}s: groupId %{public}d, service %{public}d", __func__, groupId, serviceId);
398    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
399    int32_t ret = HDF_SUCCESS;
400    int32_t result = AddCallbackMap(groupId, callbackObj);
401    if (result !=SENSOR_SUCCESS) {
402        HDF_LOGE("%{public}s: AddCallbackMap failed groupId[%{public}d]", __func__, groupId);
403    }
404    if (SensorClientsManager::GetInstance()->IsClientsEmpty(groupId)) {
405        if (sensorVdiImpl_ == nullptr) {
406            HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
407            return HDF_FAILURE;
408        }
409        sptr<SensorCallbackVdi> sensorCb = GetSensorCb(groupId, callbackObj, REGISTER_SENSOR);
410        if (sensorCb == nullptr) {
411            HDF_LOGE("%{public}s: get sensorcb fail, groupId[%{public}d]", __func__, groupId);
412            return HDF_FAILURE;
413        }
414        SENSOR_TRACE_START("sensorVdiImpl_->Register");
415        ret = sensorVdiImpl_->Register(groupId, sensorCb);
416        SENSOR_TRACE_FINISH;
417        if (ret != SENSOR_SUCCESS) {
418            HDF_LOGE("%{public}s Register failed, error code is %{public}d", __func__, ret);
419            int32_t removeResult = RemoveSensorDeathRecipient(callbackObj);
420            if (removeResult != SENSOR_SUCCESS) {
421                HDF_LOGE("%{public}s: callback RemoveSensorDeathRecipient fail, groupId[%{public}d]",
422                    __func__, groupId);
423            }
424        } else {
425            SensorClientsManager::GetInstance()->ReportDataCbRegister(groupId, serviceId, callbackObj);
426        }
427    } else {
428        SensorClientsManager::GetInstance()->ReportDataCbRegister(groupId, serviceId, callbackObj);
429    }
430    return ret;
431}
432
433int32_t SensorIfService::Unregister(int32_t groupId, const sptr<ISensorCallback> &callbackObj)
434{
435    SENSOR_TRACE_PID;
436    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
437    HDF_LOGI("%{public}s: groupId %{public}d, service %{public}d", __func__, groupId, serviceId);
438    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
439    if (groupId < TRADITIONAL_SENSOR_TYPE || groupId >= SENSOR_GROUP_TYPE_MAX) {
440        HDF_LOGE("%{public}s: groupId %{public}d is error", __func__, groupId);
441        return SENSOR_INVALID_PARAM;
442    }
443    int32_t result = RemoveCallbackMap(groupId, serviceId, callbackObj);
444    if (result !=SENSOR_SUCCESS) {
445        HDF_LOGE("%{public}s: RemoveCallbackMap failed groupId[%{public}d]", __func__, groupId);
446    }
447    SensorClientsManager::GetInstance()->ReportDataCbUnRegister(groupId, serviceId, callbackObj);
448    if (!SensorClientsManager::GetInstance()->IsClientsEmpty(groupId)) {
449        HDF_LOGD("%{public}s: clients is not empty, do not unregister", __func__);
450        return HDF_SUCCESS;
451    }
452    if (!SensorClientsManager::GetInstance()->IsNoSensorUsed()) {
453        HDF_LOGD("%{public}s: sensorUsed is not empty, do not unregister", __func__);
454        return HDF_SUCCESS;
455    }
456
457    if (sensorVdiImpl_ == nullptr) {
458        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
459        return HDF_FAILURE;
460    }
461
462    sptr<SensorCallbackVdi> sensorCb = GetSensorCb(groupId, callbackObj, UNREGISTER_SENSOR);
463    if (sensorCb == nullptr) {
464        HDF_LOGE("%{public}s: get sensorcb fail, groupId[%{public}d]", __func__, groupId);
465        return HDF_FAILURE;
466    }
467    SENSOR_TRACE_START("sensorVdiImpl_->Unregister");
468    int32_t ret = sensorVdiImpl_->Unregister(groupId, sensorCb);
469    SENSOR_TRACE_FINISH;
470    if (ret != SENSOR_SUCCESS) {
471        HDF_LOGE("%{public}s: Unregister failed, error code is %{public}d", __func__, ret);
472    }
473
474    return ret;
475}
476
477int32_t SensorIfService::AddCallbackMap(int32_t groupId, const sptr<ISensorCallback> &callbackObj)
478{
479    SENSOR_TRACE_PID;
480    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
481    HDF_LOGI("%{public}s: service %{public}d", __func__, serviceId);
482    auto groupCallBackIter = callbackMap.find(groupId);
483    if (groupCallBackIter != callbackMap.end()) {
484        auto callBackIter =
485            find_if(callbackMap[groupId].begin(), callbackMap[groupId].end(),
486            [&callbackObj](const sptr<ISensorCallback> &callbackRegistered) {
487                const sptr<IRemoteObject> &lhs = OHOS::HDI::hdi_objcast<ISensorCallback>(callbackObj);
488                const sptr<IRemoteObject> &rhs = OHOS::HDI::hdi_objcast<ISensorCallback>(callbackRegistered);
489                return lhs == rhs;
490            });
491        if (callBackIter == callbackMap[groupId].end()) {
492            int32_t addResult = AddSensorDeathRecipient(callbackObj);
493            if (addResult != SENSOR_SUCCESS) {
494                return HDF_FAILURE;
495            }
496            callbackMap[groupId].push_back(callbackObj);
497        }
498    } else {
499        int32_t addResult = AddSensorDeathRecipient(callbackObj);
500        if (addResult != SENSOR_SUCCESS) {
501            return HDF_FAILURE;
502        }
503        std::vector<sptr<ISensorCallback>> remoteVec;
504        remoteVec.push_back(callbackObj);
505        callbackMap[groupId] = remoteVec;
506    }
507    return SENSOR_SUCCESS;
508}
509
510int32_t SensorIfService::RemoveCallbackMap(int32_t groupId, int serviceId, const sptr<ISensorCallback> &callbackObj)
511{
512    SENSOR_TRACE_PID;
513    HDF_LOGI("%{public}s: service %{public}d", __func__, serviceId);
514    auto groupIdCallBackIter = callbackMap.find(groupId);
515    if (groupIdCallBackIter == callbackMap.end()) {
516        HDF_LOGE("%{public}s: groupId [%{public}d] callbackObj not registered", __func__, groupId);
517        return HDF_FAILURE;
518    }
519    auto callBackIter =
520        find_if(callbackMap[groupId].begin(), callbackMap[groupId].end(),
521        [&callbackObj](const sptr<ISensorCallback> &callbackRegistered) {
522            const sptr<IRemoteObject> &lhs = OHOS::HDI::hdi_objcast<ISensorCallback>(callbackObj);
523            const sptr<IRemoteObject> &rhs = OHOS::HDI::hdi_objcast<ISensorCallback>(callbackRegistered);
524            return lhs == rhs;
525        });
526    if (callBackIter == callbackMap[groupId].end()) {
527        HDF_LOGE("%{public}s: groupId [%{public}d] callbackObj not registered", __func__, groupId);
528        return HDF_FAILURE;
529    }
530    int32_t removeResult = RemoveSensorDeathRecipient(*callBackIter);
531    if (removeResult != SENSOR_SUCCESS) {
532        HDF_LOGE("%{public}s: last callback RemoveSensorDeathRecipient fail, groupId[%{public}d]", __func__, groupId);
533    }
534    if (callbackMap[groupId].size() > CALLBACK_CTOUNT_THRESHOLD) {
535        callbackMap[groupId].erase(callBackIter);
536    } else {
537        callbackMap.erase(groupId);
538    }
539    std::unordered_map<int, std::set<int>> sensorEnabled = SensorClientsManager::GetInstance()->GetSensorUsed();
540    for (auto iter : sensorEnabled) {
541        if (iter.second.find(serviceId) == iter.second.end()) {
542            continue;
543        }
544        if (!SensorClientsManager::GetInstance()->IsUpadateSensorState(iter.first, serviceId, DISABLE_SENSOR)) {
545            continue;
546        }
547        std::unordered_map<int, std::set<int>> sensorUsed = SensorClientsManager::GetInstance()->GetSensorUsed();
548        if (sensorUsed.find(iter.first) == sensorUsed.end()) {
549            SENSOR_TRACE_START("sensorVdiImpl_->Disable");
550            int32_t ret = sensorVdiImpl_->Disable(iter.first);
551            SENSOR_TRACE_FINISH;
552            if (ret != SENSOR_SUCCESS) {
553                HDF_LOGE("%{public}s Disable failed, error code is %{public}d", __func__, ret);
554            }
555        }
556    }
557    return SENSOR_SUCCESS;
558}
559
560int32_t SensorIfService::AddSensorDeathRecipient(const sptr<ISensorCallback> &callbackObj)
561{
562    SENSOR_TRACE_PID;
563    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
564    HDF_LOGI("%{public}s: service %{public}d", __func__, serviceId);
565    sptr<CallBackDeathRecipient> callBackDeathRecipient = new CallBackDeathRecipient(this);
566    if (callBackDeathRecipient == nullptr) {
567        HDF_LOGE("%{public}s: new CallBackDeathRecipient fail", __func__);
568        return HDF_FAILURE;
569    }
570    const sptr<IRemoteObject> &remote = OHOS::HDI::hdi_objcast<ISensorCallback>(callbackObj);
571    bool result = remote->AddDeathRecipient(callBackDeathRecipient);
572    if (!result) {
573        HDF_LOGE("%{public}s: AddDeathRecipient fail", __func__);
574        return HDF_FAILURE;
575    }
576    g_callBackDeathRecipientMap[remote.GetRefPtr()] = callBackDeathRecipient;
577    return SENSOR_SUCCESS;
578}
579
580int32_t SensorIfService::RemoveSensorDeathRecipient(const sptr<ISensorCallback> &callbackObj)
581{
582    SENSOR_TRACE_PID;
583    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
584    HDF_LOGI("%{public}s: service %{public}d", __func__, serviceId);
585    const sptr<IRemoteObject> &remote = OHOS::HDI::hdi_objcast<ISensorCallback>(callbackObj);
586    auto callBackDeathRecipientIter = g_callBackDeathRecipientMap.find(remote.GetRefPtr());
587    if (callBackDeathRecipientIter == g_callBackDeathRecipientMap.end()) {
588        HDF_LOGE("%{public}s: not find recipient", __func__);
589        return HDF_FAILURE;
590    }
591    bool result = remote->RemoveDeathRecipient(callBackDeathRecipientIter->second);
592    g_callBackDeathRecipientMap.erase(callBackDeathRecipientIter);
593    if (!result) {
594        HDF_LOGE("%{public}s: RemoveDeathRecipient fail", __func__);
595        return HDF_FAILURE;
596    }
597    return SENSOR_SUCCESS;
598}
599
600void SensorIfService::OnRemoteDied(const wptr<IRemoteObject> &object)
601{
602    SENSOR_TRACE_PID;
603    HDF_LOGI("%{public}s: service %{public}d", __func__, static_cast<uint32_t>(HdfRemoteGetCallingPid()));
604    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
605    sptr<IRemoteObject> callbackObject = object.promote();
606    if (callbackObject == nullptr) {
607        return;
608    }
609
610    for (int32_t groupId = TRADITIONAL_SENSOR_TYPE; groupId < SENSOR_GROUP_TYPE_MAX; groupId++) {
611        auto groupIdIter = callbackMap.find(groupId);
612        if (groupIdIter == callbackMap.end()) {
613            continue;
614        }
615        auto callBackIter =
616        find_if(callbackMap[groupId].begin(), callbackMap[groupId].end(),
617        [&callbackObject](const sptr<ISensorCallback> &callbackRegistered) {
618            return callbackObject.GetRefPtr() ==
619                (OHOS::HDI::hdi_objcast<ISensorCallback>(callbackRegistered)).GetRefPtr();
620        });
621        if (callBackIter != callbackMap[groupId].end()) {
622            int32_t serviceId = SensorClientsManager::GetInstance()->GetServiceId(groupId, *callBackIter);
623            if (sensorVdiImpl_ == nullptr) {
624                HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
625                continue;
626            }
627            int32_t ret = RemoveCallbackMap(groupId, serviceId, *callBackIter);
628            if (ret != SENSOR_SUCCESS) {
629                HDF_LOGE("%{public}s: Unregister failed groupId[%{public}d]", __func__, groupId);
630            }
631            if (!SensorClientsManager::GetInstance()->IsClientsEmpty(groupId)) {
632                HDF_LOGD("%{public}s: clients is not empty, do not unregister", __func__);
633                continue;
634            }
635            sptr<SensorCallbackVdi> sensorCb = GetSensorCb(groupId, *callBackIter, UNREGISTER_SENSOR);
636            if (sensorCb == nullptr) {
637                HDF_LOGE("%{public}s: get sensorcb fail, groupId[%{public}d]", __func__, groupId);
638                continue;
639            }
640            SENSOR_TRACE_START("sensorVdiImpl_->Unregister");
641            ret = sensorVdiImpl_->Unregister(groupId, sensorCb);
642            SENSOR_TRACE_FINISH;
643            if (ret != SENSOR_SUCCESS) {
644                HDF_LOGE("%{public}s: Unregister failed, error code is %{public}d", __func__, ret);
645            }
646        }
647    }
648}
649
650void  SensorIfService::RemoveDeathNotice(int32_t sensorType)
651{
652    SENSOR_TRACE_PID_MSG("sensorType " + std::to_string(sensorType));
653    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
654    HDF_LOGI("%{public}s: service %{public}d, sensorType %{public}d", __func__, serviceId, sensorType);
655    auto iter = callbackMap.find(sensorType);
656    if (iter != callbackMap.end()) {
657        return;
658    }
659    for (auto callback : callbackMap[sensorType]) {
660        const sptr<IRemoteObject> &remote = OHOS::HDI::hdi_objcast<ISensorCallback>(callback);
661        auto recipientIter = g_callBackDeathRecipientMap.find(remote.GetRefPtr());
662        if (recipientIter != g_callBackDeathRecipientMap.end()) {
663            bool removeResult = remote->RemoveDeathRecipient(recipientIter->second);
664            if (!removeResult) {
665                HDF_LOGE("%{public}s: sensor destroyed, callback RemoveSensorDeathRecipient fail", __func__);
666            }
667        }
668    }
669}
670
671int32_t SensorIfService::ReadData(int32_t sensorId, std::vector<HdfSensorEvents> &event)
672{
673    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId));
674    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
675    HDF_LOGI("%{public}s: service %{public}d", __func__, serviceId);
676    if (sensorVdiImpl_ == nullptr) {
677        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
678        return HDF_FAILURE;
679    }
680
681    return HDF_SUCCESS;
682}
683
684int32_t SensorIfService::SetSdcSensor(int32_t sensorId, bool enabled, int32_t rateLevel)
685{
686    SENSOR_TRACE_PID_MSG("sensorId " + std::to_string(sensorId) + "enabled " + std::to_string(enabled) + "rateLevel " +
687        std::to_string(rateLevel));
688    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
689    HDF_LOGI("%{public}s: sensorId %{public}d, enabled %{public}u, rateLevel %{public}u, serviceId %{public}d",
690             __func__, sensorId, enabled, rateLevel, serviceId);
691    if (sensorVdiImpl_ == nullptr) {
692        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
693        return HDF_FAILURE;
694    }
695    int32_t ret;
696    if (rateLevel < REPORT_INTERVAL) {
697        HDF_LOGE("%{public}s: rateLevel cannot less than zero", __func__);
698        return HDF_FAILURE;
699    }
700    int64_t samplingInterval = rateLevel == REPORT_INTERVAL ? REPORT_INTERVAL : COMMON_REPORT_FREQUENCY / rateLevel;
701    int64_t reportInterval = REPORT_INTERVAL;
702    if (enabled) {
703        std::unique_lock<std::mutex> lock(sensorServiceMutex_);
704        ret = SetBatchSenior(serviceId, sensorId, SDC, samplingInterval, reportInterval);
705        if (ret != SENSOR_SUCCESS) {
706            HDF_LOGE("%{public}s SetBatchSenior SDC failed, error code is %{public}d", __func__, ret);
707            return ret;
708        }
709        SENSOR_TRACE_START("sensorVdiImpl_->Enable");
710        ret = sensorVdiImpl_->Enable(sensorId);
711        SENSOR_TRACE_FINISH;
712        if (ret != SENSOR_SUCCESS) {
713            HDF_LOGE("%{public}s Enable failed, error code is %{public}d", __func__, ret);
714            return ret;
715        }
716    } else {
717        SensorClientsManager::GetInstance()->EraseSdcSensorBestConfig(sensorId);
718        ret = Disable(sensorId);
719        if (ret != SENSOR_SUCCESS) {
720            HDF_LOGE("%{public}s Disable failed, error code is %{public}d", __func__, ret);
721            return ret;
722        }
723        SensorClientsManager::GetInstance()->GetSensorBestConfig(sensorId, samplingInterval, reportInterval);
724        SENSOR_TRACE_START("sensorVdiImpl_->SetSaBatch");
725        ret = sensorVdiImpl_->SetSaBatch(sensorId, samplingInterval, samplingInterval);
726        SENSOR_TRACE_FINISH;
727        if (ret != SENSOR_SUCCESS) {
728            HDF_LOGE("%{public}s SetSaBatch failed, error code is %{public}d", __func__, ret);
729            return ret;
730        }
731    }
732    return ret;
733}
734
735int32_t SensorIfService::GetSdcSensorInfo(std::vector<SdcSensorInfo>& sdcSensorInfo)
736{
737    SENSOR_TRACE_PID;
738    uint32_t serviceId = static_cast<uint32_t>(HdfRemoteGetCallingPid());
739    HDF_LOGI("%{public}s: serviceId %{public}d", __func__, serviceId);
740    std::unique_lock<std::mutex> lock(sensorServiceMutex_);
741    if (sensorVdiImpl_ == nullptr) {
742        HDF_LOGE("%{public}s: get sensor vdi impl failed", __func__);
743        return HDF_FAILURE;
744    }
745
746    std::vector<OHOS::HDI::Sensor::V1_1::SdcSensorInfoVdi> sdcSensorInfoVdi;
747    SENSOR_TRACE_START("sensorVdiImpl_->GetSdcSensorInfo");
748    int32_t ret = sensorVdiImpl_->GetSdcSensorInfo(sdcSensorInfoVdi);
749    SENSOR_TRACE_FINISH;
750    if (ret != SENSOR_SUCCESS) {
751        HDF_LOGE("%{public}s GetSdcSensorInfo failed, error code is %{public}d", __func__, ret);
752    }
753
754    for (auto infoVdi : sdcSensorInfoVdi) {
755        SdcSensorInfo info;
756        info.offset = infoVdi.offset;
757        info.sensorId = infoVdi.sensorId;
758        info.ddrSize = infoVdi.ddrSize;
759        info.minRateLevel = infoVdi.minRateLevel;
760        info.maxRateLevel = infoVdi.maxRateLevel;
761        info.memAddr = infoVdi.memAddr;
762        info.reserved = infoVdi.reserved;
763        sdcSensorInfo.push_back(std::move(info));
764    }
765
766    return ret;
767}
768
769extern "C" ISensorInterface *SensorInterfaceImplGetInstance(void)
770{
771    SensorIfService *impl = new (std::nothrow) SensorIfService();
772    if (impl == nullptr) {
773        return nullptr;
774    }
775
776    int32_t ret = impl->Init();
777    if (ret != HDF_SUCCESS) {
778        HDF_LOGE("%{public}s: service init failed, error code is %{public}d", __func__, ret);
779        delete impl;
780        return nullptr;
781    }
782
783    return impl;
784}
785} // namespace V2_0
786} // namespace Sensor
787} // namespace HDI
788} // namespace OHOS