1 /*
2 * Copyright (c) 2021 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 "report_data_callback.h"
17 #include "sensors_errors.h"
18
19 namespace OHOS {
20 namespace Sensors {
21 using namespace OHOS::HiviewDFX;
22
23 namespace {
24 constexpr HiLogLabel LABEL = {LOG_CORE, SENSOR_LOG_DOMAIN, "ReportDataCallback"};
25 } // namespace
ReportDataCallback()26 ReportDataCallback::ReportDataCallback()
27 {
28 eventsBuf_.circularBuf = new (std::nothrow) SensorData[CIRCULAR_BUF_LEN];
29 CHKPL(eventsBuf_.circularBuf);
30 eventsBuf_.readPos = 0;
31 eventsBuf_.writePosition = 0;
32 eventsBuf_.eventNum = 0;
33 }
34
~ReportDataCallback()35 ReportDataCallback::~ReportDataCallback()
36 {
37 if (eventsBuf_.circularBuf != nullptr) {
38 delete[] eventsBuf_.circularBuf;
39 eventsBuf_.circularBuf = nullptr;
40 }
41 eventsBuf_.circularBuf = nullptr;
42 eventsBuf_.readPos = 0;
43 eventsBuf_.writePosition = 0;
44 eventsBuf_.eventNum = 0;
45 }
46
ReportEventCallback(SensorData * sensorData,sptr<ReportDataCallback> cb)47 int32_t ReportDataCallback::ReportEventCallback(SensorData* sensorData, sptr<ReportDataCallback> cb)
48 {
49 CHKPR(sensorData, ERROR);
50 if (cb == nullptr || cb->eventsBuf_.circularBuf == nullptr) {
51 SEN_HILOGE("Callback or circularBuf or event cannot be null");
52 return ERROR;
53 }
54 int32_t leftSize = CIRCULAR_BUF_LEN - cb->eventsBuf_.eventNum;
55 int32_t toEndLen = CIRCULAR_BUF_LEN - cb->eventsBuf_.writePosition;
56 if (leftSize < 0 || toEndLen < 0) {
57 SEN_HILOGE("Leftsize and toendlen cannot be less than zero");
58 return ERROR;
59 }
60 if (toEndLen == 0) {
61 cb->eventsBuf_.circularBuf[0] = *sensorData;
62 cb->eventsBuf_.writePosition = 1;
63 } else {
64 cb->eventsBuf_.circularBuf[cb->eventsBuf_.writePosition] = *sensorData;
65 cb->eventsBuf_.writePosition += 1;
66 }
67 if (leftSize < 1) {
68 cb->eventsBuf_.readPos = cb->eventsBuf_.writePosition;
69 }
70 cb->eventsBuf_.eventNum += 1;
71 if (cb->eventsBuf_.eventNum >= CIRCULAR_BUF_LEN) {
72 cb->eventsBuf_.eventNum = CIRCULAR_BUF_LEN;
73 }
74 if (cb->eventsBuf_.writePosition == CIRCULAR_BUF_LEN) {
75 cb->eventsBuf_.writePosition = 0;
76 }
77 return ERR_OK;
78 }
79
GetEventData()80 CircularEventBuf &ReportDataCallback::GetEventData()
81 {
82 return eventsBuf_;
83 }
84 } // namespace Sensors
85 } // namespace OHOS
86