1 /*
2 * Copyright (c) 2021-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_service_client.h"
17
18 #include <sys/socket.h>
19 #include <thread>
20 #include <unistd.h>
21 #include <vector>
22
23 #include "death_recipient_template.h"
24 #include "hisysevent.h"
25 #include "hitrace_meter.h"
26 #include "ipc_skeleton.h"
27 #include "sensor_agent_proxy.h"
28 #include "sensor_errors.h"
29 #include "sensor_service_proxy.h"
30 #include "system_ability_definition.h"
31 #include "rust_binding.h"
32
33 #undef LOG_TAG
34 #define LOG_TAG "SensorServiceClient"
35
36 namespace OHOS {
37 namespace Sensors {
38 using namespace OHOS::HiviewDFX;
39
40 namespace {
41 constexpr int32_t GET_SERVICE_MAX_COUNT = 3;
42 constexpr uint32_t WAIT_MS = 200;
43 #ifdef OHOS_BUILD_ENABLE_RUST
44 extern "C" {
45 void ReadClientPackets(RustStreamBuffer *, OHOS::Sensors::SensorServiceClient *,
46 void(*)(OHOS::Sensors::SensorServiceClient *, RustNetPacket *));
OnPacket(SensorServiceClient * object,RustNetPacket * cPkt)47 void OnPacket(SensorServiceClient *object, RustNetPacket *cPkt)
48 {
49 NetPacket pkt(cPkt->msgId);
50 pkt.streamBufferPtr_.reset(cPkt->streamBuffer);
51 object->HandleNetPacke(pkt);
52 }
53 }
54 #endif // OHOS_BUILD_ENABLE_RUST
55 } // namespace
56
~SensorServiceClient()57 SensorServiceClient::~SensorServiceClient()
58 {
59 if (sensorServer_ != nullptr && serviceDeathObserver_ != nullptr) {
60 auto remoteObject = sensorServer_->AsObject();
61 if (remoteObject != nullptr) {
62 remoteObject->RemoveDeathRecipient(serviceDeathObserver_);
63 }
64 }
65 Disconnect();
66 }
67
InitServiceClient()68 int32_t SensorServiceClient::InitServiceClient()
69 {
70 CALL_LOG_ENTER;
71 std::lock_guard<std::mutex> clientLock(clientMutex_);
72 if (sensorServer_ != nullptr) {
73 SEN_HILOGD("Already init");
74 return ERR_OK;
75 }
76 if (sensorClientStub_ == nullptr) {
77 sensorClientStub_ = new (std::nothrow) SensorClientStub();
78 }
79 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
80 CHKPR(systemAbilityManager, SENSOR_NATIVE_SAM_ERR);
81 int32_t retry = 0;
82 while (retry < GET_SERVICE_MAX_COUNT) {
83 auto object = systemAbilityManager->GetSystemAbility(SENSOR_SERVICE_ABILITY_ID);
84 CHKPR(object, SENSOR_NATIVE_GET_SERVICE_ERR);
85 sensorServer_ = iface_cast<ISensorService>(object);
86 if (sensorServer_ != nullptr) {
87 SEN_HILOGD("Get service success, retry:%{public}d", retry);
88 serviceDeathObserver_ = new (std::nothrow) DeathRecipientTemplate(*const_cast<SensorServiceClient *>(this));
89 CHKPR(serviceDeathObserver_, SENSOR_NATIVE_GET_SERVICE_ERR);
90 auto remoteObject = sensorServer_->AsObject();
91 CHKPR(remoteObject, SENSOR_NATIVE_GET_SERVICE_ERR);
92 remoteObject->AddDeathRecipient(serviceDeathObserver_);
93 sensorList_ = sensorServer_->GetSensorList();
94 return ERR_OK;
95 }
96 SEN_HILOGW("Get service failed, retry:%{public}d", retry);
97 std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_MS));
98 retry++;
99 }
100 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SENSOR, "SERVICE_EXCEPTION",
101 HiSysEvent::EventType::FAULT, "PKG_NAME", "InitServiceClient", "ERROR_CODE", SENSOR_NATIVE_GET_SERVICE_ERR);
102 SEN_HILOGE("Get service failed");
103 return SENSOR_NATIVE_GET_SERVICE_ERR;
104 }
105
IsValid(int32_t sensorId)106 bool SensorServiceClient::IsValid(int32_t sensorId)
107 {
108 int32_t ret = InitServiceClient();
109 if (ret != ERR_OK) {
110 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
111 }
112 std::lock_guard<std::mutex> clientLock(clientMutex_);
113 if (sensorList_.empty()) {
114 SEN_HILOGE("sensorList_ cannot be empty");
115 return false;
116 }
117 for (auto &sensor : sensorList_) {
118 if (sensor.GetSensorId() == sensorId) {
119 return true;
120 }
121 }
122 return false;
123 }
124
EnableSensor(int32_t sensorId,int64_t samplingPeriod,int64_t maxReportDelay)125 int32_t SensorServiceClient::EnableSensor(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay)
126 {
127 CALL_LOG_ENTER;
128 int32_t ret = InitServiceClient();
129 if (ret != ERR_OK) {
130 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
131 return ret;
132 }
133 std::lock_guard<std::mutex> clientLock(clientMutex_);
134 CHKPR(sensorServer_, ERROR);
135 StartTrace(HITRACE_TAG_SENSORS, "EnableSensor");
136 ret = sensorServer_->EnableSensor(sensorId, samplingPeriod, maxReportDelay);
137 FinishTrace(HITRACE_TAG_SENSORS);
138 if (ret == ERR_OK) {
139 UpdateSensorInfoMap(sensorId, samplingPeriod, maxReportDelay);
140 }
141 return ret;
142 }
143
DisableSensor(int32_t sensorId)144 int32_t SensorServiceClient::DisableSensor(int32_t sensorId)
145 {
146 CALL_LOG_ENTER;
147 int32_t ret = InitServiceClient();
148 if (ret != ERR_OK) {
149 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
150 return ret;
151 }
152 std::lock_guard<std::mutex> clientLock(clientMutex_);
153 CHKPR(sensorServer_, ERROR);
154 StartTrace(HITRACE_TAG_SENSORS, "DisableSensor");
155 ret = sensorServer_->DisableSensor(sensorId);
156 FinishTrace(HITRACE_TAG_SENSORS);
157 if (ret == ERR_OK) {
158 DeleteSensorInfoItem(sensorId);
159 }
160 return ret;
161 }
162
GetSensorList()163 std::vector<Sensor> SensorServiceClient::GetSensorList()
164 {
165 CALL_LOG_ENTER;
166 int32_t ret = InitServiceClient();
167 if (ret != ERR_OK) {
168 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
169 return {};
170 }
171 std::lock_guard<std::mutex> clientLock(clientMutex_);
172 if (sensorList_.empty()) {
173 SEN_HILOGE("sensorList_ cannot be empty");
174 }
175 return sensorList_;
176 }
177
TransferDataChannel(sptr<SensorDataChannel> sensorDataChannel)178 int32_t SensorServiceClient::TransferDataChannel(sptr<SensorDataChannel> sensorDataChannel)
179 {
180 CALL_LOG_ENTER;
181 CHKPR(sensorDataChannel, INVALID_POINTER);
182 {
183 std::lock_guard<std::mutex> channelLock(channelMutex_);
184 dataChannel_ = sensorDataChannel;
185 }
186 int32_t ret = InitServiceClient();
187 if (ret != ERR_OK) {
188 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
189 return ret;
190 }
191 std::lock_guard<std::mutex> clientLock(clientMutex_);
192 CHKPR(sensorServer_, ERROR);
193 StartTrace(HITRACE_TAG_SENSORS, "TransferDataChannel");
194 CHKPR(sensorClientStub_, INVALID_POINTER);
195 auto remoteObject = sensorClientStub_->AsObject();
196 CHKPR(remoteObject, INVALID_POINTER);
197 ret = sensorServer_->TransferDataChannel(sensorDataChannel, remoteObject);
198 FinishTrace(HITRACE_TAG_SENSORS);
199 return ret;
200 }
201
DestroyDataChannel()202 int32_t SensorServiceClient::DestroyDataChannel()
203 {
204 CALL_LOG_ENTER;
205 int32_t ret = InitServiceClient();
206 if (ret != ERR_OK) {
207 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
208 return ret;
209 }
210 std::lock_guard<std::mutex> clientLock(clientMutex_);
211 CHKPR(sensorServer_, ERROR);
212 StartTrace(HITRACE_TAG_SENSORS, "DestroyDataChannel");
213 CHKPR(sensorClientStub_, INVALID_POINTER);
214 auto remoteObject = sensorClientStub_->AsObject();
215 CHKPR(remoteObject, INVALID_POINTER);
216 ret = sensorServer_->DestroySensorChannel(remoteObject);
217 FinishTrace(HITRACE_TAG_SENSORS);
218 return ret;
219 }
220
ReenableSensor()221 void SensorServiceClient::ReenableSensor()
222 {
223 CALL_LOG_ENTER;
224 std::lock_guard<std::mutex> mapLock(mapMutex_);
225 for (const auto &it : sensorInfoMap_) {
226 std::lock_guard<std::mutex> clientLock(clientMutex_);
227 if (sensorServer_ != nullptr) {
228 sensorServer_->EnableSensor(it.first, it.second.GetSamplingPeriodNs(), it.second.GetMaxReportDelayNs());
229 }
230 }
231 if (!isConnected_) {
232 SEN_HILOGD("Previous socket channel status is false, not need retry creat socket channel");
233 return;
234 }
235 Disconnect();
236 CreateSocketChannel();
237 }
238
ProcessDeathObserver(const wptr<IRemoteObject> & object)239 void SensorServiceClient::ProcessDeathObserver(const wptr<IRemoteObject> &object)
240 {
241 CALL_LOG_ENTER;
242 {
243 std::lock_guard<std::mutex> channelLock(channelMutex_);
244 if (dataChannel_ == nullptr) {
245 SEN_HILOGI("dataChannel_ is nullptr");
246 {
247 std::lock_guard<std::mutex> clientLock(clientMutex_);
248 sensorServer_ = nullptr;
249 }
250 if (InitServiceClient() != ERR_OK) {
251 SEN_HILOGE("InitServiceClient failed");
252 return;
253 }
254 } else {
255 SEN_HILOGI("dataChannel_ is not nullptr");
256 dataChannel_->DestroySensorDataChannel();
257 dataChannel_->RestoreSensorDataChannel();
258 {
259 std::lock_guard<std::mutex> clientLock(clientMutex_);
260 sensorServer_ = nullptr;
261 }
262 if (InitServiceClient() != ERR_OK) {
263 SEN_HILOGE("InitServiceClient failed");
264 dataChannel_->DestroySensorDataChannel();
265 SENSOR_AGENT_IMPL->SetIsChannelCreated(false);
266 return;
267 }
268 std::lock_guard<std::mutex> clientLock(clientMutex_);
269 if (sensorServer_ != nullptr && sensorClientStub_ != nullptr) {
270 auto remoteObject = sensorClientStub_->AsObject();
271 if (remoteObject != nullptr) {
272 sensorServer_->TransferDataChannel(dataChannel_, remoteObject);
273 }
274 }
275 }
276 }
277 ReenableSensor();
278 }
279
UpdateSensorInfoMap(int32_t sensorId,int64_t samplingPeriod,int64_t maxReportDelay)280 void SensorServiceClient::UpdateSensorInfoMap(int32_t sensorId, int64_t samplingPeriod, int64_t maxReportDelay)
281 {
282 CALL_LOG_ENTER;
283 SensorBasicInfo sensorInfo;
284 sensorInfo.SetSamplingPeriodNs(samplingPeriod);
285 sensorInfo.SetMaxReportDelayNs(maxReportDelay);
286 sensorInfo.SetSensorState(true);
287 std::lock_guard<std::mutex> mapLock(mapMutex_);
288 sensorInfoMap_[sensorId] = sensorInfo;
289 return;
290 }
291
DeleteSensorInfoItem(int32_t sensorId)292 void SensorServiceClient::DeleteSensorInfoItem(int32_t sensorId)
293 {
294 CALL_LOG_ENTER;
295 std::lock_guard<std::mutex> mapLock(mapMutex_);
296 auto it = sensorInfoMap_.find(sensorId);
297 if (it != sensorInfoMap_.end()) {
298 sensorInfoMap_.erase(it);
299 }
300 return;
301 }
302
SuspendSensors(int32_t pid)303 int32_t SensorServiceClient::SuspendSensors(int32_t pid)
304 {
305 CALL_LOG_ENTER;
306 int32_t ret = InitServiceClient();
307 if (ret != ERR_OK) {
308 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
309 return ret;
310 }
311 std::lock_guard<std::mutex> clientLock(clientMutex_);
312 CHKPR(sensorServer_, ERROR);
313 StartTrace(HITRACE_TAG_SENSORS, "SuspendSensors");
314 ret = sensorServer_->SuspendSensors(pid);
315 FinishTrace(HITRACE_TAG_SENSORS);
316 return ret;
317 }
318
ResumeSensors(int32_t pid)319 int32_t SensorServiceClient::ResumeSensors(int32_t pid)
320 {
321 CALL_LOG_ENTER;
322 int32_t ret = InitServiceClient();
323 if (ret != ERR_OK) {
324 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
325 return ret;
326 }
327 std::lock_guard<std::mutex> clientLock(clientMutex_);
328 CHKPR(sensorServer_, ERROR);
329 StartTrace(HITRACE_TAG_SENSORS, "ResumeSensors");
330 ret = sensorServer_->ResumeSensors(pid);
331 FinishTrace(HITRACE_TAG_SENSORS);
332 return ret;
333 }
334
GetActiveInfoList(int32_t pid,std::vector<ActiveInfo> & activeInfoList)335 int32_t SensorServiceClient::GetActiveInfoList(int32_t pid, std::vector<ActiveInfo> &activeInfoList)
336 {
337 CALL_LOG_ENTER;
338 int32_t ret = InitServiceClient();
339 if (ret != ERR_OK) {
340 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
341 return ret;
342 }
343 std::lock_guard<std::mutex> clientLock(clientMutex_);
344 CHKPR(sensorServer_, ERROR);
345 StartTrace(HITRACE_TAG_SENSORS, "GetActiveInfoList");
346 ret = sensorServer_->GetActiveInfoList(pid, activeInfoList);
347 FinishTrace(HITRACE_TAG_SENSORS);
348 return ret;
349 }
350
Register(SensorActiveInfoCB callback,sptr<SensorDataChannel> sensorDataChannel)351 int32_t SensorServiceClient::Register(SensorActiveInfoCB callback, sptr<SensorDataChannel> sensorDataChannel)
352 {
353 CALL_LOG_ENTER;
354 if (!isConnected_) {
355 CHKPR(sensorDataChannel, INVALID_POINTER);
356 {
357 std::lock_guard<std::mutex> channelLock(channelMutex_);
358 dataChannel_ = sensorDataChannel;
359 }
360 int32_t ret = CreateSocketChannel();
361 if (ret != ERR_OK) {
362 SEN_HILOGE("Register sensor active info callback failed, ret:%{public}d", ret);
363 return ret;
364 }
365 }
366 std::lock_guard<std::mutex> activeInfoCBLock(activeInfoCBMutex_);
367 activeInfoCBSet_.insert(callback);
368 return ERR_OK;
369 }
370
Unregister(SensorActiveInfoCB callback)371 int32_t SensorServiceClient::Unregister(SensorActiveInfoCB callback)
372 {
373 CALL_LOG_ENTER;
374 {
375 std::lock_guard<std::mutex> activeInfoCBLock(activeInfoCBMutex_);
376 activeInfoCBSet_.erase(callback);
377 if (!activeInfoCBSet_.empty()) {
378 return ERR_OK;
379 }
380 }
381 int32_t ret = InitServiceClient();
382 if (ret != ERR_OK) {
383 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
384 return ret;
385 }
386 std::lock_guard<std::mutex> clientLock(clientMutex_);
387 CHKPR(sensorServer_, ERROR);
388 StartTrace(HITRACE_TAG_SENSORS, "DisableActiveInfoCB");
389 ret = sensorServer_->DisableActiveInfoCB();
390 FinishTrace(HITRACE_TAG_SENSORS);
391 if (ret != ERR_OK) {
392 SEN_HILOGE("Disable active info callback failed, ret:%{public}d", ret);
393 return ret;
394 }
395 Disconnect();
396 StartTrace(HITRACE_TAG_SENSORS, "DestroySocketChannel");
397 CHKPR(sensorClientStub_, INVALID_POINTER);
398 auto remoteObject = sensorClientStub_->AsObject();
399 CHKPR(remoteObject, INVALID_POINTER);
400 ret = sensorServer_->DestroySocketChannel(remoteObject);
401 FinishTrace(HITRACE_TAG_SENSORS);
402 if (ret != ERR_OK) {
403 SEN_HILOGE("Destroy socket channel failed, ret:%{public}d", ret);
404 return ret;
405 }
406 isConnected_ = false;
407 return ERR_OK;
408 }
409
ResetSensors()410 int32_t SensorServiceClient::ResetSensors()
411 {
412 CALL_LOG_ENTER;
413 int32_t ret = InitServiceClient();
414 if (ret != ERR_OK) {
415 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
416 return ret;
417 }
418 std::lock_guard<std::mutex> clientLock(clientMutex_);
419 CHKPR(sensorServer_, ERROR);
420 StartTrace(HITRACE_TAG_SENSORS, "ResetSensors");
421 ret = sensorServer_->ResetSensors();
422 FinishTrace(HITRACE_TAG_SENSORS);
423 return ret;
424 }
425
ReceiveMessage(const char * buf,size_t size)426 void SensorServiceClient::ReceiveMessage(const char *buf, size_t size)
427 {
428 CHKPV(buf);
429 if (size == 0 || size > MAX_PACKET_BUF_SIZE) {
430 SEN_HILOGE("Invalid input param size. size:%{public}zu", size);
431 return;
432 }
433 if (!circBuf_.Write(buf, size)) {
434 SEN_HILOGE("Write data failed. size:%{public}zu", size);
435 }
436 #ifdef OHOS_BUILD_ENABLE_RUST
437 ReadClientPackets(circBuf_.streamBufferPtr_.get(), this, OnPacket);
438 #else
439 OnReadPackets(circBuf_, [this] (NetPacket &pkt) { this->HandleNetPacke(pkt); });
440 #endif // OHOS_BUILD_ENABLE_RUST
441 }
442
HandleNetPacke(NetPacket & pkt)443 void SensorServiceClient::HandleNetPacke(NetPacket &pkt)
444 {
445 auto id = pkt.GetMsgId();
446 if (id != MessageId::ACTIVE_INFO) {
447 SEN_HILOGE("NetPacke message id is not ACTIVE_INFO");
448 return;
449 }
450 SensorActiveInfo sensorActiveInfo;
451 pkt >> sensorActiveInfo.pid >> sensorActiveInfo.sensorId >> sensorActiveInfo.samplingPeriodNs >>
452 sensorActiveInfo.maxReportDelayNs;
453 #ifdef OHOS_BUILD_ENABLE_RUST
454 if (StreamBufferChkRWError(pkt.streamBufferPtr_.get())) {
455 #else
456 if (pkt.ChkRWError()) {
457 #endif // OHOS_BUILD_ENABLE_RUST
458 SEN_HILOGE("Packet read type failed");
459 return;
460 }
461 std::lock_guard<std::mutex> activeInfoCBLock(activeInfoCBMutex_);
462 for (auto callback : activeInfoCBSet_) {
463 if (callback != nullptr) {
464 callback(sensorActiveInfo);
465 }
466 }
467 }
468
469 void SensorServiceClient::Disconnect()
470 {
471 CALL_LOG_ENTER;
472 int32_t fd = GetFd();
473 if (fd < 0) {
474 return;
475 }
476 {
477 std::lock_guard<std::mutex> channelLock(channelMutex_);
478 if (dataChannel_ != nullptr) {
479 int32_t ret = dataChannel_->DelFdListener(fd);
480 if (ret != ERR_OK) {
481 SEN_HILOGE("Delete fd listener failed, fd:%{public}d, ret:%{public}d", fd, ret);
482 }
483 }
484 }
485 Close();
486 }
487
488 int32_t SensorServiceClient::CreateSocketChannel()
489 {
490 CALL_LOG_ENTER;
491 int32_t ret = InitServiceClient();
492 if (ret != ERR_OK) {
493 SEN_HILOGE("InitServiceClient failed, ret:%{public}d", ret);
494 return ret;
495 }
496 std::lock_guard<std::mutex> clientLock(clientMutex_);
497 CHKPR(sensorServer_, ERROR);
498 int32_t clientFd = -1;
499 StartTrace(HITRACE_TAG_SENSORS, "CreateSocketChannel");
500 CHKPR(sensorClientStub_, INVALID_POINTER);
501 auto remoteObject = sensorClientStub_->AsObject();
502 CHKPR(remoteObject, INVALID_POINTER);
503 ret = sensorServer_->CreateSocketChannel(remoteObject, clientFd);
504 FinishTrace(HITRACE_TAG_SENSORS);
505 if (ret != ERR_OK || clientFd < 0) {
506 Close();
507 SEN_HILOGE("Create socket channel failed, ret:%{public}d", ret);
508 return ret;
509 }
510 #ifdef OHOS_BUILD_ENABLE_RUST
511 StreamSocketSetFd(streamSocketPtr_.get(), clientFd);
512 #else
513 fd_ = clientFd;
514 #endif // OHOS_BUILD_ENABLE_RUST
515 {
516 std::lock_guard<std::mutex> channelLock(channelMutex_);
517 if (dataChannel_->AddFdListener(GetFd(),
518 [this] (const char *buf, size_t size) { this->ReceiveMessage(buf, size); },
519 [this] { this->Disconnect(); })!= ERR_OK) {
520 Close();
521 SEN_HILOGE("Add fd listener failed, fd:%{public}d", GetFd());
522 return ERROR;
523 }
524 }
525 StartTrace(HITRACE_TAG_SENSORS, "EnableActiveInfoCB");
526 ret = sensorServer_->EnableActiveInfoCB();
527 FinishTrace(HITRACE_TAG_SENSORS);
528 if (ret != ERR_OK) {
529 SEN_HILOGE("Enable active info callback failed, ret:%{public}d", ret);
530 Disconnect();
531 return ret;
532 }
533 isConnected_ = true;
534 return ERR_OK;
535 }
536 } // namespace Sensors
537 } // namespace OHOS
538