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