From fd7a1fc30d43f517b57e9759d4bca65342ece4bd Mon Sep 17 00:00:00 2001 From: majiajun <864428661@qq.com> Date: Mon, 20 Dec 2021 22:54:21 -0800 Subject: [PATCH] sync code to master Signed-off-by: majiajun <864428661@qq.com> Change-Id: I7593eafe27246f0e9bc7e038a3232c91029478a9 --- OAT.xml | 3 + etc/profile/BUILD.gn | 21 + etc/profile/distributedsched_trust.xml | 19 + ohos.build | 7 +- services/dtbschedmgr/BUILD.gn | 12 +- .../ability_connection_wrapper_proxy.h | 41 + .../include/ability_connection_wrapper_stub.h | 6 - .../adapter/adapter_constant.h} | 59 +- .../include/adapter/dnetwork_adapter.h | 8 +- services/dtbschedmgr/include/caller_info.h | 5 + .../include/distributed_sched_ability_shell.h | 52 - .../include/distributed_sched_adapter.h | 7 +- .../include/distributed_sched_interface.h | 52 +- .../include/distributed_sched_proxy.h | 34 +- .../include/distributed_sched_service.h | 37 +- .../include/distributed_sched_stub.h | 25 +- .../include/dtbschedmgr_device_info_storage.h | 47 +- .../dtbschedmgr/include/dtbschedmgr_log.h | 75 +- .../distributed_data_change_listener.h} | 66 +- .../mission/distributed_data_storage.h | 122 ++ .../distributed_sched_mission_manager.h | 184 +++ .../include/mission/mission_changed_notify.h | 38 + .../include/mission/mission_constant.h | 29 + .../include/mission/mission_info.h | 65 + .../include/mission/mission_info_converter.h | 38 + .../dtbschedmgr/include/mission/snapshot.h | 106 ++ services/dtbschedmgr/include/parcel_helper.h | 0 .../src/ability_connection_wrapper_proxy.cpp | 64 + .../src/ability_connection_wrapper_stub.cpp | 36 +- .../src/adapter/dnetwork_adapter.cpp | 21 +- .../src/bundle/bundle_manager_internal.cpp | 12 +- .../src/connect_death_recipient.cpp | 5 +- .../src/deviceManager/dms_device_info.cpp | 3 + .../src/distributed_device_node_listener.cpp | 7 +- .../src/distributed_sched_ability_shell.cpp | 152 -- .../src/distributed_sched_adapter.cpp | 61 +- .../src/distributed_sched_continuation.cpp | 23 +- .../src/distributed_sched_dumper.cpp | 1 + .../src/distributed_sched_permission.cpp | 11 +- .../src/distributed_sched_proxy.cpp | 323 +++- .../src/distributed_sched_service.cpp | 206 ++- .../src/distributed_sched_stub.cpp | 399 ++++- .../src/dtbschedmgr_device_info_storage.cpp | 182 ++- .../distributed_data_change_listener.cpp | 110 ++ .../src/mission/distributed_data_storage.cpp | 182 +++ .../distributed_sched_mission_manager.cpp | 1321 +++++++++++++++++ .../src/mission/mission_changed_notify.cpp | 135 ++ .../dtbschedmgr/src/mission/mission_info.cpp | 194 +++ .../src/mission/mission_info_converter.cpp | 71 + services/dtbschedmgr/src/mission/snapshot.cpp | 219 +++ services/dtbschedmgr/test/BUILD.gn | 27 +- .../test/etsDmsDemo/dmsDemo/build.gradle | 34 + .../etsDmsDemo/dmsDemo/entry/build.gradle | 22 + .../dmsDemo/entry/src/main/config.json | 102 ++ .../entry/src/main/ets/LocalAbility/app.ets | 23 + .../src/main/ets/LocalAbility/pages/index.ets | 28 + .../entry/src/main/ets/RemoteAbility/app.ets | 38 + .../main/ets/RemoteAbility/pages/index.ets | 543 +++++++ .../src/main/ets/ServiceAbility/service.ts | 69 + .../src/main/ets/model/RemoteDeviceModel.ets | 184 +++ .../main/resources/base/element/string.json | 20 + .../src/main/resources/base/media/icon.png | 0 .../test/etsDmsDemo/dmsDemo/settings.gradle | 1 + .../test/jsDmsDemo/dmsDemo/build.gradle | 34 + .../test/jsDmsDemo/dmsDemo/entry/build.gradle | 22 + .../dmsDemo/entry/src/main/config.json | 94 ++ .../entry/src/main/js/LocalAbility/app.js | 23 + .../src/main/js/LocalAbility/i18n/en-US.json | 11 + .../src/main/js/LocalAbility/i18n/zh-CN.json | 11 + .../js/LocalAbility/pages/index/index.css | 39 + .../js/LocalAbility/pages/index/index.hml | 20 + .../main/js/LocalAbility/pages/index/index.js | 23 + .../entry/src/main/js/RemoteAbility/app.js | 38 + .../src/main/js/RemoteAbility/i18n/en-US.json | 11 + .../src/main/js/RemoteAbility/i18n/zh-CN.json | 11 + .../js/RemoteAbility/pages/index/index.css | 163 ++ .../js/RemoteAbility/pages/index/index.hml | 78 + .../js/RemoteAbility/pages/index/index.js | 438 ++++++ .../src/main/js/ServiceAbility/service.js | 69 + .../src/main/js/model/RemoteDeviceModel.js | 184 +++ .../main/resources/base/element/string.json | 20 + .../src/main/resources/base/media/icon.png | 0 .../test/jsDmsDemo/dmsDemo/settings.gradle | 1 + .../distributed_sched_ability_shell_test.cpp | 571 ------- .../distributed_sched_connect_test.cpp | 272 +++- .../distributed_sched_continuation_test.cpp | 13 +- .../distributed_sched_service_test.cpp | 62 +- .../mission/dms_mission_manager_test.cpp | 319 ++++ .../mission/dms_mission_manager_test.h | 39 + .../test/unittest/mock_distributed_sched.cpp | 93 +- .../test/unittest/mock_distributed_sched.h | 32 +- 91 files changed, 7377 insertions(+), 1301 deletions(-) create mode 100644 etc/profile/BUILD.gn create mode 100644 etc/profile/distributedsched_trust.xml mode change 100755 => 100644 ohos.build create mode 100644 services/dtbschedmgr/include/ability_connection_wrapper_proxy.h mode change 100755 => 100644 services/dtbschedmgr/include/ability_connection_wrapper_stub.h rename services/dtbschedmgr/{src/continuation_callback_death_recipient.cpp => include/adapter/adapter_constant.h} (59%) mode change 100755 => 100644 mode change 100755 => 100644 services/dtbschedmgr/include/adapter/dnetwork_adapter.h delete mode 100755 services/dtbschedmgr/include/distributed_sched_ability_shell.h mode change 100755 => 100644 services/dtbschedmgr/include/distributed_sched_adapter.h mode change 100755 => 100644 services/dtbschedmgr/include/dtbschedmgr_device_info_storage.h rename services/dtbschedmgr/include/{continuation_callback_death_recipient.h => mission/distributed_data_change_listener.h} (54%) mode change 100755 => 100644 create mode 100644 services/dtbschedmgr/include/mission/distributed_data_storage.h create mode 100644 services/dtbschedmgr/include/mission/distributed_sched_mission_manager.h create mode 100644 services/dtbschedmgr/include/mission/mission_changed_notify.h create mode 100644 services/dtbschedmgr/include/mission/mission_constant.h create mode 100644 services/dtbschedmgr/include/mission/mission_info.h create mode 100644 services/dtbschedmgr/include/mission/mission_info_converter.h create mode 100644 services/dtbschedmgr/include/mission/snapshot.h mode change 100755 => 100644 services/dtbschedmgr/include/parcel_helper.h create mode 100644 services/dtbschedmgr/src/ability_connection_wrapper_proxy.cpp mode change 100755 => 100644 services/dtbschedmgr/src/ability_connection_wrapper_stub.cpp mode change 100755 => 100644 services/dtbschedmgr/src/adapter/dnetwork_adapter.cpp mode change 100755 => 100644 services/dtbschedmgr/src/bundle/bundle_manager_internal.cpp mode change 100755 => 100644 services/dtbschedmgr/src/connect_death_recipient.cpp mode change 100755 => 100644 services/dtbschedmgr/src/deviceManager/dms_device_info.cpp mode change 100755 => 100644 services/dtbschedmgr/src/distributed_device_node_listener.cpp delete mode 100755 services/dtbschedmgr/src/distributed_sched_ability_shell.cpp mode change 100755 => 100644 services/dtbschedmgr/src/distributed_sched_adapter.cpp mode change 100755 => 100644 services/dtbschedmgr/src/distributed_sched_continuation.cpp mode change 100755 => 100644 services/dtbschedmgr/src/distributed_sched_dumper.cpp mode change 100755 => 100644 services/dtbschedmgr/src/distributed_sched_permission.cpp mode change 100755 => 100644 services/dtbschedmgr/src/dtbschedmgr_device_info_storage.cpp create mode 100644 services/dtbschedmgr/src/mission/distributed_data_change_listener.cpp create mode 100644 services/dtbschedmgr/src/mission/distributed_data_storage.cpp create mode 100644 services/dtbschedmgr/src/mission/distributed_sched_mission_manager.cpp create mode 100644 services/dtbschedmgr/src/mission/mission_changed_notify.cpp create mode 100644 services/dtbschedmgr/src/mission/mission_info.cpp create mode 100644 services/dtbschedmgr/src/mission/mission_info_converter.cpp create mode 100644 services/dtbschedmgr/src/mission/snapshot.cpp mode change 100755 => 100644 services/dtbschedmgr/test/BUILD.gn create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/build.gradle create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/build.gradle create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/config.json create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/app.ets create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/pages/index.ets create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/app.ets create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/pages/index.ets create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/ServiceAbility/service.ts create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/model/RemoteDeviceModel.ets create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/resources/base/media/icon.png create mode 100644 services/dtbschedmgr/test/etsDmsDemo/dmsDemo/settings.gradle create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/build.gradle create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/build.gradle create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/config.json create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/app.js create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/en-US.json create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/zh-CN.json create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.css create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.hml create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.js create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/app.js create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/en-US.json create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/zh-CN.json create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.css create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.hml create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.js create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/ServiceAbility/service.js create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/model/RemoteDeviceModel.js create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/resources/base/media/icon.png create mode 100644 services/dtbschedmgr/test/jsDmsDemo/dmsDemo/settings.gradle delete mode 100755 services/dtbschedmgr/test/unittest/distributed_sched_ability_shell_test.cpp mode change 100755 => 100644 services/dtbschedmgr/test/unittest/distributed_sched_connect_test.cpp mode change 100755 => 100644 services/dtbschedmgr/test/unittest/distributed_sched_continuation_test.cpp create mode 100644 services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.cpp create mode 100644 services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.h mode change 100755 => 100644 services/dtbschedmgr/test/unittest/mock_distributed_sched.cpp mode change 100755 => 100644 services/dtbschedmgr/test/unittest/mock_distributed_sched.h diff --git a/OAT.xml b/OAT.xml index b16430c7..a0f4a604 100644 --- a/OAT.xml +++ b/OAT.xml @@ -58,6 +58,9 @@ Note:If the text contains special characters, please escape them according to th + + + \ No newline at end of file diff --git a/etc/profile/BUILD.gn b/etc/profile/BUILD.gn new file mode 100644 index 00000000..a68f76b4 --- /dev/null +++ b/etc/profile/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_prebuilt_etc("distributedsched_trust") { + source = "distributedsched_trust.xml" + module_install_dir = "profile" + part_name = "dmsfwk_standard" + subsystem_name = "distributedschedule" +} diff --git a/etc/profile/distributedsched_trust.xml b/etc/profile/distributedsched_trust.xml new file mode 100644 index 00000000..4e151d3b --- /dev/null +++ b/etc/profile/distributedsched_trust.xml @@ -0,0 +1,19 @@ + + + + distributedsched + 1401 + 6001 + diff --git a/ohos.build b/ohos.build old mode 100755 new mode 100644 index f41cc29a..a0e8824f --- a/ohos.build +++ b/ohos.build @@ -7,7 +7,11 @@ "header": { "header_base": "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "header_files": [ - "uri.h" + "distributed_sched_interface.h", + "distributed_sched_proxy.h", + "caller_info.h", + "uri.h", + "mission/mission_info.h" ] }, "name": "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri" @@ -15,6 +19,7 @@ ], "module_list": [ "//foundation/distributedschedule/dmsfwk/etc/init:etc", + "//foundation/distributedschedule/dmsfwk/etc/profile:distributedsched_trust", "//foundation/distributedschedule/dmsfwk/sa_profile:dms_sa_profile", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr" ], diff --git a/services/dtbschedmgr/BUILD.gn b/services/dtbschedmgr/BUILD.gn index 0a19b781..8552207b 100644 --- a/services/dtbschedmgr/BUILD.gn +++ b/services/dtbschedmgr/BUILD.gn @@ -30,14 +30,13 @@ config("distributed_sched_config") { ohos_shared_library("distributedschedsvr") { install_enable = true sources = [ + "src/ability_connection_wrapper_proxy.cpp", "src/ability_connection_wrapper_stub.cpp", "src/adapter/dnetwork_adapter.cpp", "src/bundle/bundle_manager_internal.cpp", "src/connect_death_recipient.cpp", - "src/continuation_callback_death_recipient.cpp", "src/deviceManager/dms_device_info.cpp", "src/distributed_device_node_listener.cpp", - "src/distributed_sched_ability_shell.cpp", "src/distributed_sched_adapter.cpp", "src/distributed_sched_continuation.cpp", "src/distributed_sched_dumper.cpp", @@ -46,6 +45,13 @@ ohos_shared_library("distributedschedsvr") { "src/distributed_sched_service.cpp", "src/distributed_sched_stub.cpp", "src/dtbschedmgr_device_info_storage.cpp", + "src/mission/distributed_data_change_listener.cpp", + "src/mission/distributed_data_storage.cpp", + "src/mission/distributed_sched_mission_manager.cpp", + "src/mission/mission_changed_notify.cpp", + "src/mission/mission_info.cpp", + "src/mission/mission_info_converter.cpp", + "src/mission/snapshot.cpp", ] configs = [ ":distributed_sched_config" ] @@ -60,8 +66,10 @@ ohos_shared_library("distributedschedsvr") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//utils/native/base:utils", ] diff --git a/services/dtbschedmgr/include/ability_connection_wrapper_proxy.h b/services/dtbschedmgr/include/ability_connection_wrapper_proxy.h new file mode 100644 index 00000000..e36091ea --- /dev/null +++ b/services/dtbschedmgr/include/ability_connection_wrapper_proxy.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_ABILITY_CONNECTION_WRAPPER_PROXY_H +#define OHOS_DISTRIBUTED_ABILITY_CONNECTION_WRAPPER_PROXY_H + +#include "ability_connect_callback_interface.h" + +#include "iremote_object.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace DistributedSchedule { +class AbilityConnectionWrapperProxy : public IRemoteProxy { +public: + explicit AbilityConnectionWrapperProxy(const sptr& impl) + : IRemoteProxy(impl) {} + virtual ~AbilityConnectionWrapperProxy() = default; + + void OnAbilityConnectDone(const AppExecFwk::ElementName& element, const sptr& remoteObject, + int32_t resultCode) override; + void OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, int32_t resultCode) override; + +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DistributedSchedule +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_ABILITY_CONNECTION_WRAPPER_PROXY_H \ No newline at end of file diff --git a/services/dtbschedmgr/include/ability_connection_wrapper_stub.h b/services/dtbschedmgr/include/ability_connection_wrapper_stub.h old mode 100755 new mode 100644 index 625cb3cf..23f1a075 --- a/services/dtbschedmgr/include/ability_connection_wrapper_stub.h +++ b/services/dtbschedmgr/include/ability_connection_wrapper_stub.h @@ -26,11 +26,6 @@ namespace OHOS { namespace DistributedSchedule { class AbilityConnectionWrapperStub : public IRemoteStub { public: - enum { - ON_ABILITY_CONNECT_DONE = 1, - ON_ABILITY_DISCONNECT_DONE = 2 - }; - explicit AbilityConnectionWrapperStub(sptr connection); virtual ~AbilityConnectionWrapperStub() = default; @@ -43,7 +38,6 @@ public: private: DISALLOW_COPY_AND_MOVE(AbilityConnectionWrapperStub); - sptr distributedConnection_; }; } // namespace DistributedSchedule diff --git a/services/dtbschedmgr/src/continuation_callback_death_recipient.cpp b/services/dtbschedmgr/include/adapter/adapter_constant.h old mode 100755 new mode 100644 similarity index 59% rename from services/dtbschedmgr/src/continuation_callback_death_recipient.cpp rename to services/dtbschedmgr/include/adapter/adapter_constant.h index 944fe6b1..5193b701 --- a/services/dtbschedmgr/src/continuation_callback_death_recipient.cpp +++ b/services/dtbschedmgr/include/adapter/adapter_constant.h @@ -1,29 +1,30 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "continuation_callback_death_recipient.h" -#include "distributed_sched_ability_shell.h" -#include "dtbschedmgr_log.h" -#include "iremote_proxy.h" - -namespace OHOS { -namespace DistributedSchedule { -void ContinuationCallbackDeathRecipient::OnRemoteDied(const wptr& remote) -{ - HILOGI("%s called", __func__); - DistributedSchedAbilityShell::GetInstance().RemoveContinuationCallback(remote.promote()); -} -} // namespace DistributedSchedule -} // namespace OHOS \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DMS_DFX_CONSTANT_H +#define OHOS_DISTRIBUTED_DMS_DFX_CONSTANT_H + +namespace OHOS { +namespace DistributedSchedule { +namespace Constants { +namespace Adapter { +constexpr int32_t PARCELABLE_FLAG = 1; +constexpr int32_t VALUE_NULL = -1; +constexpr int32_t VALUE_OBJECT = 1; +} // Adapter +} // Constants +} // DistributedSchedule +} // OHOS +#endif diff --git a/services/dtbschedmgr/include/adapter/dnetwork_adapter.h b/services/dtbschedmgr/include/adapter/dnetwork_adapter.h old mode 100755 new mode 100644 index deb42afd..e1bc76aa --- a/services/dtbschedmgr/include/adapter/dnetwork_adapter.h +++ b/services/dtbschedmgr/include/adapter/dnetwork_adapter.h @@ -38,7 +38,7 @@ public: virtual void OnDeviceOnline(const NodeBasicInfo* nodeBasicInfo) = 0; virtual void OnDeviceOffline(const NodeBasicInfo* nodeBasicInfo) = 0; - virtual void OnDeviceInfoChanged(const std::string& nodeId, DeviceInfoType type) = 0; + virtual void OnDeviceInfoChanged(const std::string& networkId, DeviceInfoType type) = 0; }; class DnetworkAdapter { @@ -49,8 +49,8 @@ public: void Init(); bool AddDeviceChangeListener(const std::shared_ptr& listener); void RemoveDeviceChangeListener(const std::shared_ptr& listener); - std::string GetUdidByNodeId(const std::string& nodeId); - std::string GetUuidByNodeId(const std::string& nodeId); + std::string GetUdidByNetworkId(const std::string& networkId); + std::string GetUuidByNetworkId(const std::string& networkId); std::shared_ptr GetLocalBasicInfo(); static std::string AnonymizeDeviceId(const std::string& deviceId); @@ -59,7 +59,7 @@ public: private: DISALLOW_COPY_AND_MOVE(DnetworkAdapter); - std::string GetUuidOrUdidByNodeId(const std::string& nodeId, NodeDeivceInfoKey keyType); + std::string GetUuidOrUdidByNetworkId(const std::string& networkId, NodeDeivceInfoKey keyType); static void OnNodeOnline(NodeBasicInfo* info); static void OnNodeOffline(NodeBasicInfo* info); static void OnNodeBasicInfoChanged(NodeBasicInfoType type, NodeBasicInfo* info); diff --git a/services/dtbschedmgr/include/caller_info.h b/services/dtbschedmgr/include/caller_info.h index 3c25f966..fc28cf97 100644 --- a/services/dtbschedmgr/include/caller_info.h +++ b/services/dtbschedmgr/include/caller_info.h @@ -23,6 +23,10 @@ enum { CALLER_TYPE_HARMONY = 1, }; +enum { + VERSION_BASE = 200, // begin for 200 and step for 200 + VERSION = VERSION_BASE, +}; struct CallerInfo { int32_t uid = -1; int32_t pid = -1; @@ -31,6 +35,7 @@ struct CallerInfo { int32_t duid = -1; std::string callerAppId; std::vector bundleNames; + int32_t dmsVersion = -1; }; } // namespace DistributedSchedule } // namespace OHOS diff --git a/services/dtbschedmgr/include/distributed_sched_ability_shell.h b/services/dtbschedmgr/include/distributed_sched_ability_shell.h deleted file mode 100755 index 79ee0dc5..00000000 --- a/services/dtbschedmgr/include/distributed_sched_ability_shell.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DISTRIBUTED_SCHED_ABILITY_SHELL_H -#define OHOS_DISTRIBUTED_SCHED_ABILITY_SHELL_H - -#include -#include -#include - -#include "continuation_callback_death_recipient.h" -#include "iremote_object.h" -#include "ohos/aafwk/content/want.h" -#include "single_instance.h" - -namespace OHOS { -namespace DistributedSchedule { -class DistributedSchedAbilityShell { - DECLARE_SINGLE_INSTANCE_BASE(DistributedSchedAbilityShell); - -public: - int32_t RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback); - int32_t UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback); - sptr GetContinuationCallback(const sptr& abilityToken); - int32_t ScheduleCompleteContinuation(const sptr& abilityToken, int32_t isSuccess); - void RemoveContinuationCallback(const sptr& continuationCallback); - -private: - DistributedSchedAbilityShell(); - ~DistributedSchedAbilityShell() = default; - - std::map, std::list>> regAbilityMap_; - std::mutex regAbilityLock_; - sptr death_; -}; -} // namespace DistributedSchedule -} // namespace OHOS -#endif // OHOS_DISTRIBUTED_SCHED_ABILITY_SHELL_H \ No newline at end of file diff --git a/services/dtbschedmgr/include/distributed_sched_adapter.h b/services/dtbschedmgr/include/distributed_sched_adapter.h old mode 100755 new mode 100644 index 43ae6b97..06f3ad7b --- a/services/dtbschedmgr/include/distributed_sched_adapter.h +++ b/services/dtbschedmgr/include/distributed_sched_adapter.h @@ -22,6 +22,7 @@ #include "event_handler.h" #include "if_system_ability_manager.h" #include "iremote_object.h" +#include "mission/mission_info.h" #include "single_instance.h" #include "uri.h" @@ -42,8 +43,12 @@ public: bool QueryAbilityInfo(const OHOS::AAFwk::Want& want, AppExecFwk::AbilityInfo& abilityInfo); void ProcessConnectDied(const sptr& connect); int32_t GetBundleNameListFromBms(int32_t uid, std::vector& u16BundleNameList); + int32_t GetLocalMissionInfos(int32_t numMissions, std::vector& missionInfos); int32_t GetBundleNameListFromBms(int32_t uid, std::vector& bundleNameList); - + bool AllowMissionUid(int32_t uid); + int32_t RegisterMissionChange(bool willRegister); + int32_t GetOsdSwitch(); + void OnOsdEventOccur(int32_t flag); private: void ProcessDeviceOffline(const std::string& deviceId); diff --git a/services/dtbschedmgr/include/distributed_sched_interface.h b/services/dtbschedmgr/include/distributed_sched_interface.h index 50eca016..e957a63a 100644 --- a/services/dtbschedmgr/include/distributed_sched_interface.h +++ b/services/dtbschedmgr/include/distributed_sched_interface.h @@ -16,9 +16,11 @@ #ifndef OHOS_DISTRIBUTED_SCHED_INTERFACE_H #define OHOS_DISTRIBUTED_SCHED_INTERFACE_H +#include #include "ability_info.h" #include "caller_info.h" #include "iremote_broker.h" +#include "mission/mission_info.h" #include "ohos/aafwk/content/want.h" namespace OHOS { @@ -35,21 +37,16 @@ public: std::vector groupIdList; }; - virtual int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) = 0; + virtual int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) = 0; virtual int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const AccountInfo& accountInfo) = 0; - virtual int32_t StartContinuation(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr& abilityToken) = 0; + virtual int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr& abilityToken, + int32_t callerUid) = 0; virtual void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) = 0; virtual int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) = 0; - virtual int32_t RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) = 0; - virtual int32_t UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) = 0; - virtual int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, - const sptr& connect) = 0; + virtual int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid) = 0; virtual int32_t DisconnectRemoteAbility(const sptr& connect) = 0; virtual int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, const sptr& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) = 0; @@ -57,6 +54,23 @@ public: int32_t uid, const std::string& sourceDeviceId) = 0; virtual int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) = 0; + virtual int32_t PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) = 0; + virtual int32_t RegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) = 0; + virtual int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) = 0; + virtual int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos) = 0; + virtual int32_t StoreSnapshotInfo(const std::string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) = 0; + virtual int32_t RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) = 0; + virtual int32_t NotifyMissionsChangedFromRemote(const std::vector& missionInfos, + const CallerInfo& callerInfo) = 0; + virtual int32_t CheckSupportOsd(const std::string& deviceId) = 0; + virtual void GetCachedOsdSwitch(std::vector& deviceIds, std::vector& values) = 0; + virtual int32_t GetOsdSwitchValueFromRemote() = 0; + virtual int32_t UpdateOsdSwitchValueFromRemote(int32_t switchVal, const std::string& sourceDeviceId) = 0; + virtual int32_t PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) = 0; + virtual int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) = 0; enum { START_REMOTE_ABILITY = 1, STOP_REMOTE_ABILITY = 3, @@ -74,6 +88,24 @@ public: CONTINUE_ABILITY = 16, NOTIFY_PROCESS_DIED_FROM_REMOTE = 17, GET_REMOTE_APPTHREAD = 35, + // request code for mission + GET_MISSION_INFOS = 80, + STORE_SNAPSHOT_INFO = 81, + GET_REMOTE_SNAPSHOT_INFO = 82, + REMOVE_SNAPSHOT_INFO = 83, + REGISTER_MISSION_LISTENER = 84, + UNREGISTER_MISSION_LISTENER = 85, + PREPARE_AND_SYNC_MISSIONS_FROM_REMOTE = 86, + UNREGISTER_MISSION_LISTENER_FROM_REMOTE = 87, + CHECK_SUPPORTED_OSD = 88, + CHECK_SUPPORT_OSD_FROM_REMOTE = 89, + MISSION_CHANGED = 90, + NOTIFY_MISSIONS_CHANGED_FROM_REMOTE = 91, + PREPARE_AND_SYNC_MISSIONS = 92, + TRY_OPENP2PSESSION_FROM_REMOTE = 93, + SWITCH_CHANGED = 94, + NOTIFY_SWITCH_CHANGED_FROM_REMOTE = 95, + GET_CACHED_SUPPORTED_OSD = 96, }; }; } // namespace DistributedSchedule diff --git a/services/dtbschedmgr/include/distributed_sched_proxy.h b/services/dtbschedmgr/include/distributed_sched_proxy.h index bd00ae09..4d6b6c0e 100644 --- a/services/dtbschedmgr/include/distributed_sched_proxy.h +++ b/services/dtbschedmgr/include/distributed_sched_proxy.h @@ -26,29 +26,41 @@ public: explicit DistributedSchedProxy(const sptr& impl) : IRemoteProxy(impl) {} ~DistributedSchedProxy() {} - int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, - int32_t requestCode) override; + int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) override; int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; - int32_t StartContinuation(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, - const sptr& abilityToken) override; + int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr& abilityToken, + int32_t callerUid) override; void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override; int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override; - int32_t RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) override; - int32_t UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) override; - int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, - const sptr& connect) override; + int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid) override; int32_t DisconnectRemoteAbility(const sptr& connect) override; int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, const sptr& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; int32_t DisconnectAbilityFromRemote(const sptr& connect, int32_t uid, const std::string& sourceDeviceId) override; int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) override; - + int32_t PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) override; + int32_t RegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) override; + int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) override; + int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos) override; + int32_t StoreSnapshotInfo(const std::string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) override; + int32_t RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) override; + int32_t NotifyMissionsChangedFromRemote(const std::vector& missionInfos, + const CallerInfo& callerInfo) override; + int32_t CheckSupportOsd(const std::string& deviceId) override; + void GetCachedOsdSwitch(std::vector& deviceIds, std::vector& values) override; + int32_t GetOsdSwitchValueFromRemote() override; + int32_t UpdateOsdSwitchValueFromRemote(int32_t switchVal, const std::string& sourceDeviceId) override; + int32_t PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) override; + int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) override; private: + bool CallerInfoMarshalling(const CallerInfo& callerInfo, MessageParcel& data); static inline BrokerDelegator delegator_; }; } // namespace DistributedSchedule diff --git a/services/dtbschedmgr/include/distributed_sched_service.h b/services/dtbschedmgr/include/distributed_sched_service.h index 9f9c1040..b5d44192 100644 --- a/services/dtbschedmgr/include/distributed_sched_service.h +++ b/services/dtbschedmgr/include/distributed_sched_service.h @@ -25,6 +25,7 @@ #include "distributed_sched_continuation.h" #include "iremote_object.h" #include "iremote_proxy.h" +#include "mission/mission_info.h" #include "nocopyable.h" #include "single_instance.h" #include "system_ability.h" @@ -56,34 +57,46 @@ public: ~DistributedSchedService() = default; void OnStart() override; void OnStop() override; - int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, - int32_t requestCode) override; + int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) override; int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; - int32_t StartContinuation(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, - const sptr& abilityToken) override; + int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr& abilityToken, + int32_t callerUid) override; void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override; int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override; - int32_t RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) override; - int32_t UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) override; - int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, - const sptr& connect) override; + int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid) override; int32_t DisconnectRemoteAbility(const sptr& connect) override; int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, const sptr& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; int32_t DisconnectAbilityFromRemote(const sptr& connect, int32_t uid, const std::string& sourceDeviceId) override; int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) override; + int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos) override; + int32_t StoreSnapshotInfo(const std::string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) override; + int32_t RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) override; + int32_t NotifyMissionsChangedFromRemote(const std::vector& missionInfos, + const CallerInfo& callerInfo) override; void ProcessConnectDied(const sptr& connect); void ProcessDeviceOffline(const std::string& deviceId); int32_t Dump(int32_t fd, const std::vector& args) override; void DumpConnectInfo(std::string& info); void DumpSessionsLocked(const std::list& sessionsList, std::string& info); void DumpElementLocked(const std::list& elementsList, std::string& info); - + int32_t CheckSupportOsd(const std::string& deviceId) override; + void GetCachedOsdSwitch(std::vector& deviceIds, std::vector& values) override; + int32_t GetOsdSwitchValueFromRemote() override; + int32_t UpdateOsdSwitchValueFromRemote(int32_t switchVal, const std::string& sourceDeviceId) override; + std::unique_ptr GetRemoteSnapshotInfo(const std::u16string& deviceId, int32_t missionId) override; + int32_t RegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) override; + int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) override; + int32_t PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) override; + int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) override; + int32_t PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) override; private: DistributedSchedService(); bool Init(); @@ -105,7 +118,7 @@ private: int32_t CheckDistributedConnectLocked(const CallerInfo& callerInfo) const; void DecreaseConnectLocked(int32_t uid); static int32_t GetUidLocked(const std::list& sessionList); - int32_t TryConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, + int32_t TryConnectRemoteAbility(const OHOS::AAFwk::Want& want, const sptr& connect, const CallerInfo& callerInfo); std::shared_ptr dschedContinuation_; diff --git a/services/dtbschedmgr/include/distributed_sched_stub.h b/services/dtbschedmgr/include/distributed_sched_stub.h index 823dc5c0..e1970745 100644 --- a/services/dtbschedmgr/include/distributed_sched_stub.h +++ b/services/dtbschedmgr/include/distributed_sched_stub.h @@ -18,6 +18,7 @@ #include "distributed_sched_interface.h" #include "iremote_stub.h" +#include "mission/snapshot.h" namespace OHOS { namespace DistributedSchedule { @@ -27,6 +28,11 @@ public: ~DistributedSchedStub(); int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; +protected: + virtual std::unique_ptr GetRemoteSnapshotInfo(const std::u16string& deviceId, int32_t missionId) + { + return nullptr; + } private: int32_t StartRemoteAbilityInner(MessageParcel& data, MessageParcel& reply); @@ -34,17 +40,32 @@ private: int32_t StartContinuationInner(MessageParcel& data, MessageParcel& reply); int32_t NotifyCompleteContinuationInner(MessageParcel& data, MessageParcel& reply); int32_t NotifyContinuationResultFromRemoteInner(MessageParcel& data, MessageParcel& reply); - int32_t RegisterAbilityTokenInner(MessageParcel& data, MessageParcel& reply); - int32_t UnregisterAbilityTokenInner(MessageParcel& data, MessageParcel& reply); bool CheckDmsRequestPermission(); int32_t ConnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply); int32_t DisconnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply); int32_t ConnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply); int32_t DisconnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply); int32_t NotifyProcessDiedFromRemoteInner(MessageParcel& data, MessageParcel& reply); + int32_t CheckSupportOsdInner(MessageParcel& data, MessageParcel& reply); + int32_t GetCachedOsdSwitchInner(MessageParcel& data, MessageParcel& reply); + int32_t GetMissionInfosInner(MessageParcel& data, MessageParcel& reply); + int32_t GetOsdSwitchValueFromRemoteInner(MessageParcel& data, MessageParcel& reply); + int32_t StoreSnapshotInfoInner(MessageParcel& data, MessageParcel& reply); + int32_t RemoveSnapshotInfoInner(MessageParcel& data, MessageParcel& reply); + int32_t GetRemoteSnapshotInfoInner(MessageParcel& data, MessageParcel& reply); + int32_t RegisterRemoteMissionListenerInner(MessageParcel& data, MessageParcel& reply); + int32_t PrepareAndSyncMissionsFromRemoteInner(MessageParcel& data, MessageParcel& reply); + int32_t UnRegisterRemoteMissionListenerInner(MessageParcel& data, MessageParcel& reply); + int32_t UnRegisterMissionListenerFromRemoteInner(MessageParcel& data, MessageParcel& reply); + int32_t NotifyLocalMissionsChangedInner(MessageParcel& data, MessageParcel& reply); + int32_t NotifyMissionsChangedFromRemoteInner(MessageParcel& data, MessageParcel& reply); + int32_t PrepareAndSyncMissionsInner(MessageParcel& data, MessageParcel& reply); bool CheckCallingUid(); + int32_t NotifyOsdSwitchChangedInner(MessageParcel& data, MessageParcel& reply); + int32_t UpdateOsdSwitchValueFromRemoteInner(MessageParcel& data, MessageParcel& reply); bool EnforceInterfaceToken(MessageParcel& data); + bool CallerInfoUnmarshalling(CallerInfo& callerInfo, MessageParcel& data); using DistributedSchedFunc = int32_t(DistributedSchedStub::*)(MessageParcel& data, MessageParcel& reply); std::map remoteFuncsMap_; std::map localFuncsMap_; diff --git a/services/dtbschedmgr/include/dtbschedmgr_device_info_storage.h b/services/dtbschedmgr/include/dtbschedmgr_device_info_storage.h old mode 100755 new mode 100644 index 1654f8e8..397714c2 --- a/services/dtbschedmgr/include/dtbschedmgr_device_info_storage.h +++ b/services/dtbschedmgr/include/dtbschedmgr_device_info_storage.h @@ -16,6 +16,8 @@ #ifndef OHOS_DISTRIBUTED_DTBSCHEDMGR_DEVICE_INFO_INTERFACE_H #define OHOS_DISTRIBUTED_DTBSCHEDMGR_DEVICE_INFO_INTERFACE_H +#include + #include "adapter/dnetwork_adapter.h" #include "deviceManager/dms_device_info.h" #include "distributed_device_node_listener.h" @@ -42,17 +44,52 @@ public: void DeviceOnlineNotify(const std::shared_ptr devInfo); void DeviceOfflineNotify(const std::string& deviceId); void OnDeviceInfoChanged(const std::string& deviceId, DeviceInfoType type); - std::string AnonymizeDeviceId(const std::string& deviceId); + + /** + * get device info by device id + * + * @param deviceId, string + * @return shared_ptr + */ + std::shared_ptr GetDeviceInfoById(const std::string& deviceId); + + /** + * get uuid by networkId + * + * @param networkId + */ + std::string GetUuidByNetworkId(const std::string& networkId); + + /** + * get networkId by uuid + * + * @param uuid + */ + std::string GetNetworkIdByUuid(const std::string& uuid); + + /** + * GetDeviceIdSet get all of the device Id in same network + * + * @param deviceIdSet Returns the device set. + */ + void GetDeviceIdSet(std::set& deviceIdSet); private: - bool InitNodeIdManager(std::shared_ptr dnetworkAdapter); + bool InitNetworkIdManager(std::shared_ptr dnetworkAdapter); bool ConnectSoftbus(); + void ClearAllDevices(); bool WaitForDnetworkReady(); bool GetLocalDeviceFromDnet(std::string& deviceId); - - std::shared_ptr initHandler_; - std::shared_ptr nodeIdMgrHandler_; + void RegisterUuidNetworkIdMap(const std::string& networkId); + void UnregisterUuidNetworkIdMap(const std::string& networkId); + std::mutex deviceLock_; std::shared_ptr deviceNodeListener_; + std::map> remoteDevices_; + std::string deviceId_; + std::map uuidNetworkIdMap_; + std::mutex uuidNetworkIdLock_; + std::shared_ptr initHandler_; + std::shared_ptr networkIdMgrHandler_; }; } // namespace DistributedSchedule } // namespace OHOS diff --git a/services/dtbschedmgr/include/dtbschedmgr_log.h b/services/dtbschedmgr/include/dtbschedmgr_log.h index d5e0d9df..446d784e 100644 --- a/services/dtbschedmgr/include/dtbschedmgr_log.h +++ b/services/dtbschedmgr/include/dtbschedmgr_log.h @@ -44,11 +44,14 @@ static constexpr OHOS::HiviewDFX::HiLogLabel DSCHED_SERVICE_LABEL = {LOG_CORE, 0 #undef HILOGI #endif -#define HILOGD(...) (void)OHOS::HiviewDFX::HiLog::Debug(DSCHED_SERVICE_LABEL, __VA_ARGS__) -#define HILOGE(...) (void)OHOS::HiviewDFX::HiLog::Error(DSCHED_SERVICE_LABEL, __VA_ARGS__) -#define HILOGF(...) (void)OHOS::HiviewDFX::HiLog::Fatal(DSCHED_SERVICE_LABEL, __VA_ARGS__) -#define HILOGI(...) (void)OHOS::HiviewDFX::HiLog::Info(DSCHED_SERVICE_LABEL, __VA_ARGS__) -#define HILOGW(...) (void)OHOS::HiviewDFX::HiLog::Warn(DSCHED_SERVICE_LABEL, __VA_ARGS__) +#define DMS_LOG(level, fmt, ...) HiviewDFX::HiLog::level(DSCHED_SERVICE_LABEL, \ + "%{public}s::%{public}s " fmt, TAG.c_str(), __FUNCTION__, ##__VA_ARGS__) + +#define HILOGF(fmt, ...) DMS_LOG(Fatal, fmt, ##__VA_ARGS__) +#define HILOGE(fmt, ...) DMS_LOG(Error, fmt, ##__VA_ARGS__) +#define HILOGW(fmt, ...) DMS_LOG(Warn, fmt, ##__VA_ARGS__) +#define HILOGI(fmt, ...) DMS_LOG(Info, fmt, ##__VA_ARGS__) +#define HILOGD(fmt, ...) DMS_LOG(Debug, fmt, ##__VA_ARGS__) enum { /** @@ -206,9 +209,9 @@ enum { */ SEND_REQUEST_DEF_FAIL = 29360163, /** - * Result(29360164) for BMS can not find the specified AA. + * Result(29360164) for BMS can not find the specified ability. */ - CAN_NOT_FOUND_AA_ERR = 29360164, + CAN_NOT_FOUND_ABILITY_ERR = 29360164, /** * Result(29360165) for DMS can not register device state callback. */ @@ -218,9 +221,9 @@ enum { */ UNREGISTER_DEVICE_STATE_CALLBACK_ERR = 29360166, /** - * Result(29360167) for DMS can not start slave device FA. + * Result(29360167) for DMS can not start auxiliary device FA. */ - START_SLAVE_FA_ERR = 29360167, + START_AUXILIARY_FA_ERR = 29360167, /** * Result(29360168) for DMS can not get dmsproxy handle. */ @@ -264,47 +267,63 @@ enum { /** * Result(29360178) for osd function not support. */ - TASK_OSD_NOT_SUPPORTED = 29360178, + MISSION_OSD_NOT_SUPPORTED = 29360178, /** * Result(29360179) for osd switch is off. */ - TASK_OSD_NOT_ENABLED = 29360179, + MISSION_OSD_NOT_ENABLED = 29360179, /** * Result(29360180) for osd switch is on. */ - TASK_OSD_ENABLED = 29360180, + MISSION_OSD_ENABLED = 29360180, /** * Result(29360181) for front app check failed. */ CHECK_FRONT_APP_FAIL = 29360181, - /** - * Result(29360182) for ble connected. + /* + * Result(29360184) for notify mission change listener failed. */ - BLE_CONNECTED = 29360182, - /** - * Result(29360183) for open p2p session failed. - */ - OPENP2PSESSION_FAILED = 29360183, - /** - * Result(29360184) for notify task change listener failed. - */ - TASK_NOTIFY_CHANGE_LISTENER_ERR = 29360184, + MISSION_NOTIFY_CHANGE_LISTENER_ERR = 29360184, /** * Result(29360185) for subscribe data storage change failed. */ - TASK_SUBSCRIBE_DATA_STORAGE_ERR = 29360185, + MISSION_SUBSCRIBE_DATA_STORAGE_ERR = 29360185, /** * Result(29360186) for sync snapshot failed. */ - TASK_SYNC_SNAPSHOT_ERR = 29360186, + MISSION_SYNC_SNAPSHOT_ERR = 29360186, /** - * Result(29360187) for sync task info list failed. + * Result(29360187) for sync mission info list failed. */ - TASK_SYNC_TASK_INFO_LIST_ERR = 29360187, + MISSION_SYNC_MISSION_INFO_LIST_ERR = 29360187, /** * Result(29360188) for distributed communication permission check failed. */ - REMOTE_DISTRIBUTED_COMMUNICATION_PERMISSION_DENIED = 29360188 + REMOTE_DISTRIBUTED_COMMUNICATION_PERMISSION_DENIED = 29360188, + /* + * Result(29360191) for blur snapshot failed. + */ + MISSION_BLUR_SNAPSHOT_ERR = 29360191, + /* + * Result(29360192) for take foreground snapshot failed. + */ + MISSION_TAKE_FOREGROUND_SNAPSHOT_ERR = 29360192, + /* + * Result(29360193) for ccm switch not support. + */ + MISSION_OSD_CCM_NOT_SUPPORTED = 29360193, + /* + * Result(29360194) for wifi switch is off. + */ + MISSION_OSD_WIFI_OFF = 29360194, + /* + * Result(29360195) for child mode is on. + */ + MISSION_OSD_CHILDMODE_ON = 29360195, + /* + * Result(29360196) for cloud switch is off. + */ + MISSION_OSD_CLOUD_SWITCH_OFF = 29360196, }; } // namespace DistributedSchedule } // namespace OHOS diff --git a/services/dtbschedmgr/include/continuation_callback_death_recipient.h b/services/dtbschedmgr/include/mission/distributed_data_change_listener.h old mode 100755 new mode 100644 similarity index 54% rename from services/dtbschedmgr/include/continuation_callback_death_recipient.h rename to services/dtbschedmgr/include/mission/distributed_data_change_listener.h index fbf448da..7b49a8d0 --- a/services/dtbschedmgr/include/continuation_callback_death_recipient.h +++ b/services/dtbschedmgr/include/mission/distributed_data_change_listener.h @@ -1,32 +1,34 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DISTRIBUTED_CONTINUATION_CALLBACK_DEATH_RECIPIENT_H -#define OHOS_DISTRIBUTED_CONTINUATION_CALLBACK_DEATH_RECIPIENT_H - -#include "iremote_object.h" - -namespace OHOS { -namespace DistributedSchedule { -class ContinuationCallbackDeathRecipient : public IRemoteObject::DeathRecipient { -public: - void OnRemoteDied(const wptr &remote) override; - ContinuationCallbackDeathRecipient() = default; - ~ContinuationCallbackDeathRecipient() override = default; -}; -} // namespace DistributedSchedule -} // namespace OHOS - -#endif // OHOS_DISTRIBUTED_CONTINUATION_CALLBACK_DEATH_RECIPIENT_H \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTED_DATA_CHANGE_LISTENER_H +#define DISTRIBUTED_DATA_CHANGE_LISTENER_H + +#include "kvstore_observer.h" +#include "change_notification.h" + +namespace OHOS { +namespace DistributedSchedule { +class DistributedDataChangeListener : public DistributedKv::KvStoreObserver { +public: + DistributedDataChangeListener() = default; + ~DistributedDataChangeListener() override = default; + + void OnChange(const DistributedKv::ChangeNotification &appChangeNotification) override; +}; +} // DistributedSchedule +} // OHOS + +#endif // DISTRIBUTED_DATA_CHANGE_LISTENER_H diff --git a/services/dtbschedmgr/include/mission/distributed_data_storage.h b/services/dtbschedmgr/include/mission/distributed_data_storage.h new file mode 100644 index 00000000..a64ec2ca --- /dev/null +++ b/services/dtbschedmgr/include/mission/distributed_data_storage.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTED_DATA_STORAGE_H +#define DISTRIBUTED_DATA_STORAGE_H + +#include +#include +#include +#include +#include +#include "deviceManager/dms_device_info.h" +#include "distributed_kv_data_manager.h" +#include "event_handler.h" +#include "mission/distributed_data_change_listener.h" + +namespace OHOS { +namespace DistributedSchedule { +class DistributedDataStorage { +public: + DistributedDataStorage() = default; + ~DistributedDataStorage() = default; + + /** + * Init DistributedDataStorage. + * + * @return Returns true if Init successfully. + */ + bool Init(); + + /** + * Stop DistributedDataStorage. + * + * @return Returns true if Stop successfully. + */ + bool Stop(); + + /** + * Insert deviceId + missionId to kvStore. + * + * @param deviceId, the deviceId to insert + * @param missionId, the missionId to insert + * @param byteStream, byte stream for file conversion + * @param len, length of the byte stream + * @return Returns true if Insert successfully. + */ + bool Insert(const std::string& deviceId, int32_t missionId, const uint8_t* byteStream, size_t len); + + /** + * Delete deviceId + missionId in kvStore. + * + * @param deviceId, the deviceId to delete + * @param missionId, the missionId to delete + * @return Returns true if Delete successfully. + */ + bool Delete(const std::string& deviceId, int32_t missionId); + + /** + * FuzzyDelete deviceId in kvStore. + * + * @param deviceId, the deviceId to delete + * @return Returns true if Delete successfully. + */ + bool FuzzyDelete(const std::string& deviceId); + + /** + * Query deviceId + missionId in kvStore. + * + * @param deviceId, the deviceId to query + * @param missionId, the missionId to query + * @param value, if success return the value + * @return Returns true if query successfully. + */ + bool Query(const std::string& deviceId, int32_t missionId, DistributedKv::Value& value) const; + + /** + * PushSync in kvStore. + * + * @param deviceId, push sync to the deviceId + * @return Returns true if sync successfully. + */ + bool Sync(const std::string& deviceId); +private: + bool InitKvDataManager(); + void SubscribeDistributedDataStorage(); + bool UninitKvDataManager(); + bool InsertInnerLocked(const std::string& deviceId, int32_t missionId, const uint8_t* byteStream, size_t len); + bool DeleteInnerLocked(const std::string& deviceId, int32_t missionId); + bool FuzzyDeleteInnerLocked(const std::string& deviceId); + bool QueryInnerLocked(const std::string& deviceId, int32_t missionId, DistributedKv::Value& value) const; + bool Sync(); + bool SyncInnerLocked(const std::vector& deviceVec, const DistributedKv::SyncMode& mode, + uint32_t syncCount); + void RetrySync(const std::vector& deviceVec, const DistributedKv::SyncMode& mode, + uint32_t syncCount); + void InitHandler(); + static void GenerateKey(const std::string& deviceId, int32_t missionId, DistributedKv::Key& key); + static void GenerateKey(const std::string& deviceId, DistributedKv::Key& key); + static void GenerateValue(const uint8_t* byteStream, size_t len, DistributedKv::Value& value); + + mutable std::shared_mutex initLock_; + std::shared_ptr dmsDataStorageHandler_; + std::shared_ptr appDataMgr_; // protected by initLock_ + std::unique_ptr appKvStorePtr_; // protected by initLock_ + std::unique_ptr appDistributedDataChangeListener_; +}; +} // DistributedSchedule +} // OHOS + +#endif // DISTRIBUTED_DATA_STORAGE_H diff --git a/services/dtbschedmgr/include/mission/distributed_sched_mission_manager.h b/services/dtbschedmgr/include/mission/distributed_sched_mission_manager.h new file mode 100644 index 00000000..a04f98cf --- /dev/null +++ b/services/dtbschedmgr/include/mission/distributed_sched_mission_manager.h @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDSCHED_MISSION_MANAGER_H +#define DISTRIBUTEDSCHED_MISSION_MANAGER_H + +#include +#include +#include + +#include "common_event_manager.h" +#include "distributed_sched_interface.h" +#include "event_handler.h" +#include "single_instance.h" +#include "mission/distributed_data_storage.h" +#include "mission/snapshot.h" + +namespace OHOS { +namespace DistributedSchedule { +struct ListenerInfo { + bool called = false; + std::set> listenerSet; + + bool Emplace(sptr listener) + { + auto pairRet = listenerSet.emplace(listener); + if (!pairRet.second) { + return false; + } + return true; + } + + bool Find(sptr listener) + { + auto iter = listenerSet.find(listener); + if (iter == listenerSet.end()) { + return false; + } + return true; + } + + void Erase(sptr listener) + { + listenerSet.erase(listener); + } + + int32_t Size() const + { + return listenerSet.size(); + } + + bool Empty() const + { + return listenerSet.empty(); + } +}; +class DistributedSchedMissionManager { + DECLARE_SINGLE_INSTANCE(DistributedSchedMissionManager); + +public: + void Init(); + int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions, std::vector& missionInfos); + int32_t InitDataStorage(); + int32_t StopDataStorage(); + int32_t StoreSnapshotInfo(const std::string& deviceId, + int32_t missionId, + const uint8_t* byteStream, + size_t len); + int32_t RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId); + std::unique_ptr GetRemoteSnapshotInfo(const std::string& deviceId, int32_t missionId); + void DeviceOnlineNotify(const std::string& deviceId); + void DeviceOfflineNotify(const std::string& deviceId); + void DeleteDataStorage(const std::string& deviceId, bool isDelayed); + int32_t RegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj); + int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj); + int32_t PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, std::vector& missionInfos); + void UnRegisterMissionListenerFromRemote(const std::string& deviceId); + bool needSyncDevice(const std::string& deviceId); + + void NotifySnapshotChanged(const std::string& devId, int32_t missionId); + void OnRemoteDied(const wptr& remote); + + void EnqueueCachedSnapshotInfo(const std::string& deviceId, int32_t missionId, std::unique_ptr snapshot); + std::unique_ptr DequeueCachedSnapshotInfo(const std::string& deviceId, int32_t missionId); + int32_t NotifyMissionsChangedToRemote(const std::vector& missionInfos); + int32_t NotifyMissionsChangedFromRemote(const CallerInfo& callerInfo, const std::vector& missionInfos); + int32_t CheckSupportOsd(const std::string& deviceId); + int32_t CheckOsdSwitch(const std::string& deviceId); + void GetCachedOsdSwitch(std::vector& deviceIds, std::vector& values); + int32_t GetOsdSwitchValueFromRemote(); + int32_t UpdateOsdSwitchValueFromRemote(int32_t switchVal, const std::string& deviceId); + int32_t UpdateSwitchValueToRemote(); + void UpdateConnCapSupportOsd(const std::string& deviceId); + void NotifyOsdSwitchChanged(bool needNotifyChanged); + int32_t PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag); + void OnRemoteDmsDied(const wptr& remote); + void NotifyDmsProxyProcessDied(); + void OnDnetDied(); +private: + std::map> deviceHandle_; + mutable std::mutex remoteMissionInfosLock_; + std::map> deviceMissionInfos_; + sptr GetRemoteDms(const std::string& deviceId); + bool IsDeviceIdValidated(const std::string& deviceId); + std::shared_ptr FetchDeviceHandler(const std::string& deviceId); + bool GenerateCallerInfo(CallerInfo& callerInfo); + void NotifyMissionsChangedToRemoteInner(const std::string& remoteUuid, + const std::vector& missionInfos, const CallerInfo& callerInfo); + std::string GenerateKeyInfo(const std::string& devId, int32_t missionId) + { + return devId + "_" + std::to_string(missionId); + } + bool AllowMissionUid(int32_t uid); + int32_t PrepareAndSyncMissions(const std::string& dstDevId, const std::string& localDevId); + int32_t PrepareAndSyncMissions(const std::string& dstDevId, const sptr& remoteDms); + int32_t UnRegisterRemoteMissionListenerInner(const std::string& dstDevId, bool offline, bool exit = false); + void CleanMissionResources(const std::string& dstDevId); + void RetryStartRemoteSyncMission(const std::string& dstDeviceId, const std::string& localDevId, int32_t retryTimes); + bool HasSyncListener(const std::string& dstDeviceId); + void DeleteCachedSnapshotInfo(const std::string& networkId); + int32_t FetchCachedRemoteMissions(const std::string& srcId, int32_t numMissions, + std::vector& missionInfos); + void RebornMissionCache(const std::string& deviceId, const std::vector& missionInfos); + void CleanMissionCache(const std::string& deviceId); + void UpdateSwitchValueToRemoteInner(std::set& remoteSyncDeviceSet, + const std::string& localNetworkId); + void TryUpdateSwitchValueToRemote(const std::string& localNetworkId, + const std::string& destUuid, int32_t retryTime); + bool IsValidOsdSwitchValue(int32_t osdSwitchVal); + bool IsConnCapSupportOsd(const std::string& deviceId); + bool GetConnCapSupportOsd(const std::string& deviceId); + bool GetConnCapSupportOsdInnerLocked(const std::string& deviceId); + bool PreCheckSupportOsd(const std::string& deviceId); + void NotifyOsdSwitchChanged(bool needNotifyChanged, const std::string& deviceId, int32_t switchVal); + void OnMissionListenerDied(const sptr& remote); + void OnRemoteDmsDied(const sptr& remote); + void RetryRegisterMissionChange(int32_t retryTimes); + + class ListenerDeathRecipient : public IRemoteObject::DeathRecipient { + public: + void OnRemoteDied(const wptr& remote) override; + }; + sptr listenerDeath_; + + std::set remoteSyncDeviceSet_; + std::mutex remoteSyncDeviceLock_; + + std::map> cachedSnapshotInfos_; + std::map listenDeviceMap_; + std::mutex listenDeviceLock_; + std::shared_ptr distributedDataStorage_; + + std::set allowMissionUids_; + std::mutex allowMissionUidsLock_; + bool isRegMissionChange_ = false; + + class RemoteDmsDeathRecipient : public IRemoteObject::DeathRecipient { + public: + void OnRemoteDied(const wptr& remote) override; + }; + sptr remoteDmsRecipient_; + std::map> remoteDmsMap_; + std::mutex remoteDmsLock_; + std::shared_ptr missionHandler_; + std::shared_ptr updateHandler_; + std::mutex osdSwitchLock_; + std::map osdSwitchValueMap_; // key is uuid + std::map connCapSupportOsdMap_; // key is networkId +}; +} +} +#endif // DISTRIBUTEDSCHED_MISSION_MANAGER_H diff --git a/services/dtbschedmgr/include/mission/mission_changed_notify.h b/services/dtbschedmgr/include/mission/mission_changed_notify.h new file mode 100644 index 00000000..408232a3 --- /dev/null +++ b/services/dtbschedmgr/include/mission/mission_changed_notify.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SERVICES_DTBSCHEDMGR_INCLUDE_IMISSION_CHANGED_LISTENER_H +#define SERVICES_DTBSCHEDMGR_INCLUDE_IMISSION_CHANGED_LISTENER_H + +#include + +#include "iremote_broker.h" +#include "mission/snapshot.h" + +namespace OHOS { +namespace DistributedSchedule { +class MissionChangedNotify { +public: + static void NotifySnapshot(const sptr& remoteObject, const std::u16string& deviceId, + int32_t missionId); + static void NotifyMissionsChanged(const sptr& remoteObject, const std::u16string& deviceId); + static void NotifyNetDisconnect(const sptr& remoteObject, const std::u16string& deviceId, + int32_t state); + static void NotifyOsdSwitchChanged(const sptr& remoteObject, const std::u16string& deviceId, + bool isSwitchOn); +}; +} // namespace DistributedSchedule +} // namespace OHOS +#endif /* SERVICES_DTBSCHEDMGR_INCLUDE_IMISSION_CHANGED_LISTENER_H */ diff --git a/services/dtbschedmgr/include/mission/mission_constant.h b/services/dtbschedmgr/include/mission/mission_constant.h new file mode 100644 index 00000000..a254e8c4 --- /dev/null +++ b/services/dtbschedmgr/include/mission/mission_constant.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_MISSION_CONSTANT_H +#define OHOS_DISTRIBUTED_MISSION_CONSTANT_H + +namespace OHOS { +namespace DistributedSchedule { +namespace Constants { +namespace Mission { +constexpr int32_t GET_MAX_MISSIONS = 20; +} // Mission +} // Constants +} // DistributedSchedule +} // OHOS + +#endif diff --git a/services/dtbschedmgr/include/mission/mission_info.h b/services/dtbschedmgr/include/mission/mission_info.h new file mode 100644 index 00000000..231aba1e --- /dev/null +++ b/services/dtbschedmgr/include/mission/mission_info.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_MISSION_INFO_H +#define OHOS_DISTRIBUTED_MISSION_INFO_H + +#include + +#include "parcel.h" + +#include "application_info.h" +#include "element_name.h" +#include "ohos/aafwk/content/want.h" + +namespace OHOS { +namespace DistributedSchedule { +struct MissionInfo : public Parcelable { + int32_t id = -1; + int32_t runingState = -1; + int32_t userId = 0; + int32_t missionStackId = -1; + std::vector combinedMissionIds; + int32_t windowMode = 0; + int32_t boundsLeft = 0; + int32_t boundsTop = 0; + int32_t boundsRight = 0; + int32_t boundsBottom = 0; + std::shared_ptr baseWant; + std::shared_ptr topAbility; + std::shared_ptr baseAbility; + std::shared_ptr reservedAbility; + int64_t lastMissionActiveTime = 0; + int32_t displayId = 0; + std::string label; + int32_t size = 0; + std::string iconPath; + int32_t color = 0; + int32_t windowType = 0; + bool supportsMultiWindow = false; + int32_t missionType = INT_MAX; + int32_t windowTypeMode = 0; + + bool ReadFromParcel(Parcel& parcel); + virtual bool Marshalling(Parcel& parcel) const override; + static MissionInfo* Unmarshalling(Parcel& parcel); + std::string ToString() const; + + static bool ReadMissionInfoVectorFromParcel(Parcel& parcel, std::vector &missionInfos); + static bool WriteMissionInfoVectorFromParcel(Parcel& parcel, const std::vector &missionInfos); +}; +} // namespace DistributedSchedule +} // namespace OHOS +#endif // OHOS_DISTRIBUTED_MISSION_INFO_H diff --git a/services/dtbschedmgr/include/mission/mission_info_converter.h b/services/dtbschedmgr/include/mission/mission_info_converter.h new file mode 100644 index 00000000..fb238d3b --- /dev/null +++ b/services/dtbschedmgr/include/mission/mission_info_converter.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DISTRIBUTEDSCHED_MISSION_INFO_CONVERTER_H +#define DISTRIBUTEDSCHED_MISSION_INFO_CONVERTER_H + +#include +#include + +#include "ability_mission_info.h" +#include "mission/mission_info.h" + +using AbilityMissionInfo = OHOS::AAFwk::AbilityMissionInfo; + +namespace OHOS { +namespace DistributedSchedule { +class MissionInfoConverter { +public: + static int32_t ConvertToMissionInfos(std::vector& abilityMissionInfos, + std::vector& missionInfos); + static int32_t ConvertToAbilityMissionInfos(std::vector& missionInfos, + std::vector& abilityMissionInfos); +}; +} +} +#endif // DISTRIBUTEDSCHED_MISSION_INFO_CONVERTER_H diff --git a/services/dtbschedmgr/include/mission/snapshot.h b/services/dtbschedmgr/include/mission/snapshot.h new file mode 100644 index 00000000..7478c5b4 --- /dev/null +++ b/services/dtbschedmgr/include/mission/snapshot.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SERVICES_DTBSCHEDMGR_INCLUDE_SNAPSHOT_SNAP_SHOT_H +#define SERVICES_DTBSCHEDMGR_INCLUDE_SNAPSHOT_SNAP_SHOT_H + +#include + +#include "dtbschedmgr_log.h" +#include "message_parcel.h" +#include "pixel_map.h" + +namespace OHOS { +namespace DistributedSchedule { +struct Rect; +class Snapshot { +public: + ~Snapshot(); + bool WriteToParcel(MessageParcel& data) const; + static std::unique_ptr Create(const std::vector& data); + int64_t GetCreatedTime() const; + int64_t GetLastAccessTime() const; + void UpdateLastAccessTime(int64_t accessTime); +private: + static std::unique_ptr CreatePixelMap(const uint8_t* buffer, uint32_t bufferSize); + static std::unique_ptr FillSnapShot(MessageParcel& data); + std::unique_ptr pixelMap_; + int32_t orientation_ = 0; + std::unique_ptr rect_; + bool reducedResolution_ = true; + float scale_ = 0.0; + bool isRealSnapshot_ = true; + int32_t windowingMode_ = 0; + int32_t systemUiVisibility_ = 0; + bool isTranslucent_ = true; + std::unique_ptr windowBounds_; + std::u16string applicationLabel_; + std::u16string activityLabel_; + std::vector icon_; + std::u16string secApplicationLabel_; + std::u16string secActivityLabel_; + std::vector secIcon_; + std::u16string sourceDeviceTips_; + + // inner used + int64_t createdTime_ = 0; + int64_t lastAccessTime_ = 0; + int32_t version_ = 0; +}; + +struct Rect : public Parcelable { + Rect(int32_t left, int32_t top, int32_t right, int32_t bottom) + { + this->left = left; + this->top = top; + this->right = right; + this->bottom = bottom; + } + + bool Marshalling(Parcel &parcel) const override + { + if (!parcel.WriteInt32(left)) { + return false; + } + if (!parcel.WriteInt32(top)) { + return false; + } + if (!parcel.WriteInt32(right)) { + return false; + } + if (!parcel.WriteInt32(bottom)) { + return false; + } + return true; + } + + static Rect* Unmarshalling(Parcel &parcel) + { + int32_t left = parcel.ReadInt32(); + int32_t top = parcel.ReadInt32(); + int32_t right = parcel.ReadInt32(); + int32_t bottom = parcel.ReadInt32(); + auto rectPtr = new Rect(left, top, right, bottom); + return rectPtr; + } + + int32_t left = 0; + int32_t top = 0; + int32_t right = 0; + int32_t bottom = 0; +}; +} // DistributedSchedule +} // OHOS +#endif /* SERVICES_DTBSCHEDMGR_INCLUDE_SNAPSHOT_SNAP_SHOT_H */ diff --git a/services/dtbschedmgr/include/parcel_helper.h b/services/dtbschedmgr/include/parcel_helper.h old mode 100755 new mode 100644 diff --git a/services/dtbschedmgr/src/ability_connection_wrapper_proxy.cpp b/services/dtbschedmgr/src/ability_connection_wrapper_proxy.cpp new file mode 100644 index 00000000..3bbb5dc7 --- /dev/null +++ b/services/dtbschedmgr/src/ability_connection_wrapper_proxy.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ability_connection_wrapper_proxy.h" + +#include "dtbschedmgr_log.h" +#include "ipc_object_proxy.h" +#include "ipc_types.h" +#include "parcel_helper.h" + +namespace OHOS { +namespace DistributedSchedule { +namespace { +const std::u16string CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.abilityshell.DistributedConnection"; +const std::string TAG = "AbilityConnectionWrapperProxy"; +} + +void AbilityConnectionWrapperProxy::OnAbilityConnectDone(const AppExecFwk::ElementName& element, + const sptr& remoteObject, int32_t resultCode) +{ + HILOGD("AbilityConnectionWrapperProxy::OnAbilityConnectDone called"); + MessageParcel data; + if (!data.WriteInterfaceToken(CONNECTION_CALLBACK_INTERFACE_TOKEN)) { + return; + } + + MessageParcel reply; + MessageOption option; + PARCEL_WRITE_HELPER_NORET(data, Parcelable, &element); + PARCEL_WRITE_HELPER_NORET(data, RemoteObject, remoteObject); + PARCEL_WRITE_HELPER_NORET(data, Int32, resultCode); + int32_t errCode = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_CONNECT_DONE, data, reply, option); + HILOGD("AbilityConnectionWrapperProxy::OnAbilityConnectDone result %{public}d", errCode); +} + +void AbilityConnectionWrapperProxy::OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, int32_t resultCode) +{ + HILOGD("AbilityConnectionWrapperProxy::OnAbilityDisconnectDone called"); + MessageParcel data; + if (!data.WriteInterfaceToken(CONNECTION_CALLBACK_INTERFACE_TOKEN)) { + return; + } + + MessageParcel reply; + MessageOption option; + PARCEL_WRITE_HELPER_NORET(data, Parcelable, &element); + PARCEL_WRITE_HELPER_NORET(data, Int32, resultCode); + int32_t errCode = Remote()->SendRequest(IAbilityConnection::ON_ABILITY_DISCONNECT_DONE, data, reply, option); + HILOGD("AbilityConnectionWrapperProxy::OnAbilityDisconnectDone result %{public}d", errCode); +} +} // namespace DistributedSchedule +} // namespace OHOS \ No newline at end of file diff --git a/services/dtbschedmgr/src/ability_connection_wrapper_stub.cpp b/services/dtbschedmgr/src/ability_connection_wrapper_stub.cpp old mode 100755 new mode 100644 index 69fdc173..7b941e8b --- a/services/dtbschedmgr/src/ability_connection_wrapper_stub.cpp +++ b/services/dtbschedmgr/src/ability_connection_wrapper_stub.cpp @@ -15,17 +15,15 @@ #include "ability_connection_wrapper_stub.h" +#include "ability_connection_wrapper_proxy.h" #include "dtbschedmgr_log.h" -#include "ipc_object_proxy.h" #include "ipc_types.h" -#include "parcel_helper.h" namespace OHOS { namespace DistributedSchedule { using namespace AAFwk; - namespace { -const std::u16string CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.abilityshell.DistributedConnection"; +const std::string TAG = "AbilityConnectionWrapperStub"; } AbilityConnectionWrapperStub::AbilityConnectionWrapperStub(sptr connection) @@ -52,7 +50,7 @@ int32_t AbilityConnectionWrapperStub::OnRemoteRequest(uint32_t code, MessageParc int32_t resultCode = ERR_NONE; switch (code) { case IAbilityConnection::ON_ABILITY_CONNECT_DONE: { - if (auto remoteObject = data.ReadParcelable()) { + if (auto remoteObject = data.ReadRemoteObject()) { resultCode = data.ReadInt32(); OnAbilityConnectDone(*element, remoteObject, resultCode); return ERR_NONE; @@ -75,35 +73,15 @@ int32_t AbilityConnectionWrapperStub::OnRemoteRequest(uint32_t code, MessageParc void AbilityConnectionWrapperStub::OnAbilityConnectDone(const AppExecFwk::ElementName& element, const sptr& remoteObject, int32_t resultCode) { - HILOGD("AbilityConnectionWrapperStub::OnAbilityConnectDone called"); - MessageParcel data; - if (!data.WriteInterfaceToken(CONNECTION_CALLBACK_INTERFACE_TOKEN)) { - return; - } - MessageParcel reply; - MessageOption option; - PARCEL_WRITE_HELPER_NORET(data, Parcelable, &element); - PARCEL_WRITE_HELPER_NORET(data, RemoteObject, remoteObject); - PARCEL_WRITE_HELPER_NORET(data, Int32, resultCode); - int32_t errCode = distributedConnection_->SendRequest(ON_ABILITY_CONNECT_DONE, data, reply, option); - HILOGI("AbilityConnectionWrapperStub::OnAbilityConnectDone result %{public}d", errCode); + auto proxy = std::make_unique(distributedConnection_); + proxy->OnAbilityConnectDone(element, remoteObject, resultCode); } void AbilityConnectionWrapperStub::OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, int32_t resultCode) { - HILOGD("AbilityConnectionWrapperStub::OnAbilityDisconnectDone called"); - MessageParcel data; - if (!data.WriteInterfaceToken(CONNECTION_CALLBACK_INTERFACE_TOKEN)) { - return; - } - - MessageParcel reply; - MessageOption option; - PARCEL_WRITE_HELPER_NORET(data, Parcelable, &element); - PARCEL_WRITE_HELPER_NORET(data, Int32, resultCode); - int32_t errCode = distributedConnection_->SendRequest(ON_ABILITY_DISCONNECT_DONE, data, reply, option); - HILOGI("AbilityConnectionWrapperStub::OnAbilityDisconnectDone result %{public}d", errCode); + auto proxy = std::make_unique(distributedConnection_); + proxy->OnAbilityDisconnectDone(element, resultCode); } } // namespace DistributedSchedule } // namespace OHOS \ No newline at end of file diff --git a/services/dtbschedmgr/src/adapter/dnetwork_adapter.cpp b/services/dtbschedmgr/src/adapter/dnetwork_adapter.cpp old mode 100755 new mode 100644 index 8eec7a2a..aaea05c5 --- a/services/dtbschedmgr/src/adapter/dnetwork_adapter.cpp +++ b/services/dtbschedmgr/src/adapter/dnetwork_adapter.cpp @@ -34,6 +34,7 @@ const std::string PKG_NAME = "DBinderBus_" + std::to_string(getpid()); constexpr int32_t NON_ANONYMIZED_LENGTH = 6; const std::string EMPTY_DEVICE_ID = ""; +const std::string TAG = "DnetworkAdapter"; } std::shared_ptr DnetworkAdapter::dnetworkHandler_; @@ -106,7 +107,7 @@ bool DnetworkAdapter::AddDeviceChangeListener(const std::shared_ptr DnetworkAdapter::GetLocalBasicInfo() auto info = std::make_shared(); int32_t errCode = GetLocalNodeDeviceInfo(PKG_NAME.c_str(), info.get()); if (errCode != ERR_OK) { - HILOGE("DnetworkAdapter::GetLocalBasicInfo errCode = %{public}d", errCode); + HILOGE("GetLocalBasicInfo errCode = %{public}d", errCode); return nullptr; } return info; } -std::string DnetworkAdapter::GetUdidByNodeId(const std::string& nodeId) +std::string DnetworkAdapter::GetUdidByNetworkId(const std::string& networkId) { - return GetUuidOrUdidByNodeId(nodeId, NodeDeivceInfoKey::NODE_KEY_UDID); + return GetUuidOrUdidByNetworkId(networkId, NodeDeivceInfoKey::NODE_KEY_UDID); } -std::string DnetworkAdapter::GetUuidByNodeId(const std::string& nodeId) +std::string DnetworkAdapter::GetUuidByNetworkId(const std::string& networkId) { - return GetUuidOrUdidByNodeId(nodeId, NodeDeivceInfoKey::NODE_KEY_UUID); + return GetUuidOrUdidByNetworkId(networkId, NodeDeivceInfoKey::NODE_KEY_UUID); } -std::string DnetworkAdapter::GetUuidOrUdidByNodeId(const std::string& nodeId, NodeDeivceInfoKey keyType) +std::string DnetworkAdapter::GetUuidOrUdidByNetworkId(const std::string& networkId, NodeDeivceInfoKey keyType) { - if (nodeId.empty()) { + if (networkId.empty()) { return std::string(); } char uuidOrUdid[DEVICE_ID_SIZE] = {0}; - int32_t ret = GetNodeKeyInfo(PKG_NAME.c_str(), nodeId.c_str(), keyType, + int32_t ret = GetNodeKeyInfo(PKG_NAME.c_str(), networkId.c_str(), keyType, reinterpret_cast(uuidOrUdid), DEVICE_ID_SIZE); return (ret == ERR_OK) ? std::string(uuidOrUdid) : std::string(); } diff --git a/services/dtbschedmgr/src/bundle/bundle_manager_internal.cpp b/services/dtbschedmgr/src/bundle/bundle_manager_internal.cpp old mode 100755 new mode 100644 index 871240c0..533a1ae7 --- a/services/dtbschedmgr/src/bundle/bundle_manager_internal.cpp +++ b/services/dtbschedmgr/src/bundle/bundle_manager_internal.cpp @@ -23,20 +23,22 @@ namespace OHOS { namespace DistributedSchedule { +namespace { +const std::string TAG = "BundleManagerInternal"; +} IMPLEMENT_SINGLE_INSTANCE(BundleManagerInternal); - bool BundleManagerInternal::GetCallerAppIdFromBms(int32_t callingUid, std::string& appId) { std::vector bundleNameList; int32_t ret = DistributedSchedAdapter::GetInstance().GetBundleNameListFromBms(callingUid, bundleNameList); if (ret != ERR_OK || bundleNameList.empty()) { - HILOGE("BundleManagerInternal::GetCallerAppIdFromBms error"); + HILOGE("GetBundleNameListFromBms error"); return false; } auto bundleMgr = GetBundleManager(); if (bundleMgr == nullptr) { - HILOGE("BundleManagerInternal::GetCallerAppIdFromBms failed to get bms"); + HILOGE("failed to get bms"); return false; } @@ -44,7 +46,7 @@ bool BundleManagerInternal::GetCallerAppIdFromBms(int32_t callingUid, std::strin std::string identity = IPCSkeleton::ResetCallingIdentity(); appId = bundleMgr->GetAppIdByBundleName(bundleNameList.front(), callingUid); IPCSkeleton::SetCallingIdentity(identity); - HILOGD("BundleManagerInternal::GetCallerAppIdFromBms appId:%s", appId.c_str()); + HILOGD("appId:%s", appId.c_str()); return true; } @@ -55,7 +57,7 @@ sptr BundleManagerInternal::GetBundleManager() return iface_cast( samgrClient->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID)); } else { - HILOGE("DistributedSchedAdapter::GetBundleManager failed to get samgr"); + HILOGE("failed to get samgr"); return nullptr; } } diff --git a/services/dtbschedmgr/src/connect_death_recipient.cpp b/services/dtbschedmgr/src/connect_death_recipient.cpp old mode 100755 new mode 100644 index d3789ed6..bf7461cc --- a/services/dtbschedmgr/src/connect_death_recipient.cpp +++ b/services/dtbschedmgr/src/connect_death_recipient.cpp @@ -21,9 +21,12 @@ namespace OHOS { namespace DistributedSchedule { +namespace { +const std::string TAG = "ConnectDeathRecipient"; +} void ConnectDeathRecipient::OnRemoteDied(const wptr& remote) { - HILOGI("ConnectDeathRecipient::OnRemoteDied called"); + HILOGI("OnRemoteDied called"); DistributedSchedAdapter::GetInstance().ProcessConnectDied(remote.promote()); } } // namespace DistributedSchedule diff --git a/services/dtbschedmgr/src/deviceManager/dms_device_info.cpp b/services/dtbschedmgr/src/deviceManager/dms_device_info.cpp old mode 100755 new mode 100644 index e45af971..092cd877 --- a/services/dtbschedmgr/src/deviceManager/dms_device_info.cpp +++ b/services/dtbschedmgr/src/deviceManager/dms_device_info.cpp @@ -21,6 +21,9 @@ namespace OHOS { namespace DistributedSchedule { +namespace { +const std::string TAG = "DmsDeviceInfo"; +} const std::string& DmsDeviceInfo::GetDeviceName() const { return deviceName_; diff --git a/services/dtbschedmgr/src/distributed_device_node_listener.cpp b/services/dtbschedmgr/src/distributed_device_node_listener.cpp old mode 100755 new mode 100644 index eb9d1847..205ddcb8 --- a/services/dtbschedmgr/src/distributed_device_node_listener.cpp +++ b/services/dtbschedmgr/src/distributed_device_node_listener.cpp @@ -21,10 +21,13 @@ namespace OHOS { namespace DistributedSchedule { +namespace { +const std::string TAG = "DistributedDeviceNodeListener"; +} void DistributedDeviceNodeListener::OnDeviceOnline(const NodeBasicInfo* nodeBasicInfo) { if (nodeBasicInfo == nullptr) { - HILOGE("DistributedDeviceNodeListener::OnDeviceOnline null nodeBasicInfo"); + HILOGE("OnDeviceOnline null nodeBasicInfo"); return; } auto dmsDeviceInfo = std::make_shared( @@ -35,7 +38,7 @@ void DistributedDeviceNodeListener::OnDeviceOnline(const NodeBasicInfo* nodeBasi void DistributedDeviceNodeListener::OnDeviceOffline(const NodeBasicInfo* nodeBasicInfo) { if (nodeBasicInfo == nullptr) { - HILOGE("DistributedDeviceNodeListener::OnDeviceOffline null nodeBasicInfo"); + HILOGE("OnDeviceOffline null nodeBasicInfo"); return; } DtbschedmgrDeviceInfoStorage::GetInstance().DeviceOfflineNotify(nodeBasicInfo->networkId); diff --git a/services/dtbschedmgr/src/distributed_sched_ability_shell.cpp b/services/dtbschedmgr/src/distributed_sched_ability_shell.cpp deleted file mode 100755 index 954e2d83..00000000 --- a/services/dtbschedmgr/src/distributed_sched_ability_shell.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "distributed_sched_ability_shell.h" - -#include "dtbschedmgr_log.h" -#include "ipc_skeleton.h" -#include "ipc_types.h" -#include "iservice_registry.h" -#include "parcel_helper.h" -#include "string_ex.h" - -namespace OHOS { -namespace DistributedSchedule { -namespace { -const std::u16string ABILITYSHELL_INTERFACE_TOKEN = u"ohos.abilityshell.ContinuationScheduler"; -constexpr int64_t SCHEDULE_COMPLETE_CONTINUE = 1; -} -using namespace OHOS::HiviewDFX; -IMPLEMENT_SINGLE_INSTANCE(DistributedSchedAbilityShell); - -DistributedSchedAbilityShell::DistributedSchedAbilityShell() -{ - death_ = sptr(new ContinuationCallbackDeathRecipient()); -} - -int32_t DistributedSchedAbilityShell::RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) -{ - if (abilityToken == nullptr || continuationCallback == nullptr) { - HILOGE("RegisterAbilityToken abilityToken or continuationCallback is null"); - return INVALID_PARAMETERS_ERR; - } - std::lock_guard autoLock(regAbilityLock_); - auto itAbility = regAbilityMap_.find(continuationCallback); - if (itAbility == regAbilityMap_.end()) { - // new continuationCallback, add death recipient - continuationCallback->AddDeathRecipient(death_); - } - auto& tokenList = regAbilityMap_[continuationCallback]; - for (const auto& tokenItem : tokenList) { - if (tokenItem == abilityToken) { - // already have reg abilityToken - return REG_REPEAT_ABILITY_TOKEN_ERR; - } - } - // add abilityToken - tokenList.emplace_back(abilityToken); - return ERR_OK; -} - -int32_t DistributedSchedAbilityShell::UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) -{ - if (abilityToken == nullptr || continuationCallback == nullptr) { - HILOGE("UnregisterAbilityToken abilityToken or continuationCallback is null"); - return INVALID_PARAMETERS_ERR; - } - std::lock_guard autoLock(regAbilityLock_); - auto itAbility = regAbilityMap_.find(continuationCallback); - if (itAbility != regAbilityMap_.end()) { - std::list>& tokenList = itAbility->second; - int32_t sizeBefore = tokenList.size(); - if (sizeBefore == 0) { - return NO_ABILITY_TOKEN_ERR; - } - tokenList.remove(abilityToken); - int32_t sizeAfter = tokenList.size(); - // if list is empty and erase it from map - if (sizeAfter == 0) { - if (itAbility->first != nullptr) { - itAbility->first->RemoveDeathRecipient(death_); - } - regAbilityMap_.erase(itAbility); - } - if (sizeBefore == sizeAfter) { - return NO_ABILITY_TOKEN_ERR; - } - return ERR_OK; - } - // not find continuationCallback, return NO_APP_THREAD_ERR - return NO_APP_THREAD_ERR; -} - -sptr DistributedSchedAbilityShell::GetContinuationCallback(const sptr& abilityToken) -{ - if (abilityToken == nullptr) { - HILOGE("GetContinuationCallback abilityToken is null"); - return nullptr; - } - std::lock_guard autoLock(regAbilityLock_); - for (const auto& regAbility : regAbilityMap_) { - const std::list>& tokenList = regAbility.second; - for (const auto& tokenItem : tokenList) { - if (tokenItem == abilityToken) { - // find abilityToken - return regAbility.first; - } - } - } - return nullptr; -} - -void DistributedSchedAbilityShell::RemoveContinuationCallback(const sptr& continuationCallback) -{ - if (continuationCallback == nullptr) { - HILOGE("RemoveContinuationCallback continuationCallback is null"); - return; - } - std::lock_guard autoLock(regAbilityLock_); - continuationCallback->RemoveDeathRecipient(death_); - regAbilityMap_.erase(continuationCallback); -} - -int32_t DistributedSchedAbilityShell::ScheduleCompleteContinuation(const sptr& abilityToken, - int32_t isSuccess) -{ - if (abilityToken == nullptr) { - HILOGE("ScheduleCompleteContinuation ability abilityToken is null"); - return INVALID_PARAMETERS_ERR; - } - - sptr continuationCallback = GetContinuationCallback(abilityToken); - if (continuationCallback == nullptr) { - HILOGE("ScheduleCompleteContinuation continuationCallback is null"); - return INVALID_PARAMETERS_ERR; - } - MessageParcel data; - if (!data.WriteInterfaceToken(ABILITYSHELL_INTERFACE_TOKEN)) { - return ERR_FLATTEN_OBJECT; - } - PARCEL_WRITE_HELPER(data, Int32, isSuccess); - MessageParcel reply; - MessageOption option; - int32_t error = continuationCallback->SendRequest(SCHEDULE_COMPLETE_CONTINUE, data, reply, option); - HILOGI("ScheduleCompleteContinuation transact result: %{public}d", error); - return error; -} -} // namespace DistributedSchedule -} // namespace OHOS \ No newline at end of file diff --git a/services/dtbschedmgr/src/distributed_sched_adapter.cpp b/services/dtbschedmgr/src/distributed_sched_adapter.cpp old mode 100755 new mode 100644 index 0017efc8..f27f1038 --- a/services/dtbschedmgr/src/distributed_sched_adapter.cpp +++ b/services/dtbschedmgr/src/distributed_sched_adapter.cpp @@ -22,6 +22,8 @@ #include "ability_manager_client.h" #include "ipc_skeleton.h" #include "ipc_types.h" +#include "mission/distributed_sched_mission_manager.h" +#include "mission/mission_info_converter.h" #include "parcel_helper.h" #include "string_ex.h" @@ -34,6 +36,7 @@ using namespace AppExecFwk; namespace { // set a non-zero value on need later constexpr int64_t DEVICE_OFFLINE_DELAY_TIME = 0; +const std::string TAG = "DistributedSchedAdapter"; } IMPLEMENT_SINGLE_INSTANCE(DistributedSchedAdapter); @@ -43,7 +46,7 @@ void DistributedSchedAdapter::Init() if (dmsAdapterHandler_ == nullptr) { shared_ptr runner = EventRunner::Create("dmsAdapter"); if (runner == nullptr) { - HILOGE("DistributedSchedAdapter create runner failed"); + HILOGE("create runner failed"); return; } dmsAdapterHandler_ = make_shared(runner); @@ -58,10 +61,10 @@ void DistributedSchedAdapter::UnInit() int32_t DistributedSchedAdapter::ConnectAbility(const OHOS::AAFwk::Want& want, const sptr& connect, const sptr& callerToken) { - HILOGD("DistributedSchedAdapter ConnectAbility"); + HILOGD("ConnectAbility"); ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect(); if (errCode != ERR_OK) { - HILOGE("DistributedSchedAdapter connect ability server failed, errCode=%{public}d", errCode); + HILOGE("connect ability server failed, errCode=%{public}d", errCode); return errCode; } ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, @@ -71,10 +74,10 @@ int32_t DistributedSchedAdapter::ConnectAbility(const OHOS::AAFwk::Want& want, int32_t DistributedSchedAdapter::DisconnectAbility(const sptr& connect) { - HILOGD("DistributedSchedAdapter DisconnectAbility"); + HILOGD("DisconnectAbility"); ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect(); if (errCode != ERR_OK) { - HILOGE("DistributedSchedAdapter connect ability server failed, errCode=%{public}d", errCode); + HILOGE("connect ability server failed, errCode=%{public}d", errCode); return errCode; } ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility( @@ -164,7 +167,7 @@ int32_t DistributedSchedAdapter::GetBundleNameListFromBms(int32_t uid, vector bundleNameList; int32_t ret = GetBundleNameListFromBms(uid, bundleNameList); if (ret != ERR_OK) { - HILOGE("DistributedSchedAdapter::GetBundleNameListFromBms failed"); + HILOGE("GetBundleNameListFromBms failed"); return ret; } for (const string& bundleName : bundleNameList) { @@ -177,14 +180,54 @@ int32_t DistributedSchedAdapter::GetBundleNameListFromBms(int32_t uid, std::vect { auto bundleMgr = BundleManagerInternal::GetBundleManager(); if (bundleMgr == nullptr) { - HILOGE("DistributedSchedAdapter::GetBundleNameListFromBms failed to get bms"); + HILOGE("GetBundleNameListFromBms failed to get bms"); return OBJECT_NULL; } std::string identity = IPCSkeleton::ResetCallingIdentity(); bool result = bundleMgr->GetBundlesForUid(uid, bundleNameList); IPCSkeleton::SetCallingIdentity(identity); - HILOGD("DistributedSchedAdapter::GetBundleNameListFromBms %{public}d", result); + HILOGD("GetBundleNameListFromBms %{public}d", result); return result ? ERR_OK : BUNDLE_MANAGER_SERVICE_ERR; } + +int32_t DistributedSchedAdapter::GetLocalMissionInfos(int32_t numMissions, std::vector& missionInfos) +{ + ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect(); + if (errCode != ERR_OK) { + HILOGE("get ability server failed, errCode=%{public}d", errCode); + return errCode; + } + std::vector abilityMissions; + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->GetRecentMissions(numMissions, + RECENT_WITH_EXCLUDED, abilityMissions); + if (ret != ERR_OK) { + HILOGE("GetRecentMissions failed, ret=%{public}d", ret); + return ret; + } + return MissionInfoConverter::ConvertToMissionInfos(abilityMissions, missionInfos); +} + +bool DistributedSchedAdapter::AllowMissionUid(int32_t uid) +{ + if (uid < 0) { + HILOGE("AllowMissionUid invalid params!"); + return false; + } + return true; +} + +int32_t DistributedSchedAdapter::RegisterMissionChange(bool willRegister) +{ + return ERR_NONE; +} + +int32_t DistributedSchedAdapter::GetOsdSwitch() +{ + return MISSION_OSD_ENABLED; +} + +void DistributedSchedAdapter::OnOsdEventOccur(int32_t flag) +{ +} } // namespace DistributedSchedule -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/dtbschedmgr/src/distributed_sched_continuation.cpp b/services/dtbschedmgr/src/distributed_sched_continuation.cpp old mode 100755 new mode 100644 index 98cf0be1..c445c360 --- a/services/dtbschedmgr/src/distributed_sched_continuation.cpp +++ b/services/dtbschedmgr/src/distributed_sched_continuation.cpp @@ -23,6 +23,7 @@ namespace OHOS { namespace DistributedSchedule { namespace { constexpr int64_t CONTINUATION_DELAY_TIME = 20000; +const std::string TAG = "DSchedContinuation"; } void DSchedContinuation::Init(const FuncContinuationCallback& contCallback) @@ -34,17 +35,17 @@ void DSchedContinuation::Init(const FuncContinuationCallback& contCallback) bool DSchedContinuation::PushAbilityToken(int32_t sessionId, const sptr& abilityToken) { if (abilityToken == nullptr) { - HILOGE("DSchedContinuation::PushAbilityToken abilityToken null!"); + HILOGE("PushAbilityToken abilityToken null!"); return false; } if (sessionId <= 0) { - HILOGE("DSchedContinuation::PushAbilityToken sessionId invalid!"); + HILOGE("PushAbilityToken sessionId invalid!"); return false; } if (continuationHandler_ == nullptr) { - HILOGE("DSchedContinuation::PushAbilityToken not initialized!"); + HILOGE("PushAbilityToken not initialized!"); return false; } @@ -52,13 +53,13 @@ bool DSchedContinuation::PushAbilityToken(int32_t sessionId, const sptrSendEvent(sessionId, 0, CONTINUATION_DELAY_TIME); if (!ret) { - HILOGE("DSchedContinuation::PushAbilityToken SendEvent failed!"); + HILOGE("PushAbilityToken SendEvent failed!"); return false; } auto iterSession = continuationMap_.find(sessionId); if (iterSession != continuationMap_.end()) { - HILOGE("DSchedContinuation::PushAbilityToken sessionId:%{public}d exist!", sessionId); + HILOGE("PushAbilityToken sessionId:%{public}d exist!", sessionId); return false; } (void)continuationMap_.emplace(sessionId, abilityToken); @@ -68,14 +69,14 @@ bool DSchedContinuation::PushAbilityToken(int32_t sessionId, const sptr DSchedContinuation::PopAbilityToken(int32_t sessionId) { if (sessionId <= 0) { - HILOGE("DSchedContinuation::PopAbilityToken sessionId invalid"); + HILOGE("PopAbilityToken sessionId invalid"); return nullptr; } lock_guard autoLock(continuationLock_); auto iter = continuationMap_.find(sessionId); if (iter == continuationMap_.end()) { - HILOGW("DSchedContinuation::PopAbilityToken not found sessionId:%{public}d", sessionId); + HILOGW("PopAbilityToken not found sessionId:%{public}d", sessionId); return nullptr; } sptr abilityToken = iter->second; @@ -99,26 +100,26 @@ int32_t DSchedContinuation::GenerateSessionId() void DSchedContinuation::ContinuationHandler::ProcessEvent(const InnerEvent::Pointer& event) { if (event == nullptr) { - HILOGE("ContinuationHandler::ProcessEvent event nullptr!"); + HILOGE("ProcessEvent event nullptr!"); return; } auto dSchedContinuation = continuationObj_.lock(); if (dSchedContinuation == nullptr) { - HILOGE("ContinuationHandler::ProcessEvent continuation object failed!"); + HILOGE("ProcessEvent continuation object failed!"); return; } auto eventId = event->GetInnerEventId(); int32_t sessionId = static_cast(eventId); if (sessionId <= 0) { - HILOGW("ContinuationHandler::ProcessEvent sessionId invalid!"); + HILOGW("ProcessEvent sessionId invalid!"); return; } auto abilityToken = dSchedContinuation->PopAbilityToken(sessionId); if (abilityToken == nullptr) { - HILOGW("ContinuationHandler::ProcessEvent abilityToken nullptr!"); + HILOGW("ProcessEvent abilityToken nullptr!"); return; } diff --git a/services/dtbschedmgr/src/distributed_sched_dumper.cpp b/services/dtbschedmgr/src/distributed_sched_dumper.cpp old mode 100755 new mode 100644 index 9ff85236..535c3344 --- a/services/dtbschedmgr/src/distributed_sched_dumper.cpp +++ b/services/dtbschedmgr/src/distributed_sched_dumper.cpp @@ -25,6 +25,7 @@ namespace { constexpr size_t MIN_ARGS_SIZE = 1; const std::string ARGS_HELP = "-h"; const std::string ARGS_CONNECT_REMOTE_ABILITY = "-connect"; +const std::string TAG = "DistributedSchedDumper"; constexpr int32_t UID_ROOT = 0; } diff --git a/services/dtbschedmgr/src/distributed_sched_permission.cpp b/services/dtbschedmgr/src/distributed_sched_permission.cpp old mode 100755 new mode 100644 index 1fece57c..deef879d --- a/services/dtbschedmgr/src/distributed_sched_permission.cpp +++ b/services/dtbschedmgr/src/distributed_sched_permission.cpp @@ -28,6 +28,7 @@ using namespace OHOS::Security; namespace OHOS { namespace DistributedSchedule { namespace { +const std::string TAG = "DistributedSchedPermission"; constexpr int32_t ERROR_DUID = -1; constexpr int32_t PERMISSION_GRANTED = 0; } @@ -39,13 +40,13 @@ bool DistributedSchedPermission::CheckCustomPermission(const AppExecFwk::Ability { const auto& permissions = abilityInfo.permissions; if (permissions.empty()) { - HILOGI("CheckCustomPermission no need any permission, so granted!"); + HILOGI("no need any permission, so granted!"); return true; } int32_t duid = callerInfo.duid; if (callerInfo.callerType == CALLER_TYPE_HARMONY) { duid = AllocateDuid(callerInfo.uid, callerInfo.sourceDeviceId); - HILOGD("CheckCustomPermission AllocateDuid uid = %{public}d, duid = %{public}d", callerInfo.uid, duid); + HILOGD("AllocateDuid uid = %{public}d, duid = %{public}d", callerInfo.uid, duid); } if (duid < 0) { HILOGE("CheckCustomPermission duid invalid!"); @@ -61,7 +62,7 @@ bool DistributedSchedPermission::CheckCustomPermission(const AppExecFwk::Ability duid, permission.c_str()); return true; } - HILOGI("CheckCustomPermission duid:%{public}d, permission:%{public}s check failed!", + HILOGI("duid:%{public}d, permission:%{public}s check failed!", duid, permission.c_str()); } return false; @@ -76,7 +77,7 @@ int32_t DistributedSchedPermission::AllocateDuid(int32_t rUid, const std::string int64_t begin = GetTickCount(); auto duid = Permission::DistributedPermissionKit::AllocateDuid(deviceId, rUid); int64_t end = GetTickCount(); - HILOGI("DistributedSchedPermission::AllocateDuid spend:%{public}" PRId64 " ms", (end - begin)); + HILOGI("AllocateDuid spend:%{public}" PRId64 " ms", (end - begin)); return duid; } @@ -113,7 +114,7 @@ bool DistributedSchedPermission::getTargetAbility(const AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, const std::string& localDeviceId, AppExecFwk::AbilityInfo& targetAbility, const CallerInfo& callerInfo) const { - HILOGD("DistributedSchedPermission::getTargetAbility"); + HILOGD("getTargetAbility"); bool result = DistributedSchedAdapter::GetInstance().QueryAbilityInfo(want, targetAbility); if (!result) { HILOGE("getTargetAbility QueryAbilityInfo fail"); diff --git a/services/dtbschedmgr/src/distributed_sched_proxy.cpp b/services/dtbschedmgr/src/distributed_sched_proxy.cpp index 26554266..aec4952b 100644 --- a/services/dtbschedmgr/src/distributed_sched_proxy.cpp +++ b/services/dtbschedmgr/src/distributed_sched_proxy.cpp @@ -27,11 +27,13 @@ using namespace std; using namespace AAFwk; namespace { +const std::string TAG = "DistributedSchedProxy"; const std::u16string DMS_PROXY_INTERFACE_TOKEN = u"ohos.distributedschedule.accessToken"; +constexpr int32_t WAIT_TIME = 15; } int32_t DistributedSchedProxy::StartRemoteAbility(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) + int32_t callerUid, int32_t requestCode) { sptr remote = Remote(); if (remote == nullptr) { @@ -42,7 +44,7 @@ int32_t DistributedSchedProxy::StartRemoteAbility(const OHOS::AAFwk::Want& want, return ERR_FLATTEN_OBJECT; } PARCEL_WRITE_HELPER(data, Parcelable, &want); - PARCEL_WRITE_HELPER(data, Parcelable, &abilityInfo); + PARCEL_WRITE_HELPER(data, Int32, callerUid); PARCEL_WRITE_HELPER(data, Int32, requestCode); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, START_REMOTE_ABILITY, data, reply); @@ -75,7 +77,7 @@ int32_t DistributedSchedProxy::StartAbilityFromRemote(const OHOS::AAFwk::Want& w } int32_t DistributedSchedProxy::StartContinuation(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr& abilityToken) + const sptr& abilityToken, int32_t callerUid) { if (abilityToken == nullptr) { HILOGE("StartContinuation abilityToken null!"); @@ -91,8 +93,8 @@ int32_t DistributedSchedProxy::StartContinuation(const OHOS::AAFwk::Want& want, return ERR_FLATTEN_OBJECT; } PARCEL_WRITE_HELPER(data, Parcelable, &want); - PARCEL_WRITE_HELPER(data, Parcelable, &abilityInfo); PARCEL_WRITE_HELPER(data, RemoteObject, abilityToken); + PARCEL_WRITE_HELPER(data, Int32, callerUid); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, START_CONTINUATION, data, reply); } @@ -132,52 +134,8 @@ int32_t DistributedSchedProxy::NotifyContinuationResultFromRemote(int32_t sessio PARCEL_TRANSACT_SYNC_RET_INT(remote, NOTIFY_CONTINUATION_RESULT_FROM_REMOTE, data, reply); } -int32_t DistributedSchedProxy::RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) -{ - if (abilityToken == nullptr || continuationCallback == nullptr) { - HILOGE("RegisterAbilityToken paramter null!"); - return ERR_NULL_OBJECT; - } - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("RegisterAbilityToken remote service null"); - return ERR_NULL_OBJECT; - } - MessageParcel data; - if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { - return ERR_FLATTEN_OBJECT; - } - PARCEL_WRITE_HELPER(data, RemoteObject, abilityToken); - PARCEL_WRITE_HELPER(data, RemoteObject, continuationCallback); - MessageParcel reply; - PARCEL_TRANSACT_SYNC_RET_INT(remote, REGISTER_ABILITY_TOKEN, data, reply); -} - -int32_t DistributedSchedProxy::UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) -{ - if (abilityToken == nullptr || continuationCallback == nullptr) { - HILOGE("UnregisterAbilityToken paramter null!"); - return ERR_NULL_OBJECT; - } - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("UnregisterAbilityToken remote service null"); - return ERR_NULL_OBJECT; - } - MessageParcel data; - if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { - return ERR_FLATTEN_OBJECT; - } - PARCEL_WRITE_HELPER(data, RemoteObject, abilityToken); - PARCEL_WRITE_HELPER(data, RemoteObject, continuationCallback); - MessageParcel reply; - PARCEL_TRANSACT_SYNC_RET_INT(remote, UNREGISTER_ABILITY_TOKEN, data, reply); -} - int32_t DistributedSchedProxy::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, - const AppExecFwk::AbilityInfo& abilityInfo, const sptr& connect) + const sptr& connect, int32_t callerUid, int32_t callerPid) { if (connect == nullptr) { HILOGE("ConnectRemoteAbility connect is null"); @@ -194,8 +152,9 @@ int32_t DistributedSchedProxy::ConnectRemoteAbility(const OHOS::AAFwk::Want& wan return ERR_FLATTEN_OBJECT; } PARCEL_WRITE_HELPER(data, Parcelable, &want); - PARCEL_WRITE_HELPER(data, Parcelable, &abilityInfo); PARCEL_WRITE_HELPER(data, RemoteObject, connect); + PARCEL_WRITE_HELPER(data, Int32, callerUid); + PARCEL_WRITE_HELPER(data, Int32, callerPid); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, CONNECT_REMOTE_ABILITY, data, reply); } @@ -296,6 +255,270 @@ int32_t DistributedSchedProxy::NotifyProcessDiedFromRemote(const CallerInfo& cal MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, NOTIFY_PROCESS_DIED_FROM_REMOTE, data, reply); } + +int32_t DistributedSchedProxy::PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) +{ + HILOGI("called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("remote system abiity is null"); + return ERR_NULL_OBJECT; + } + + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String16, devId); + PARCEL_WRITE_HELPER(data, Bool, fixConflict); + PARCEL_WRITE_HELPER(data, Int64, tag); + PARCEL_TRANSACT_SYNC_RET_INT(remote, PREPARE_AND_SYNC_MISSIONS, data, reply); +} + +int32_t DistributedSchedProxy::RegisterRemoteMissionListener(const std::u16string& devId, + const sptr& obj) +{ + return ERR_NONE; +} + +int32_t DistributedSchedProxy::UnRegisterRemoteMissionListener(const std::u16string& devId, + const sptr& obj) +{ + return ERR_NONE; +} + +int32_t DistributedSchedProxy::GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos) +{ + HILOGI("called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("remote system abiity is null"); + return ERR_NULL_OBJECT; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String16, Str8ToStr16(deviceId)); + PARCEL_WRITE_HELPER(data, Int32, numMissions); + int32_t ret = remote->SendRequest(GET_MISSION_INFOS, data, reply, option); + if (ret != ERR_NONE) { + HILOGW("sendRequest fail, error: %{public}d", ret); + return ret; + } + return MissionInfo::ReadMissionInfoVectorFromParcel(reply, missionInfos) ? ERR_NONE : ERR_FLATTEN_OBJECT; +} + +int32_t DistributedSchedProxy::NotifyMissionsChangedFromRemote(const std::vector& missionInfos, + const CallerInfo& callerInfo) +{ + HILOGI("NotifyMissionsChangedFromRemote is called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("NotifyMissionsChangedFromRemote remote service is null"); + return ERR_NULL_OBJECT; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, Int32, callerInfo.dmsVersion); + if (!MissionInfo::WriteMissionInfoVectorFromParcel(data, missionInfos)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String, callerInfo.sourceDeviceId); + PARCEL_WRITE_HELPER(data, Int32, callerInfo.uid); + PARCEL_WRITE_HELPER(data, Int32, callerInfo.pid); + PARCEL_WRITE_HELPER(data, Int32, callerInfo.dmsVersion); + MessageParcel reply; + MessageOption option { MessageOption::TF_SYNC, WAIT_TIME }; + int32_t error = remote->SendRequest(NOTIFY_MISSIONS_CHANGED_FROM_REMOTE, data, reply, option); + if (error != ERR_NONE) { + HILOGE("%{public}s transact failed, error: %{public}d", __func__, error); + return error; + } + int32_t result = reply.ReadInt32(); + HILOGD("%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int32_t DistributedSchedProxy::CheckSupportOsd(const std::string& deviceId) +{ + HILOGI("CheckSupportOsd is called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("CheckSupportOsd remote service is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, String, deviceId); + return remote->SendRequest(CHECK_SUPPORTED_OSD, data, reply, option); +} + +void DistributedSchedProxy::GetCachedOsdSwitch(std::vector& deviceIds, std::vector& values) +{ + HILOGI("GetCachedOsdSwitch is called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("GetCachedOsdSwitch remote service is null"); + return; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return; + } + int32_t error = remote->SendRequest(GET_CACHED_SUPPORTED_OSD, data, reply, option); + if (error != ERR_NONE) { + HILOGE("%{public}s transact failed, error: %{public}d", __func__, error); + return; + } + PARCEL_READ_HELPER_NORET(reply, String16Vector, &deviceIds); + PARCEL_READ_HELPER_NORET(reply, Int32Vector, &values); + return; +} + +int32_t DistributedSchedProxy::GetOsdSwitchValueFromRemote() +{ + HILOGI("GetOsdSwitchValueFromRemote is called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("GetOsdSwitchValueFromRemote remote service is null"); + return ERR_NULL_OBJECT; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + MessageParcel reply; + MessageOption option { MessageOption::TF_SYNC, WAIT_TIME }; + int32_t error = remote->SendRequest(CHECK_SUPPORT_OSD_FROM_REMOTE, data, reply, option); + if (error != ERR_NONE) { + HILOGE("%{public}s transact failed, error: %{public}d", __func__, error); + return error; + } + int32_t result = reply.ReadInt32(); + HILOGD("%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +int32_t DistributedSchedProxy::StoreSnapshotInfo(const std::string& deviceId, + int32_t missionId, + const uint8_t* byteStream, + size_t len) +{ + return ERR_NONE; +} + +int32_t DistributedSchedProxy::RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) +{ + return ERR_NONE; +} + +int32_t DistributedSchedProxy::PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) +{ + HILOGI("called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("remote service is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + MessageParcel reply; + MessageOption option { MessageOption::TF_SYNC, WAIT_TIME }; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + if (!CallerInfoMarshalling(callerInfo, data)) { + return ERR_FLATTEN_OBJECT; + } + int32_t error = remote->SendRequest(PREPARE_AND_SYNC_MISSIONS_FROM_REMOTE, data, reply, option); + if (error != ERR_NONE) { + HILOGW("fail, error: %{public}d", error); + return error; + } + int32_t version = reply.ReadInt32(); + HILOGD("version : %{public}d", version); + return MissionInfo::ReadMissionInfoVectorFromParcel(reply, missionInfos) ? ERR_NONE : ERR_FLATTEN_OBJECT; +} + +int32_t DistributedSchedProxy::UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) +{ + HILOGI("called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("remote service is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + MessageParcel reply; + MessageOption option { MessageOption::TF_SYNC, WAIT_TIME }; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + if (!CallerInfoMarshalling(callerInfo, data)) { + return ERR_FLATTEN_OBJECT; + } + int32_t error = remote->SendRequest(UNREGISTER_MISSION_LISTENER_FROM_REMOTE, data, reply, option); + if (error != ERR_NONE) { + HILOGW("sendRequest fail, error: %{public}d", error); + return error; + } + return reply.ReadInt32(); +} + +int32_t DistributedSchedProxy::UpdateOsdSwitchValueFromRemote(int32_t switchVal, + const std::string& sourceDeviceId) +{ + HILOGD("called"); + sptr remote = Remote(); + if (remote == nullptr) { + HILOGE("remote service is null"); + return ERR_NULL_OBJECT; + } + MessageParcel data; + if (!data.WriteInterfaceToken(DMS_PROXY_INTERFACE_TOKEN)) { + return ERR_FLATTEN_OBJECT; + } + PARCEL_WRITE_HELPER(data, Int32, switchVal); + PARCEL_WRITE_HELPER(data, String, sourceDeviceId); + MessageParcel reply; + MessageOption option { MessageOption::TF_SYNC, WAIT_TIME }; + int32_t error = remote->SendRequest(NOTIFY_SWITCH_CHANGED_FROM_REMOTE, data, reply, option); + if (error != ERR_NONE) { + HILOGE("%{public}s transact failed, error: %{public}d", __func__, error); + return error; + } + int32_t result = reply.ReadInt32(); + HILOGD("%{public}s get result from server data = %{public}d", __func__, result); + return result; +} + +bool DistributedSchedProxy::CallerInfoMarshalling(const CallerInfo& callerInfo, MessageParcel& data) +{ + PARCEL_WRITE_HELPER_RET(data, Int32, callerInfo.uid, false); + PARCEL_WRITE_HELPER_RET(data, Int32, callerInfo.pid, false); + PARCEL_WRITE_HELPER_RET(data, Int32, callerInfo.callerType, false); + PARCEL_WRITE_HELPER_RET(data, String, callerInfo.sourceDeviceId, false); + PARCEL_WRITE_HELPER_RET(data, Int32, callerInfo.duid, false); + PARCEL_WRITE_HELPER_RET(data, String, callerInfo.callerAppId, false); + PARCEL_WRITE_HELPER_RET(data, Int32, callerInfo.dmsVersion, false); + return true; +} } // namespace DistributedSchedule } // namespace OHOS diff --git a/services/dtbschedmgr/src/distributed_sched_service.cpp b/services/dtbschedmgr/src/distributed_sched_service.cpp index 41dfb74d..228814fb 100644 --- a/services/dtbschedmgr/src/distributed_sched_service.cpp +++ b/services/dtbschedmgr/src/distributed_sched_service.cpp @@ -19,24 +19,24 @@ #include #include "ability_connection_wrapper_stub.h" +#include "ability_manager_client.h" #include "adapter/dnetwork_adapter.h" #include "bundle/bundle_manager_internal.h" #include "connect_death_recipient.h" +#include "datetime_ex.h" #include "distributed_sched_adapter.h" -#include "distributed_sched_ability_shell.h" +#include "distributed_sched_dumper.h" #include "distributed_sched_permission.h" #include "dtbschedmgr_device_info_storage.h" #include "dtbschedmgr_log.h" -#include "distributed_sched_dumper.h" - -#include "ability_manager_client.h" -#include "datetime_ex.h" #include "element_name.h" +#include "file_ex.h" #include "ipc_skeleton.h" #include "iservice_registry.h" +#include "mission/distributed_sched_mission_manager.h" +#include "mission/mission_info.h" #include "parcel_helper.h" #include "string_ex.h" -#include "file_ex.h" #include "system_ability_definition.h" namespace OHOS { @@ -45,8 +45,8 @@ using namespace AAFwk; using namespace AppExecFwk; namespace { +const std::string TAG = "DistributedSchedService"; const std::u16string CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.abilityshell.DistributedConnection"; - constexpr int32_t BIND_CONNECT_RETRY_TIMES = 3; constexpr int32_t BIND_CONNECT_TIMEOUT = 500; // 500ms constexpr int32_t MAX_DISTRIBUTED_CONNECT_NUM = 600; @@ -74,23 +74,24 @@ void DistributedSchedService::OnStart() }; dschedContinuation_ = std::make_shared(); dschedContinuation_->Init(continuationCallback); - HILOGI("DistributedSchedService::OnStart start service success."); + HILOGI("OnStart start service success."); } bool DistributedSchedService::Init() { - HILOGD("DistributedSchedService::Init ready to init."); + HILOGD("Init ready to init."); + DistributedSchedMissionManager::GetInstance().Init(); bool ret = Publish(this); if (!ret) { - HILOGE("DistributedSchedService::Init Publish failed!"); + HILOGE("Init Publish failed!"); return false; } if (!DtbschedmgrDeviceInfoStorage::GetInstance().Init()) { - HILOGE("DistributedSchedService::Init DtbschedmgrDeviceInfoStorage init failed."); + HILOGE("Init DtbschedmgrDeviceInfoStorage init failed."); } - HILOGD("DistributedSchedService::Init init success."); + HILOGD("Init init success."); DistributedSchedAdapter::GetInstance().Init(); DnetworkAdapter::GetInstance()->Init(); connectDeathRecipient_ = sptr(new ConnectDeathRecipient()); @@ -99,31 +100,35 @@ bool DistributedSchedService::Init() void DistributedSchedService::OnStop() { - HILOGD("DistributedSchedService::OnStop ready to stop service."); + HILOGD("OnStop ready to stop service."); } int32_t DistributedSchedService::StartRemoteAbility(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) + int32_t callerUid, int32_t requestCode) { std::string localDeviceId; std::string deviceId = want.GetElement().GetDeviceID(); if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) { - HILOGE("StartRemoteAbility check deviceId failed"); + HILOGE("check deviceId failed"); + return INVALID_PARAMETERS_ERR; + } + if (IPCSkeleton::GetCallingUid() != SYSTEM_UID) { + HILOGE("check uid failed"); return INVALID_PARAMETERS_ERR; } sptr remoteDms = GetRemoteDms(deviceId); if (remoteDms == nullptr) { - HILOGE("StartRemoteAbility DMS get remoteDms failed"); + HILOGE("get remoteDms failed"); return INVALID_PARAMETERS_ERR; } + AppExecFwk::AbilityInfo abilityInfo; CallerInfo callerInfo; - callerInfo.uid = IPCSkeleton::GetCallingUid(); callerInfo.sourceDeviceId = localDeviceId; - callerInfo.callerType = CALLER_TYPE_HARMONY; + callerInfo.uid = callerUid; AccountInfo accountInfo; - HILOGI("[PerformanceTest] DistributedSchedService StartRemoteAbility transact begin"); + HILOGI("[PerformanceTest] StartRemoteAbility transact begin"); int32_t result = remoteDms->StartAbilityFromRemote(want, abilityInfo, requestCode, callerInfo, accountInfo); - HILOGI("[PerformanceTest] DistributedSchedService StartRemoteAbility transact end"); + HILOGI("[PerformanceTest] StartRemoteAbility transact end"); return result; } @@ -135,31 +140,31 @@ int32_t DistributedSchedService::StartAbilityFromRemote(const OHOS::AAFwk::Want& std::string deviceId = want.GetElement().GetDeviceID(); if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceIdFromRemote(localDeviceId, deviceId, callerInfo.sourceDeviceId)) { - HILOGE("StartAbilityFromRemote check deviceId failed"); + HILOGE("check deviceId failed"); return INVALID_REMOTE_PARAMETERS_ERR; } DistributedSchedPermission& permissionInstance = DistributedSchedPermission::GetInstance(); ErrCode err = permissionInstance.CheckDPermission(want, callerInfo, accountInfo, abilityInfo, deviceId); if (err != ERR_OK) { - HILOGE("StartAbilityFromRemote CheckDPermission denied!!"); + HILOGE("CheckDPermission denied!!"); return err; } err = AAFwk::AbilityManagerClient::GetInstance()->Connect(); if (err != ERR_OK) { - HILOGE("StartAbilityFromRemote connect ability server failed %{public}d", err); + HILOGE("connect ability server failed %{public}d", err); return err; } err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, requestCode); if (err != ERR_OK) { - HILOGE("StartAbilityFromRemote is failed %{public}d", err); + HILOGE("StartAbility failed %{public}d", err); } return err; } int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr& abilityToken) + const sptr& abilityToken, int32_t callerUid) { - HILOGD("[PerformanceTest] DistributedSchedService StartContinuation begin"); + HILOGD("[PerformanceTest] StartContinuation begin"); if (abilityToken == nullptr) { HILOGE("StartContinuation abilityToken is null!"); return INVALID_REMOTE_PARAMETERS_ERR; @@ -169,7 +174,16 @@ int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want HILOGE("StartContinuation want continuation flags invalid!"); return INVALID_REMOTE_PARAMETERS_ERR; } + HILOGD("StartContinuation: devId = %{private}s, bundleName = %{private}s, abilityName = %{private}s", + want.GetElement().GetDeviceID().c_str(), + want.GetElement().GetBundleName().c_str(), + want.GetElement().GetAbilityName().c_str()); + int32_t uid = IPCSkeleton::GetCallingUid(); + if (uid != SYSTEM_UID) { + HILOGE("StartContinuation not allowed!"); + return INVALID_REMOTE_PARAMETERS_ERR; + } std::string devId; if (!GetLocalDeviceId(devId)) { HILOGE("StartContinuation get local deviceId failed!"); @@ -186,9 +200,9 @@ int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want newWant.SetParam("sessionId", sessionId); newWant.SetParam("deviceId", devId); int32_t result = ERR_OK; - result = StartRemoteAbility(newWant, abilityInfo, 0); + result = StartRemoteAbility(newWant, callerUid, 0); if (result != ERR_OK) { - HILOGE("DistributedSchedService:continue ability failed, errorCode = %{public}d", result); + HILOGE("continue ability failed, errorCode = %{public}d", result); return result; } @@ -197,7 +211,7 @@ int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want HILOGW("StartContinuation PushAbilityToken failed!"); return INVALID_REMOTE_PARAMETERS_ERR; } - HILOGD("[PerformanceTest] DistributedSchedService StartContinuation end"); + HILOGD("[PerformanceTest] StartContinuation end"); return result; } @@ -250,22 +264,6 @@ void DistributedSchedService::NotifyContinuationCallbackResult(const sptr& abilityToken, - const sptr& continuationCallback) -{ - return DistributedSchedAbilityShell::GetInstance().RegisterAbilityToken(abilityToken, continuationCallback); -} - -int32_t DistributedSchedService::UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) -{ - return DistributedSchedAbilityShell::GetInstance().UnregisterAbilityToken(abilityToken, continuationCallback); } void DistributedSchedService::RemoteConnectAbilityMappingLocked(const sptr& connect, @@ -343,7 +341,7 @@ int32_t DistributedSchedService::GetUidLocked(const std::list& connect) + const sptr& connect, int32_t callerUid, int32_t callerPid) { std::string localDeviceId; std::string remoteDeviceId = want.GetElement().GetDeviceID(); @@ -351,11 +349,13 @@ int32_t DistributedSchedService::ConnectRemoteAbility(const OHOS::AAFwk::Want& w HILOGE("ConnectRemoteAbility check deviceId failed"); return INVALID_PARAMETERS_ERR; } + if (IPCSkeleton::GetCallingUid() != SYSTEM_UID) { + HILOGE("ConnectRemoteAbility check uid failed"); + return INVALID_PARAMETERS_ERR; + } std::lock_guard autoLock(distributedLock_); - CallerInfo callerInfo = { - IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid(), CALLER_TYPE_HARMONY, localDeviceId - }; + CallerInfo callerInfo = { callerUid, callerPid, CALLER_TYPE_HARMONY, localDeviceId }; int32_t checkResult = CheckDistributedConnectLocked(callerInfo); if (checkResult != ERR_OK) { return checkResult; @@ -372,18 +372,19 @@ int32_t DistributedSchedService::ConnectRemoteAbility(const OHOS::AAFwk::Want& w return INVALID_PARAMETERS_ERR; } - HILOGD("[PerformanceTest] DistributedSchedService::ConnectRemoteAbility begin"); - int32_t result = TryConnectRemoteAbility(want, abilityInfo, connect, callerInfo); + HILOGD("[PerformanceTest] ConnectRemoteAbility begin"); + int32_t result = TryConnectRemoteAbility(want, connect, callerInfo); if (result != ERR_OK) { HILOGE("ConnectRemoteAbility result is %{public}d", result); } - HILOGD("[PerformanceTest] DistributedSchedService::ConnectRemoteAbility end"); + HILOGD("[PerformanceTest] ConnectRemoteAbility end"); return result; } int32_t DistributedSchedService::TryConnectRemoteAbility(const OHOS::AAFwk::Want& want, - const AppExecFwk::AbilityInfo& abilityInfo, const sptr& connect, const CallerInfo& callerInfo) + const sptr& connect, const CallerInfo& callerInfo) { + AppExecFwk::AbilityInfo abilityInfo; AccountInfo accountInfo; std::string remoteDeviceId = want.GetElement().GetDeviceID(); sptr remoteDms = GetRemoteDms(remoteDeviceId); @@ -428,9 +429,9 @@ sptr DistributedSchedService::GetRemoteDms(const std::string& HILOGE("GetRemoteDms failed to connect to systemAbilityMgr!"); return nullptr; } - HILOGD("[PerformanceTest] DistributedSchedService GetRemoteDms begin"); + HILOGD("[PerformanceTest] GetRemoteDms begin"); auto object = samgr->CheckSystemAbility(DISTRIBUTED_SCHED_SA_ID, remoteDeviceId); - HILOGD("[PerformanceTest] DistributedSchedService GetRemoteDms end"); + HILOGD("[PerformanceTest] GetRemoteDms end"); if (object == nullptr) { HILOGE("GetRemoteDms failed to get remote DistributedSched %{private}s", remoteDeviceId.c_str()); return nullptr; @@ -519,7 +520,7 @@ int32_t DistributedSchedService::ConnectAbilityFromRemote(const OHOS::AAFwk::Wan } } int32_t errCode = DistributedSchedAdapter::GetInstance().ConnectAbility(want, callbackWrapper, this); - HILOGD("[PerformanceTest] DistributedSchedService ConnectAbilityFromRemote end"); + HILOGD("[PerformanceTest] ConnectAbilityFromRemote end"); return errCode; } @@ -562,7 +563,7 @@ int32_t DistributedSchedService::DisconnectRemoteAbility(const sptrRemoveDeathRecipient(connectDeathRecipient_); distributedConnectAbilityMap_.erase(it); - HILOGI("remove connect sucess"); + HILOGI("remove connection success"); return ERR_OK; } return NO_CONNECT_CALLBACK_ERR; @@ -576,7 +577,7 @@ int32_t DistributedSchedService::DisconnectAbilityFromRemote(const sptr autoLock(distributedLock_); @@ -632,7 +633,7 @@ int32_t DistributedSchedService::NotifyProcessDiedFromRemote(const CallerInfo& c void DistributedSchedService::ProcessDeviceOffline(const std::string& deviceId) { - HILOGI("DistributedSchedService::ProcessDeviceOffline called"); + HILOGI("ProcessDeviceOffline called"); std::string localDeviceId; if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) { HILOGE("ProcessDeviceOffline check deviceId failed"); @@ -859,5 +860,88 @@ void DistributedSchedService::DumpElementLocked(const std::list& missionInfos) +{ + return DistributedSchedMissionManager::GetInstance().GetMissionInfos(deviceId, numMissions, missionInfos); +} + +int32_t DistributedSchedService::NotifyMissionsChangedFromRemote(const std::vector& missionInfos, + const CallerInfo& callerInfo) +{ + return DistributedSchedMissionManager::GetInstance() + .NotifyMissionsChangedFromRemote(callerInfo, missionInfos); +} + +std::unique_ptr DistributedSchedService::GetRemoteSnapshotInfo(const std::u16string& deviceId, + int32_t missionId) +{ + std::string strDeviceId = Str16ToStr8(deviceId); + HILOGI("GetRemoteSnapShot missionId:%{public}d", missionId); + return DistributedSchedMissionManager::GetInstance().GetRemoteSnapshotInfo(strDeviceId, missionId); +} + +int32_t DistributedSchedService::CheckSupportOsd(const std::string& deviceId) +{ + return DistributedSchedMissionManager::GetInstance().CheckSupportOsd(deviceId); +} + +void DistributedSchedService::GetCachedOsdSwitch(std::vector& deviceIds, std::vector& values) +{ + return DistributedSchedMissionManager::GetInstance().GetCachedOsdSwitch(deviceIds, values); +} + +int32_t DistributedSchedService::GetOsdSwitchValueFromRemote() +{ + return DistributedSchedMissionManager::GetInstance().GetOsdSwitchValueFromRemote(); +} + +int32_t DistributedSchedService::StoreSnapshotInfo(const std::string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) +{ + return DistributedSchedMissionManager::GetInstance().StoreSnapshotInfo(deviceId, missionId, byteStream, len); +} + +int32_t DistributedSchedService::RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) +{ + return DistributedSchedMissionManager::GetInstance().RemoveSnapshotInfo(deviceId, missionId); +} + +int32_t DistributedSchedService::RegisterRemoteMissionListener(const std::u16string& devId, + const sptr& obj) +{ + return DistributedSchedMissionManager::GetInstance().RegisterRemoteMissionListener(devId, obj); +} + +int32_t DistributedSchedService::UnRegisterRemoteMissionListener(const std::u16string& devId, + const sptr& obj) +{ + return DistributedSchedMissionManager::GetInstance().UnRegisterRemoteMissionListener(devId, obj); +} + +int32_t DistributedSchedService::PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) +{ + return DistributedSchedMissionManager::GetInstance().PrepareAndSyncMissionsFromRemote(callerInfo, missionInfos); +} + +int32_t DistributedSchedService::UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) +{ + DistributedSchedMissionManager::GetInstance().UnRegisterMissionListenerFromRemote(callerInfo.sourceDeviceId); + return ERR_NONE; +} + +int32_t DistributedSchedService::UpdateOsdSwitchValueFromRemote(int32_t switchVal, + const std::string& sourceDeviceId) +{ + return DistributedSchedMissionManager::GetInstance() + .UpdateOsdSwitchValueFromRemote(switchVal, sourceDeviceId); +} + +int32_t DistributedSchedService::PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) +{ + return DistributedSchedMissionManager::GetInstance().PrepareAndSyncMissions(devId, fixConflict, tag); +} } // namespace DistributedSchedule } // namespace OHOS \ No newline at end of file diff --git a/services/dtbschedmgr/src/distributed_sched_stub.cpp b/services/dtbschedmgr/src/distributed_sched_stub.cpp index b2ca7368..b3e88420 100644 --- a/services/dtbschedmgr/src/distributed_sched_stub.cpp +++ b/services/dtbschedmgr/src/distributed_sched_stub.cpp @@ -16,13 +16,15 @@ #include "distributed_sched_stub.h" #include "ability_info.h" +#include "adapter/dnetwork_adapter.h" #include "caller_info.h" -#include "distributed_sched_ability_shell.h" -#include "dtbschedmgr_log.h" - #include "datetime_ex.h" +#include "dtbschedmgr_log.h" +#include "dtbschedmgr_device_info_storage.h" +#include "image_source.h" #include "ipc_skeleton.h" #include "message_parcel.h" +#include "mission/distributed_sched_mission_manager.h" #include "parcel_helper.h" namespace OHOS { @@ -33,6 +35,7 @@ using namespace AppExecFwk; namespace { constexpr int32_t HID_HAP = 10000; /* first hap user */ +const std::string TAG = "DistributedSchedStub"; const std::u16string DMS_STUB_INTERFACE_TOKEN = u"ohos.distributedschedule.accessToken"; } @@ -41,10 +44,20 @@ DistributedSchedStub::DistributedSchedStub() localFuncsMap_[START_REMOTE_ABILITY] = &DistributedSchedStub::StartRemoteAbilityInner; localFuncsMap_[START_CONTINUATION] = &DistributedSchedStub::StartContinuationInner; localFuncsMap_[NOTIFY_COMPLETE_CONTINUATION] = &DistributedSchedStub::NotifyCompleteContinuationInner; - localFuncsMap_[REGISTER_ABILITY_TOKEN] = &DistributedSchedStub::RegisterAbilityTokenInner; - localFuncsMap_[UNREGISTER_ABILITY_TOKEN] = &DistributedSchedStub::UnregisterAbilityTokenInner; localFuncsMap_[CONNECT_REMOTE_ABILITY] = &DistributedSchedStub::ConnectRemoteAbilityInner; localFuncsMap_[DISCONNECT_REMOTE_ABILITY] = &DistributedSchedStub::DisconnectRemoteAbilityInner; + // request codes for mission mananger + localFuncsMap_[CHECK_SUPPORTED_OSD] = &DistributedSchedStub::CheckSupportOsdInner; + localFuncsMap_[STORE_SNAPSHOT_INFO] = &DistributedSchedStub::StoreSnapshotInfoInner; + localFuncsMap_[REMOVE_SNAPSHOT_INFO] = &DistributedSchedStub::RemoveSnapshotInfoInner; + localFuncsMap_[GET_REMOTE_SNAPSHOT_INFO] = &DistributedSchedStub::GetRemoteSnapshotInfoInner; + localFuncsMap_[REGISTER_MISSION_LISTENER] = &DistributedSchedStub::RegisterRemoteMissionListenerInner; + localFuncsMap_[UNREGISTER_MISSION_LISTENER] = &DistributedSchedStub::UnRegisterRemoteMissionListenerInner; + localFuncsMap_[GET_MISSION_INFOS] = &DistributedSchedStub::GetMissionInfosInner; + localFuncsMap_[MISSION_CHANGED] = &DistributedSchedStub::NotifyLocalMissionsChangedInner; + localFuncsMap_[PREPARE_AND_SYNC_MISSIONS] = &DistributedSchedStub::PrepareAndSyncMissionsInner; + localFuncsMap_[SWITCH_CHANGED] = &DistributedSchedStub::NotifyOsdSwitchChangedInner; + localFuncsMap_[GET_CACHED_SUPPORTED_OSD] = &DistributedSchedStub::GetCachedOsdSwitchInner; remoteFuncsMap_[START_ABILITY_FROM_REMOTE] = &DistributedSchedStub::StartAbilityFromRemoteInner; remoteFuncsMap_[NOTIFY_CONTINUATION_RESULT_FROM_REMOTE] = @@ -52,6 +65,14 @@ DistributedSchedStub::DistributedSchedStub() remoteFuncsMap_[CONNECT_ABILITY_FROM_REMOTE] = &DistributedSchedStub::ConnectAbilityFromRemoteInner; remoteFuncsMap_[DISCONNECT_ABILITY_FROM_REMOTE] = &DistributedSchedStub::DisconnectAbilityFromRemoteInner; remoteFuncsMap_[NOTIFY_PROCESS_DIED_FROM_REMOTE] = &DistributedSchedStub::NotifyProcessDiedFromRemoteInner; + // request codes for mission mananger + remoteFuncsMap_[CHECK_SUPPORT_OSD_FROM_REMOTE] = &DistributedSchedStub::GetOsdSwitchValueFromRemoteInner; + remoteFuncsMap_[PREPARE_AND_SYNC_MISSIONS_FROM_REMOTE] = + &DistributedSchedStub::PrepareAndSyncMissionsFromRemoteInner; + remoteFuncsMap_[UNREGISTER_MISSION_LISTENER_FROM_REMOTE] = + &DistributedSchedStub::UnRegisterMissionListenerFromRemoteInner; + remoteFuncsMap_[NOTIFY_MISSIONS_CHANGED_FROM_REMOTE] = &DistributedSchedStub::NotifyMissionsChangedFromRemoteInner; + remoteFuncsMap_[NOTIFY_SWITCH_CHANGED_FROM_REMOTE] = &DistributedSchedStub::UpdateOsdSwitchValueFromRemoteInner; } DistributedSchedStub::~DistributedSchedStub() @@ -64,7 +85,7 @@ int32_t DistributedSchedStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) { bool IsLocalCalling = IPCSkeleton::IsLocalCalling(); - HILOGI("DistributedSchedStub::OnRemoteRequest, code = %{public}d, flags = %{public}d, IsLocalCalling = %{public}d.", + HILOGI("OnRemoteRequest, code = %{public}d, flags = %{public}d, IsLocalCalling = %{public}d.", code, option.GetFlags(), IsLocalCalling); const auto& funcsMap = IsLocalCalling ? localFuncsMap_ : remoteFuncsMap_; @@ -72,7 +93,7 @@ int32_t DistributedSchedStub::OnRemoteRequest(uint32_t code, if (iter != funcsMap.end()) { auto func = iter->second; if (!EnforceInterfaceToken(data)) { - HILOGW("DistributedSchedStub::OnRemoteRequest interface token check failed!"); + HILOGW("OnRemoteRequest interface token check failed!"); return DMS_PERMISSION_DENIED; } if (func != nullptr) { @@ -80,7 +101,7 @@ int32_t DistributedSchedStub::OnRemoteRequest(uint32_t code, } } - HILOGW("DistributedSchedStub::OnRemoteRequest default case, need check."); + HILOGW("OnRemoteRequest default case, need check."); return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } @@ -88,18 +109,16 @@ int32_t DistributedSchedStub::StartRemoteAbilityInner(MessageParcel& data, Messa { shared_ptr want(data.ReadParcelable()); if (want == nullptr) { - HILOGW("DistributedSchedStub:: START_ABILITY want readParcelable failed!"); - return ERR_NULL_OBJECT; - } - unique_ptr spAbilityInfo(data.ReadParcelable()); - if (spAbilityInfo == nullptr) { - HILOGW("DistributedSchedStub: StartRemoteAbilityInner AbilityInfo readParcelable failed!"); + HILOGW("START_ABILITY want readParcelable failed!"); return ERR_NULL_OBJECT; } + int32_t callerUid = 0; + PARCEL_READ_HELPER(data, Int32, callerUid); + HILOGI("get callerUid = %{public}d", callerUid); int32_t requestCode = 0; PARCEL_READ_HELPER(data, Int32, requestCode); - int32_t result = StartRemoteAbility(*want, *spAbilityInfo, requestCode); - HILOGI("DistributedSchedStub:: StartRemoteAbilityInner result = %{public}d", result); + int32_t result = StartRemoteAbility(*want, callerUid, requestCode); + HILOGI("StartRemoteAbilityInner result = %{public}d", result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); } @@ -107,12 +126,12 @@ int32_t DistributedSchedStub::StartAbilityFromRemoteInner(MessageParcel& data, M { shared_ptr want(data.ReadParcelable()); if (want == nullptr) { - HILOGW("DistributedSchedStub:: StartAbilityFromRemoteInner want readParcelable failed!"); + HILOGW("want readParcelable failed!"); return ERR_NULL_OBJECT; } unique_ptr cmpAbilityInfo(data.ReadParcelable()); if (cmpAbilityInfo == nullptr) { - HILOGW("DistributedSchedStub: StartAbilityFromRemoteInner AbilityInfo readParcelable failed!"); + HILOGW("AbilityInfo readParcelable failed!"); return ERR_NULL_OBJECT; } AbilityInfo abilityInfo; @@ -131,7 +150,7 @@ int32_t DistributedSchedStub::StartAbilityFromRemoteInner(MessageParcel& data, M PARCEL_READ_HELPER(data, StringVector, &accountInfo.groupIdList); callerInfo.callerAppId = data.ReadString(); int32_t result = StartAbilityFromRemote(*want, abilityInfo, requestCode, callerInfo, accountInfo); - HILOGI("DistributedSchedStub:: StartAbilityFromRemoteInner result = %{public}d", result); + HILOGI("result = %{public}d", result); PARCEL_WRITE_HELPER(reply, Int32, result); int64_t end = GetTickCount(); PARCEL_WRITE_HELPER(reply, Int64, end - begin); @@ -144,17 +163,13 @@ int32_t DistributedSchedStub::StartContinuationInner(MessageParcel& data, Messag { shared_ptr want(data.ReadParcelable()); if (want == nullptr) { - HILOGW("DistributedSchedStub: StartContinuationInner want readParcelable failed!"); - return ERR_NULL_OBJECT; - } - unique_ptr spAbilityInfo(data.ReadParcelable()); - if (spAbilityInfo == nullptr) { - HILOGW("DistributedSchedStub: StartContinuationInner AbilityInfo readParcelable failed!"); + HILOGW("want readParcelable failed!"); return ERR_NULL_OBJECT; } sptr abilityToken = data.ReadRemoteObject(); - int32_t result = StartContinuation(*want, *spAbilityInfo, abilityToken); - HILOGI("DistributedSchedStub: StartContinuationInner result = %{public}d", result); + int32_t callerUid = data.ReadInt32(); + int32_t result = StartContinuation(*want, abilityToken, callerUid); + HILOGI("result = %{public}d", result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); } @@ -163,7 +178,7 @@ int32_t DistributedSchedStub::NotifyCompleteContinuationInner(MessageParcel& dat { u16string devId = data.ReadString16(); if (devId.empty()) { - HILOGE("DistributedSchedStub: NotifyCompleteContinuationInner devId empty!"); + HILOGE("devId is empty!"); return INVALID_PARAMETERS_ERR; } int32_t sessionId = 0; @@ -178,7 +193,7 @@ int32_t DistributedSchedStub::NotifyContinuationResultFromRemoteInner(MessagePar [[maybe_unused]] MessageParcel& reply) { if (!CheckCallingUid()) { - HILOGW("DistributedSchedStub: NotifyContinuationResultFromRemoteInner request DENIED!"); + HILOGW("request DENIED!"); return DMS_PERMISSION_DENIED; } @@ -189,39 +204,22 @@ int32_t DistributedSchedStub::NotifyContinuationResultFromRemoteInner(MessagePar return NotifyContinuationResultFromRemote(sessionId, continuationResult); } -int32_t DistributedSchedStub::RegisterAbilityTokenInner(MessageParcel& data, MessageParcel& reply) -{ - sptr abilityToken = data.ReadRemoteObject(); - sptr continuationCallback = data.ReadRemoteObject(); - int32_t result = RegisterAbilityToken(abilityToken, continuationCallback); - HILOGI("DistributedSchedStub: RegisterAbilityTokenInner result = %{public}d", result); - PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); -} - -int32_t DistributedSchedStub::UnregisterAbilityTokenInner(MessageParcel& data, MessageParcel& reply) -{ - sptr abilityToken = data.ReadRemoteObject(); - sptr continuationCallback = data.ReadRemoteObject(); - int32_t result = UnregisterAbilityToken(abilityToken, continuationCallback); - HILOGI("DistributedSchedStub: UnregisterAbilityTokenInner result = %{public}d", result); - PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); -} - int32_t DistributedSchedStub::ConnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply) { shared_ptr want(data.ReadParcelable()); if (want == nullptr) { - HILOGW("DistributedSchedStub::ConnectRemoteAbilityInner want readParcelable failed!"); - return ERR_NULL_OBJECT; - } - unique_ptr abilityInfo(data.ReadParcelable()); - if (abilityInfo == nullptr) { - HILOGW("DistributedSchedStub::ConnectRemoteAbilityInner abilityInfo readParcelable failed!"); + HILOGW("want readParcelable failed!"); return ERR_NULL_OBJECT; } sptr connect = data.ReadRemoteObject(); - int32_t result = ConnectRemoteAbility(*want, *abilityInfo, connect); - HILOGI("DistributedSchedStub::ConnectRemoteAbilityInner result = %{public}d", result); + int32_t callerUid = 0; + PARCEL_READ_HELPER(data, Int32, callerUid); + HILOGI("get callerUid = %{public}d", callerUid); + int32_t callerPid = 0; + PARCEL_READ_HELPER(data, Int32, callerPid); + HILOGI("get callerPid = %{public}d", callerPid); + int32_t result = ConnectRemoteAbility(*want, connect, callerUid, callerPid); + HILOGI("result = %{public}d", result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); } @@ -229,25 +227,25 @@ int32_t DistributedSchedStub::DisconnectRemoteAbilityInner(MessageParcel& data, { sptr connect = data.ReadRemoteObject(); int32_t result = DisconnectRemoteAbility(connect); - HILOGI("DistributedSchedStub::DisconnectRemoteAbilityInner result = %{public}d", result); + HILOGI("result = %{public}d", result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); } int32_t DistributedSchedStub::ConnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply) { if (!CheckCallingUid()) { - HILOGW("DistributedSchedStub::ConnectAbilityFromRemoteInner request DENIED!"); + HILOGW("request DENIED!"); return DMS_PERMISSION_DENIED; } shared_ptr want(data.ReadParcelable()); if (want == nullptr) { - HILOGW("DistributedSchedStub::ConnectAbilityFromRemoteInner want readParcelable failed!"); + HILOGW("want readParcelable failed!"); return ERR_NULL_OBJECT; } unique_ptr cmpAbilityInfo(data.ReadParcelable()); if (cmpAbilityInfo == nullptr) { - HILOGW("DistributedSchedStub::ConnectAbilityFromRemoteInner abilityInfo readParcelable failed!"); + HILOGW("abilityInfo readParcelable failed!"); return ERR_NULL_OBJECT; } AbilityInfo abilityInfo; @@ -266,7 +264,7 @@ int32_t DistributedSchedStub::ConnectAbilityFromRemoteInner(MessageParcel& data, std::string deviceId = abilityInfo.deviceId; int64_t begin = GetTickCount(); int32_t result = ConnectAbilityFromRemote(*want, abilityInfo, connect, callerInfo, accountInfo); - HILOGW("DistributedSchedStub::ConnectAbilityFromRemoteInner result = %{public}d", result); + HILOGW("result = %{public}d", result); int64_t end = GetTickCount(); PARCEL_WRITE_HELPER(reply, Int32, result); PARCEL_WRITE_HELPER(reply, Int64, end - begin); @@ -278,7 +276,7 @@ int32_t DistributedSchedStub::ConnectAbilityFromRemoteInner(MessageParcel& data, int32_t DistributedSchedStub::DisconnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply) { if (!CheckCallingUid()) { - HILOGW("DistributedSchedStub::DisconnectAbilityFromRemoteInner request DENIED!"); + HILOGW("request DENIED!"); return DMS_PERMISSION_DENIED; } @@ -288,14 +286,14 @@ int32_t DistributedSchedStub::DisconnectAbilityFromRemoteInner(MessageParcel& da string sourceDeviceId; PARCEL_READ_HELPER(data, String, sourceDeviceId); int32_t result = DisconnectAbilityFromRemote(connect, uid, sourceDeviceId); - HILOGI("DistributedSchedStub::DisconnectAbilityFromRemoteInner result %{public}d", result); + HILOGI("result %{public}d", result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); } int32_t DistributedSchedStub::NotifyProcessDiedFromRemoteInner(MessageParcel& data, MessageParcel& reply) { if (!CheckCallingUid()) { - HILOGW("DistributedSchedStub::NotifyProcessDiedFromRemoteInner request DENIED!"); + HILOGW("request DENIED!"); return DMS_PERMISSION_DENIED; } @@ -311,7 +309,7 @@ int32_t DistributedSchedStub::NotifyProcessDiedFromRemoteInner(MessageParcel& da callerInfo.sourceDeviceId = sourceDeviceId; callerInfo.callerType = CALLER_TYPE_HARMONY; int32_t result = NotifyProcessDiedFromRemote(callerInfo); - HILOGI("DistributedSchedStub::NotifyProcessDiedFromRemoteInner result %{public}d", result); + HILOGI("result %{public}d", result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); } @@ -327,5 +325,278 @@ bool DistributedSchedStub::EnforceInterfaceToken(MessageParcel& data) u16string interfaceToken = data.ReadInterfaceToken(); return interfaceToken == DMS_STUB_INTERFACE_TOKEN; } + +int32_t DistributedSchedStub::GetMissionInfosInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + std::u16string deviceId = data.ReadString16(); + int32_t numMissions = 0; + PARCEL_READ_HELPER(data, Int32, numMissions); + + std::vector missionInfos; + int result = GetMissionInfos(Str16ToStr8(deviceId), numMissions, missionInfos); + HILOGI("result = %{public}d", result); + if (result == ERR_NONE) { + return MissionInfo::WriteMissionInfoVectorFromParcel(reply, missionInfos) ? ERR_NONE : ERR_FLATTEN_OBJECT; + } + return ERR_NULL_OBJECT; +} + +int32_t DistributedSchedStub::GetRemoteSnapshotInfoInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + u16string deviceId = data.ReadString16(); + int32_t missionId = 0; + PARCEL_READ_HELPER(data, Int32, missionId); + if (deviceId.empty()) { + HILOGE("deviceId is empty!"); + return ERR_FLATTEN_OBJECT; + } + unique_ptr snapShot = GetRemoteSnapshotInfo(deviceId, missionId); + if (snapShot == nullptr) { + HILOGE("snapShot object nullptr!"); + return ERR_NULL_OBJECT; + } + bool ret = snapShot->WriteToParcel(reply); + if (!ret) { + HILOGE("snapShot WriteToParcel failed!"); + return ERR_NULL_OBJECT; + } + std::string uuid = DnetworkAdapter::GetInstance()->GetUuidByNetworkId(Str16ToStr8(deviceId)); + if (uuid.empty()) { + HILOGE("uuid is empty!"); + return ERR_NULL_OBJECT; + } + DistributedSchedMissionManager::GetInstance().EnqueueCachedSnapshotInfo(uuid, + missionId, std::move(snapShot)); + return ERR_NONE; +} + +int32_t DistributedSchedStub::RegisterRemoteMissionListenerInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + if (!EnforceInterfaceToken(data)) { + HILOGW("RegisterRemoteMissionListenerInner interface token check failed!"); + return DMS_PERMISSION_DENIED; + } + u16string devId = data.ReadString16(); + if (devId.empty()) { + HILOGW("read deviceId failed!"); + return ERR_FLATTEN_OBJECT; + } + sptr missionChangedListener = data.ReadRemoteObject(); + if (missionChangedListener == nullptr) { + HILOGW("read IRemoteObject failed!"); + return ERR_FLATTEN_OBJECT; + } + int32_t result = RegisterRemoteMissionListener(devId, missionChangedListener); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +int32_t DistributedSchedStub::PrepareAndSyncMissionsFromRemoteInner(MessageParcel& data, MessageParcel& reply) +{ + CallerInfo callerInfo; + if (!CallerInfoUnmarshalling(callerInfo, data)) { + HILOGW("read callerInfo failed!"); + return ERR_FLATTEN_OBJECT; + } + std::vector missionInfos; + if (PrepareAndSyncMissionsFromRemote(callerInfo, missionInfos) != ERR_NONE) { + return ERR_FLATTEN_OBJECT; + } + if (!reply.WriteInt32(VERSION)) { + return ERR_FLATTEN_OBJECT; + } + if (!MissionInfo::WriteMissionInfoVectorFromParcel(reply, missionInfos)) { + HILOGE("write mission info failed!"); + return ERR_FLATTEN_OBJECT; + } + return ERR_NONE; +} + +int32_t DistributedSchedStub::UnRegisterRemoteMissionListenerInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + u16string devId = data.ReadString16(); + if (devId.empty()) { + HILOGW("read deviceId failed!"); + return ERR_FLATTEN_OBJECT; + } + sptr missionChangedListener = data.ReadRemoteObject(); + if (missionChangedListener == nullptr) { + HILOGW("read IRemoteObject failed!"); + return ERR_FLATTEN_OBJECT; + } + int32_t result = UnRegisterRemoteMissionListener(devId, missionChangedListener); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +int32_t DistributedSchedStub::UnRegisterMissionListenerFromRemoteInner(MessageParcel& data, MessageParcel& reply) +{ + CallerInfo callerInfo; + if (!CallerInfoUnmarshalling(callerInfo, data)) { + HILOGW("read callerInfo failed!"); + return ERR_FLATTEN_OBJECT; + } + int32_t result = UnRegisterMissionListenerFromRemote(callerInfo); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +int32_t DistributedSchedStub::CheckSupportOsdInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + int64_t begin = GetTickCount(); + std::u16string deviceId = data.ReadString16(); + std::string u8DeviceId = Str16ToStr8(deviceId); + int32_t result = CheckSupportOsd(u8DeviceId); + HILOGI("result = %{public}d, deviceId = %{public}s spend %{public}" PRId64 " ms", + result, DnetworkAdapter::AnonymizeDeviceId(u8DeviceId).c_str(), GetTickCount() - begin); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +int32_t DistributedSchedStub::GetCachedOsdSwitchInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + std::vector deviceIds; + std::vector values; + int64_t begin = GetTickCount(); + GetCachedOsdSwitch(deviceIds, values); + HILOGI("spend %{public}" PRId64 " ms", GetTickCount() - begin); + PARCEL_WRITE_HELPER(reply, String16Vector, deviceIds); + PARCEL_WRITE_HELPER(reply, Int32Vector, values); + return ERR_NONE; +} + +int32_t DistributedSchedStub::NotifyLocalMissionsChangedInner(MessageParcel& data, MessageParcel& reply) +{ + std::vector missionInfos; + if (!MissionInfo::ReadMissionInfoVectorFromParcel(data, missionInfos)) { + return ERR_FLATTEN_OBJECT; + } + int32_t result = DistributedSchedMissionManager::GetInstance().NotifyMissionsChangedToRemote(missionInfos); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +int32_t DistributedSchedStub::NotifyMissionsChangedFromRemoteInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t version = data.ReadInt32(); + HILOGD("version is %{public}d", version); + std::vector missionInfos; + if (!MissionInfo::ReadMissionInfoVectorFromParcel(data, missionInfos)) { + return ERR_FLATTEN_OBJECT; + } + CallerInfo callerInfo; + callerInfo.sourceDeviceId = data.ReadString(); + callerInfo.uid = data.ReadInt32(); + callerInfo.pid = data.ReadInt32(); + callerInfo.dmsVersion = data.ReadInt32(); + int32_t result = NotifyMissionsChangedFromRemote(missionInfos, callerInfo); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +int32_t DistributedSchedStub::GetOsdSwitchValueFromRemoteInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t result = GetOsdSwitchValueFromRemote(); + HILOGI("result = %{public}d", result); + PARCEL_WRITE_HELPER(reply, Int32, result); + return ERR_NONE; +} + +int32_t DistributedSchedStub::StoreSnapshotInfoInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + int32_t missionId = 0; + if (!data.ReadInt32(missionId)) { + return ERR_FLATTEN_OBJECT; + } + size_t len = data.GetReadableBytes(); + const uint8_t* byteSteam = data.ReadBuffer(len); + std::string deviceId; + DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(deviceId); + if (deviceId.empty()) { + HILOGE("get deviceId failed!"); + return INVALID_PARAMETERS_ERR; + } + int32_t result = StoreSnapshotInfo(deviceId, missionId, byteSteam, len); + PARCEL_WRITE_HELPER(reply, Int32, result); + return ERR_NONE; +} + +int32_t DistributedSchedStub::RemoveSnapshotInfoInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest] called, IPC end = %{public}" PRId64, GetTickCount()); + int32_t missionId = 0; + if (!data.ReadInt32(missionId)) { + return ERR_FLATTEN_OBJECT; + } + std::string deviceId; + DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(deviceId); + if (deviceId.empty()) { + HILOGE("get deviceId failed!"); + return INVALID_PARAMETERS_ERR; + } + int32_t result = RemoveSnapshotInfo(deviceId, missionId); + PARCEL_WRITE_HELPER(reply, Int32, result); + return ERR_NONE; +} + +int32_t DistributedSchedStub::NotifyOsdSwitchChangedInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t result = DistributedSchedMissionManager::GetInstance().UpdateSwitchValueToRemote(); + HILOGI("result: %{public}d!", result); + return ERR_NONE; +} + +int32_t DistributedSchedStub::UpdateOsdSwitchValueFromRemoteInner(MessageParcel& data, MessageParcel& reply) +{ + int32_t switchVal = data.ReadInt32(); + std::string srcUuid = data.ReadString(); + int32_t result = UpdateOsdSwitchValueFromRemote(switchVal, srcUuid); + HILOGD("srcUuid: %s, result: %d!", + srcUuid.c_str(), result); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +int32_t DistributedSchedStub::PrepareAndSyncMissionsInner(MessageParcel& data, MessageParcel& reply) +{ + HILOGI("[PerformanceTest], IPC end = %{public}" PRId64, GetTickCount()); + u16string devId = data.ReadString16(); + bool fixConflict = data.ReadBool(); + long tag = data.ReadInt64(); + if (devId.empty()) { + HILOGW("read deviceId failed!"); + return ERR_FLATTEN_OBJECT; + } + int32_t result = PrepareAndSyncMissions(devId, fixConflict, tag); + PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); +} + +bool DistributedSchedStub::CallerInfoUnmarshalling(CallerInfo& callerInfo, MessageParcel& data) +{ + int32_t uid = -1; + PARCEL_READ_HELPER_RET(data, Int32, uid, false); + int32_t pid = -1; + PARCEL_READ_HELPER_RET(data, Int32, pid, false); + int32_t callerType = CALLER_TYPE_NONE; + PARCEL_READ_HELPER_RET(data, Int32, callerType, false); + std::string sourceDeviceId; + PARCEL_READ_HELPER_RET(data, String, sourceDeviceId, false); + HILOGI("sourceDeviceId = %{public}s", + DnetworkAdapter::AnonymizeDeviceId(sourceDeviceId).c_str()); + int32_t duid = -1; + PARCEL_READ_HELPER_RET(data, Int32, duid, false); + std::string callerAppId; + PARCEL_READ_HELPER_RET(data, String, callerAppId, false); + int32_t version = -1; + PARCEL_READ_HELPER_RET(data, Int32, version, false); + callerInfo.uid = uid; + callerInfo.pid = pid; + callerInfo.callerType = callerType; + callerInfo.sourceDeviceId = sourceDeviceId; + callerInfo.duid = duid; + callerInfo.callerAppId = callerAppId; + callerInfo.dmsVersion = version; + return true; +} } // namespace DistributedSchedule } // namespace OHOS diff --git a/services/dtbschedmgr/src/dtbschedmgr_device_info_storage.cpp b/services/dtbschedmgr/src/dtbschedmgr_device_info_storage.cpp old mode 100755 new mode 100644 index d715af60..3d356177 --- a/services/dtbschedmgr/src/dtbschedmgr_device_info_storage.cpp +++ b/services/dtbschedmgr/src/dtbschedmgr_device_info_storage.cpp @@ -25,17 +25,18 @@ #include "ipc_object_proxy.h" #include "ipc_skeleton.h" #include "iservice_registry.h" +#include "mission/distributed_sched_mission_manager.h" #include "system_ability_definition.h" +using namespace std; namespace OHOS { namespace DistributedSchedule { using namespace std::chrono_literals; namespace { constexpr int32_t RETRY_TIMES = 30; -constexpr int32_t NON_ANONYMIZE_LENGTH = 6; -const std::string EMPTY_DEVICE_ID = ""; constexpr int32_t CONNECT_SOFTBUS_RETRY_TIMES = 60; +const std::string TAG = "DtbschedmgrDeviceInfoStorage"; } IMPLEMENT_SINGLE_INSTANCE(DtbschedmgrDeviceInfoStorage); @@ -48,17 +49,18 @@ bool DtbschedmgrDeviceInfoStorage::Init() } auto func = [this]() { - HILOGI("DtbschedmgrDeviceInfoStorage begin connect softbus"); + HILOGI("begin connect softbus"); for (int32_t retryTimes = 0; retryTimes <= CONNECT_SOFTBUS_RETRY_TIMES; retryTimes++) { if (ConnectSoftbus()) { return; } - HILOGE("DtbschedmgrDeviceInfoStorage retry connect softbus %{public}d times", retryTimes); + HILOGE("retry connect softbus %{public}d times", retryTimes); std::this_thread::sleep_for(1s); } + HILOGE("connect softbus 60times * 30s, error!!"); }; if (!initHandler_->PostTask(func)) { - HILOGE("DtbschedmgrDeviceInfoStorage::Init handler postTask failed"); + HILOGE("Init handler postTask failed"); return false; } return true; @@ -66,35 +68,36 @@ bool DtbschedmgrDeviceInfoStorage::Init() bool DtbschedmgrDeviceInfoStorage::ConnectSoftbus() { + ClearAllDevices(); bool isReady = WaitForDnetworkReady(); if (!isReady) { - HILOGE("DtbschedmgrDeviceInfoStorage::ConnectSoftbus wait Dnetwork failed!"); + HILOGE("ConnectSoftbus wait Dnetwork failed!"); return false; } std::shared_ptr dnetworkAdapter = DnetworkAdapter::GetInstance(); if (dnetworkAdapter == nullptr) { - HILOGE("DtbschedmgrDeviceInfoStorage DnetworkAdapter::GetInstance() null"); + HILOGE("DnetworkAdapter::GetInstance() null"); return false; } - if (!InitNodeIdManager(dnetworkAdapter)) { - HILOGE("DtbschedmgrDeviceInfoStorage::InitNodeIdManager failed"); + if (!InitNetworkIdManager(dnetworkAdapter)) { + HILOGE("InitNetworkIdManager failed"); return false; } - HILOGI("DtbschedmgrDeviceInfoStorage::ConnectSoftbus success"); + HILOGI("ConnectSoftbus success"); return true; } -bool DtbschedmgrDeviceInfoStorage::InitNodeIdManager(std::shared_ptr dnetworkAdapter) +bool DtbschedmgrDeviceInfoStorage::InitNetworkIdManager(std::shared_ptr dnetworkAdapter) { - if (nodeIdMgrHandler_ == nullptr) { - auto runner = AppExecFwk::EventRunner::Create("DmsNodeIdManager"); - nodeIdMgrHandler_ = std::make_shared(runner); + if (networkIdMgrHandler_ == nullptr) { + auto runner = AppExecFwk::EventRunner::Create("DmsNetworkIdManager"); + networkIdMgrHandler_ = std::make_shared(runner); } deviceNodeListener_ = std::make_shared(); if (!dnetworkAdapter->AddDeviceChangeListener(deviceNodeListener_)) { - HILOGE("DtbschedmgrDeviceInfoStorage::AddDeviceChangeListener failed"); deviceNodeListener_ = nullptr; + HILOGE("AddDeviceChangeListener failed!"); return false; } return true; @@ -102,9 +105,10 @@ bool DtbschedmgrDeviceInfoStorage::InitNodeIdManager(std::shared_ptrRemoveDeviceChangeListener(deviceNodeListener_); - deviceNodeListener_= nullptr; + deviceNodeListener_ = nullptr; } } @@ -125,16 +129,43 @@ bool DtbschedmgrDeviceInfoStorage::WaitForDnetworkReady() return true; } } - HILOGI("DtbschedmgrDeviceInfoStorage::Waiting for dnentwork service..."); + HILOGI("Waiting for dnentwork service..."); std::this_thread::sleep_for(1s); if (--retryTimeout <= 0) { - HILOGI("DtbschedmgrDeviceInfoStorage::Waiting for dnentwork service timeout(30)s"); + HILOGI("Waiting for dnentwork service timeout(30)s"); return false; } } while (true); return false; } +void DtbschedmgrDeviceInfoStorage::RegisterUuidNetworkIdMap(const std::string& networkId) +{ + std::string uuid = DnetworkAdapter::GetInstance()->GetUuidByNetworkId(networkId); + { + std::lock_guard autoLock(uuidNetworkIdLock_); + uuidNetworkIdMap_[uuid] = networkId; + } +} + +void DtbschedmgrDeviceInfoStorage::UnregisterUuidNetworkIdMap(const std::string& networkId) +{ + std::string uuid = DnetworkAdapter::GetInstance()->GetUuidByNetworkId(networkId); + { + std::lock_guard autoLock(uuidNetworkIdLock_); + uuidNetworkIdMap_.erase(uuid); + } +} + +void DtbschedmgrDeviceInfoStorage::GetDeviceIdSet(std::set& deviceIdSet) +{ + deviceIdSet.clear(); + lock_guard autoLock(deviceLock_); + for (const auto& device : remoteDevices_) { + deviceIdSet.emplace(device.first); + } +} + bool DtbschedmgrDeviceInfoStorage::GetLocalDeviceId(std::string& deviceId) { return GetLocalDeviceFromDnet(deviceId); @@ -144,82 +175,143 @@ bool DtbschedmgrDeviceInfoStorage::GetLocalDeviceFromDnet(std::string& deviceId) { auto dnetworkAdapter = DnetworkAdapter::GetInstance(); if (dnetworkAdapter == nullptr) { - HILOGE("DtbschedmgrDeviceInfoStorage::GetLocalDeviceFromDnet dnetworkAdapter null"); + HILOGE("GetLocalDeviceFromDnet dnetworkAdapter null"); return false; } std::shared_ptr localNode = dnetworkAdapter->GetLocalBasicInfo(); if (localNode != nullptr) { deviceId = localNode->networkId; HILOGI("get local deviceId from DnetworkAdapter, deviceId = %{public}s", - AnonymizeDeviceId(deviceId).c_str()); + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); return true; } - HILOGE("DtbschedmgrDeviceInfoStorage::GetLocalDeviceFromDnet localNode null"); + HILOGE("GetLocalDeviceFromDnet localNode null"); return false; } -std::string DtbschedmgrDeviceInfoStorage::AnonymizeDeviceId(const std::string& deviceId) +void DtbschedmgrDeviceInfoStorage::ClearAllDevices() { - if (deviceId.length() < NON_ANONYMIZE_LENGTH) { - return EMPTY_DEVICE_ID; - } - std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH); - anonDeviceId.append("******"); - return anonDeviceId; + lock_guard autoLock(deviceLock_); + remoteDevices_.clear(); } +std::shared_ptr DtbschedmgrDeviceInfoStorage::GetDeviceInfoById(const string& deviceId) +{ + lock_guard autoLock(deviceLock_); + auto iter = remoteDevices_.find(deviceId); + if (iter == remoteDevices_.end()) { + return nullptr; + } + return iter->second; +} + +std::string DtbschedmgrDeviceInfoStorage::GetUuidByNetworkId(const std::string& networkId) +{ + if (networkId.empty()) { + HILOGW("GetUuidByNetworkId networkId empty!"); + return ""; + } + { + std::lock_guard autoLock(uuidNetworkIdLock_); + auto iter = uuidNetworkIdMap_.begin(); + while (iter != uuidNetworkIdMap_.end()) { + if (iter->second == networkId) { + return iter->first; + } else { + ++iter; + } + } + } + std::string uuid = DnetworkAdapter::GetInstance()->GetUuidByNetworkId(networkId); + return uuid; +} + +std::string DtbschedmgrDeviceInfoStorage::GetNetworkIdByUuid(const std::string& uuid) +{ + if (uuid.empty()) { + HILOGW("GetNetworkIdByUuid uuid empty!"); + return ""; + } + { + std::lock_guard autoLock(uuidNetworkIdLock_); + auto iter = uuidNetworkIdMap_.find(uuid); + if (iter != uuidNetworkIdMap_.end()) { + return iter->second; + } + return ""; + } +} void DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify(const std::shared_ptr devInfo) { if (devInfo == nullptr) { - HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify devInfo null"); + HILOGE("DeviceOnlineNotify devInfo null"); return; } std::string devId = devInfo->GetDeviceId(); - HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify deviceId = %{public}s", - AnonymizeDeviceId(devId).c_str()); + HILOGI("DeviceOnlineNotify deviceId = %{public}s", + DnetworkAdapter::AnonymizeDeviceId(devId).c_str()); - if (nodeIdMgrHandler_ == nullptr) { - HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify nodeIdMgrHandler null"); + if (networkIdMgrHandler_ == nullptr) { + HILOGE("DeviceOnlineNotify networkIdMgrHandler null"); return; } auto nodeOnline = [this, devInfo]() { - HILOGI("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify called"); std::string deviceId = devInfo->GetDeviceId(); + RegisterUuidNetworkIdMap(deviceId); + std::string uuid = GetUuidByNetworkId(deviceId); + HILOGI("DeviceOnlineNotify process deviceId = %{public}s, uuid = %{public}s, deviceName = %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str(), + DnetworkAdapter::AnonymizeDeviceId(uuid).c_str(), devInfo->GetDeviceName().c_str()); DistributedSchedAdapter::GetInstance().DeviceOnline(deviceId); + DistributedSchedMissionManager::GetInstance().UpdateConnCapSupportOsd(deviceId); + DistributedSchedMissionManager::GetInstance().DeviceOnlineNotify(deviceId); + { + lock_guard autoLock(deviceLock_); + remoteDevices_[deviceId] = devInfo; + } + DistributedSchedMissionManager::GetInstance().UpdateSwitchValueToRemote(); }; - if (!nodeIdMgrHandler_->PostTask(nodeOnline)) { - HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify handler postTask failed"); + if (!networkIdMgrHandler_->PostTask(nodeOnline)) { + HILOGE("DeviceOnlineNotify handler postTask failed"); } } void DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify(const std::string& deviceId) { if (deviceId.empty()) { - HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify deviceId empty"); + HILOGE("DeviceOfflineNotify deviceId empty"); return; } - if (nodeIdMgrHandler_ == nullptr) { - HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify nodeIdMgrHandler null"); + HILOGI("DeviceOfflineNotify deviceId = %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + if (networkIdMgrHandler_ == nullptr) { + HILOGE("DeviceOfflineNotify networkIdMgrHandler null"); return; } auto nodeOffline = [this, deviceId]() { - HILOGI("DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify called"); + std::string uuid = GetUuidByNetworkId(deviceId); + HILOGI("DeviceOfflineNotify process deviceId = %{public}s, uuid = %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str(), DnetworkAdapter::AnonymizeDeviceId(uuid).c_str()); DistributedSchedAdapter::GetInstance().DeviceOffline(deviceId); + DistributedSchedMissionManager::GetInstance().DeviceOfflineNotify(deviceId); + UnregisterUuidNetworkIdMap(deviceId); + lock_guard autoLock(deviceLock_); + remoteDevices_.erase(deviceId); }; - if (!nodeIdMgrHandler_->PostTask(nodeOffline)) { - HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify handler postTask failed"); + if (!networkIdMgrHandler_->PostTask(nodeOffline)) { + HILOGE("DeviceOfflineNotify handler postTask failed"); } } void DtbschedmgrDeviceInfoStorage::OnDeviceInfoChanged(const std::string& deviceId, DeviceInfoType type) { - HILOGI("DtbschedmgrDeviceInfoStorage::OnDeviceInfoChanged called"); + HILOGI("OnDeviceInfoChanged called"); } void DnetServiceDeathRecipient::OnRemoteDied(const wptr& remote) { - HILOGI("DnetServiceDeathRecipient::OnRemoteDied dnetwork service died"); + HILOGI("OnRemoteDied dnetwork service died"); DtbschedmgrDeviceInfoStorage::GetInstance().Init(); } } -} \ No newline at end of file +} diff --git a/services/dtbschedmgr/src/mission/distributed_data_change_listener.cpp b/services/dtbschedmgr/src/mission/distributed_data_change_listener.cpp new file mode 100644 index 00000000..24ca50f9 --- /dev/null +++ b/services/dtbschedmgr/src/mission/distributed_data_change_listener.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mission/distributed_data_change_listener.h" + +#include +#include "dtbschedmgr_device_info_storage.h" +#include "dtbschedmgr_log.h" +#include "mission/distributed_sched_mission_manager.h" +#include "string_ex.h" + +using namespace std; +using namespace OHOS::DistributedKv; + +namespace OHOS { +namespace DistributedSchedule { +namespace { +const std::string TAG = "DistributedDataChangeListener"; + +struct KeyInfo { + std::string devId; + int32_t missionId = 0; + static constexpr int32_t MAX_SPLIT_VARS = 2; + static std::unique_ptr ParseInfo(const std::string& strKey) + { + std::vector strVector; + SplitStr(strKey, "_", strVector); + if (strVector.size() != MAX_SPLIT_VARS) { + HILOGI("ParseInfo key invalid!"); + return nullptr; + } + int32_t index = 0; + auto keyInfo = std::make_unique(); + keyInfo->devId = strVector[index++]; + int32_t iValue = 0; + bool ret = StrToInt(strVector[index], iValue); + if (!ret) { + HILOGI("ParseInfo key missionId invalid!"); + return nullptr; + } + keyInfo->missionId = iValue; + return keyInfo; + } +}; +} +void DistributedDataChangeListener::OnChange(const DistributedKv::ChangeNotification &appChangeNotification) +{ + HILOGI("OnChange"); + const vector inserts = appChangeNotification.GetInsertEntries(); + for (const auto& entry : inserts) { + unique_ptr keyInfo = KeyInfo::ParseInfo(entry.key.ToString()); + if (keyInfo != nullptr) { + std::string keyStr = DnetworkAdapter::AnonymizeDeviceId(keyInfo->devId) + "_" + + std::to_string(keyInfo->missionId); + HILOGI("insertEntries Key:%{public}s, Value:%{public}s", + keyStr.c_str(), entry.value.ToString().c_str()); + std::string networkId = DtbschedmgrDeviceInfoStorage::GetInstance().GetNetworkIdByUuid(keyInfo->devId); + if (networkId.empty()) { + HILOGE("OnChange networkId empty!"); + return; + } + DistributedSchedMissionManager::GetInstance().NotifySnapshotChanged(networkId, keyInfo->missionId); + } + } + + const vector deletes = appChangeNotification.GetDeleteEntries(); + for (const auto& entry : deletes) { + unique_ptr keyInfo = KeyInfo::ParseInfo(entry.key.ToString()); + if (keyInfo != nullptr) { + std::string keyStr = DnetworkAdapter::AnonymizeDeviceId(keyInfo->devId) + "_" + + std::to_string(keyInfo->missionId); + HILOGI("deleteEntries Key:%{public}s, Value:%{public}s", + keyStr.c_str(), entry.value.ToString().c_str()); + (void)DistributedSchedMissionManager::GetInstance().DequeueCachedSnapshotInfo(keyInfo->devId, + keyInfo->missionId); + } + } + + const vector updates = appChangeNotification.GetUpdateEntries(); + for (const auto& entry : updates) { + unique_ptr keyInfo = KeyInfo::ParseInfo(entry.key.ToString()); + if (keyInfo != nullptr) { + std::string keyStr = DnetworkAdapter::AnonymizeDeviceId(keyInfo->devId) + "_" + + std::to_string(keyInfo->missionId); + HILOGI("updateEntries Key:%{public}s, Value:%{public}s", + keyStr.c_str(), entry.value.ToString().c_str()); + std::string networkId = DtbschedmgrDeviceInfoStorage::GetInstance().GetNetworkIdByUuid(keyInfo->devId); + if (networkId.empty()) { + HILOGE("OnChange networkId empty!"); + return; + } + DistributedSchedMissionManager::GetInstance().DequeueCachedSnapshotInfo(keyInfo->devId, keyInfo->missionId); + DistributedSchedMissionManager::GetInstance().NotifySnapshotChanged(networkId, keyInfo->missionId); + } + } +} +} // namespace DistributedSchedule +} // namespace OHOS diff --git a/services/dtbschedmgr/src/mission/distributed_data_storage.cpp b/services/dtbschedmgr/src/mission/distributed_data_storage.cpp new file mode 100644 index 00000000..18b2b1e4 --- /dev/null +++ b/services/dtbschedmgr/src/mission/distributed_data_storage.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mission/distributed_data_storage.h" + +#include +#include "datetime_ex.h" +#include "dtbschedmgr_device_info_storage.h" +#include "dtbschedmgr_log.h" +#include "mission/distributed_sched_mission_manager.h" + +using namespace std; +using namespace OHOS::DistributedKv; + +namespace OHOS { +namespace DistributedSchedule { +namespace { +const std::string TAG = "DistributedDataStorage"; +} + +bool DistributedDataStorage::Init() +{ + HILOGD("Init begin!"); + InitHandler(); + bool ret = InitKvDataManager(); + if (!ret) { + HILOGE("Init InitKvDataManager failed!"); + return false; + } + SubscribeDistributedDataStorage(); + HILOGD("Init success!"); + return true; +} + +bool DistributedDataStorage::InitKvDataManager() +{ + return true; +} + +void DistributedDataStorage::SubscribeDistributedDataStorage() +{ +} + +void DistributedDataStorage::InitHandler() +{ + if (dmsDataStorageHandler_ == nullptr) { + shared_ptr runner = AppExecFwk::EventRunner::Create("dmsDataStorageHandler"); + dmsDataStorageHandler_ = make_shared(runner); + } +} + +bool DistributedDataStorage::Stop() +{ + HILOGD("Stop begin!"); + bool ret = UninitKvDataManager(); + if (!ret) { + HILOGW("Stop UninitKvDataManager failed!"); + return false; + } + dmsDataStorageHandler_ = nullptr; + HILOGD("Stop success!"); + return true; +} + +bool DistributedDataStorage::UninitKvDataManager() +{ + return true; +} + +bool DistributedDataStorage::Insert(const string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) +{ + return true; +} + +bool DistributedDataStorage::InsertInnerLocked(const string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) +{ + return true; +} + +bool DistributedDataStorage::Delete(const string& deviceId, int32_t missionId) +{ + return true; +} + +bool DistributedDataStorage::DeleteInnerLocked(const string& deviceId, int32_t missionId) +{ + return true; +} + +bool DistributedDataStorage::FuzzyDelete(const string& uuid) +{ + if (uuid.empty()) { + HILOGW("FuzzyDelete uuid empty!"); + return false; + } + { + unique_lock writeLock(initLock_); + bool ret = FuzzyDeleteInnerLocked(uuid); + if (!ret) { + HILOGW("FuzzyDelete deviceId = %{public}s failed!", + DnetworkAdapter::AnonymizeDeviceId(uuid).c_str()); + return false; + } + } + HILOGI("FuzzyDelete fuzzy delete successful!"); + return true; +} + +bool DistributedDataStorage::FuzzyDeleteInnerLocked(const string& deviceId) +{ + return true; +} + +bool DistributedDataStorage::Query(const string& deviceId, int32_t missionId, Value& value) const +{ + return true; +} + +bool DistributedDataStorage::QueryInnerLocked(const string& deviceId, int32_t missionId, Value& value) const +{ + return true; +} + +bool DistributedDataStorage::Sync(const std::string& deviceId) +{ + if (deviceId.empty()) { + HILOGW("Sync deviceId empty!"); + return false; + } + return true; +} + +bool DistributedDataStorage::Sync() +{ + return true; +} + +bool DistributedDataStorage::SyncInnerLocked(const vector& deviceVec, const SyncMode& mode, uint32_t syncCount) +{ + return true; +} + +void DistributedDataStorage::RetrySync(const vector& deviceVec, const DistributedKv::SyncMode& mode, + uint32_t syncCount) +{ +} + +void DistributedDataStorage::GenerateKey(const string& deviceId, int32_t missionId, Key& key) +{ + string keyString; + keyString.append(deviceId).append("_").append(to_string(missionId)); + key = keyString; +} + +void DistributedDataStorage::GenerateKey(const string& deviceId, Key& key) +{ + string keyString; + keyString.append(deviceId); + key = keyString; +} + +void DistributedDataStorage::GenerateValue(const uint8_t* byteStream, size_t len, Value& value) +{ + Value valueString((char *)byteStream, len); + value = valueString; +} +} // DistributedSchedule +} // namespace OHOS diff --git a/services/dtbschedmgr/src/mission/distributed_sched_mission_manager.cpp b/services/dtbschedmgr/src/mission/distributed_sched_mission_manager.cpp new file mode 100644 index 00000000..0bd9c9ad --- /dev/null +++ b/services/dtbschedmgr/src/mission/distributed_sched_mission_manager.cpp @@ -0,0 +1,1321 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mission/distributed_sched_mission_manager.h" + +#include +#include +#include + +#include "datetime_ex.h" +#include "distributed_sched_adapter.h" +#include "dtbschedmgr_device_info_storage.h" +#include "dtbschedmgr_log.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "mission/mission_changed_notify.h" +#include "mission/mission_constant.h" +#include "nlohmann/json.hpp" +#include "string_ex.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedSchedule { +namespace { +const std::string TAG = "DistributedSchedMissionManager"; +constexpr size_t MAX_CACHED_ITEM = 10; +constexpr int32_t FIRST_APPLICATION_UID = 10000; +constexpr int32_t MULTIUSER_HAP_PER_USER_RANGE = 100000; +constexpr int32_t MAX_RETRY_TIMES = 15; +constexpr int32_t RETRY_DELAYED = 2000; +const std::string DELETE_DATA_STORAGE = "DeleteDataStorage"; +constexpr int32_t DELETE_DATA_STORAGE_DELAYED = 60000; +constexpr int32_t REGISTER_MISSION_LISTENER = 0; +constexpr int32_t UNREGISTER_MISSION_LISTENER = 1; +constexpr int64_t DELAY_TIME = 300; +const std::string INVAILD_LOCAL_DEVICE_ID = "-1"; +} +namespace Mission { +constexpr int32_t GET_MAX_MISSIONS = 20; +} // Mission +using namespace std::chrono; +using namespace Constants::Mission; +using namespace OHOS::DistributedKv; + +IMPLEMENT_SINGLE_INSTANCE(DistributedSchedMissionManager); + +void DistributedSchedMissionManager::Init() +{ + listenerDeath_ = new ListenerDeathRecipient(); + remoteDmsRecipient_ = new RemoteDmsDeathRecipient(); + auto runner = AppExecFwk::EventRunner::Create("MissionManagerHandler"); + missionHandler_ = std::make_shared(runner); + auto updateRunner = AppExecFwk::EventRunner::Create("UpdateHandler"); + updateHandler_ = std::make_shared(updateRunner); +} + +int32_t DistributedSchedMissionManager::GetMissionInfos(const std::string& deviceId, + int32_t numMissions, std::vector& missionInfos) +{ + HILOGI("start!"); + if (!AllowMissionUid(IPCSkeleton::GetCallingUid())) { + HILOGE("permission denied!"); + return ERR_PERMISSION_DENIED; + } + if (!IsDeviceIdValidated(deviceId)) { + return INVALID_PARAMETERS_ERR; + } + if (numMissions <= 0) { + HILOGE("numMissions is illegal! numMissions:%{public}d", numMissions); + return INVALID_PARAMETERS_ERR; + } + + return FetchCachedRemoteMissions(deviceId, numMissions, missionInfos); +} + +sptr DistributedSchedMissionManager::GetRemoteDms(const std::string& deviceId) +{ + int64_t begin = GetTickCount(); + if (deviceId.empty()) { + HILOGE("GetRemoteDms remoteDeviceId is empty"); + return nullptr; + } + { + std::lock_guard autoLock(remoteDmsLock_); + auto iter = remoteDmsMap_.find(deviceId); + if (iter != remoteDmsMap_.end()) { + auto object = iter->second; + if (object != nullptr) { + HILOGI("[PerformanceTest] GetRemoteDms from cache spend %{public}" PRId64 " ms", + GetTickCount() - begin); + return object; + } + } + } + HILOGD("GetRemoteDms connect deviceid is %s", deviceId.c_str()); + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + HILOGE("GetRemoteDms failed to connect to systemAbilityMgr!"); + return nullptr; + } + auto object = samgr->CheckSystemAbility(DISTRIBUTED_SCHED_SA_ID, deviceId); + if (object == nullptr) { + HILOGE("GetRemoteDms failed to get dms for remote device:%{public}s!", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + return nullptr; + } + auto ret = object->AddDeathRecipient(remoteDmsRecipient_); + HILOGD("GetRemoteDms AddDeathRecipient ret : %{public}d", ret); + sptr remoteDmsObj = iface_cast(object); + { + std::lock_guard autoLock(remoteDmsLock_); + auto iter = remoteDmsMap_.find(deviceId); + if (iter != remoteDmsMap_.end()) { + iter->second->AsObject()->RemoveDeathRecipient(remoteDmsRecipient_); + } + remoteDmsMap_[deviceId] = remoteDmsObj; + } + HILOGI("[PerformanceTest] GetRemoteDms spend %{public}" PRId64 " ms", GetTickCount() - begin); + return remoteDmsObj; +} + +bool DistributedSchedMissionManager::IsDeviceIdValidated(const std::string& deviceId) +{ + if (deviceId.empty()) { + HILOGE("IsDeviceIdValidated deviceId is empty!"); + return false; + } + if (DtbschedmgrDeviceInfoStorage::GetInstance().GetDeviceInfoById(deviceId) == nullptr) { + HILOGW("IsDeviceIdValidated device offline."); + return false; + } + + return true; +} + +int32_t DistributedSchedMissionManager::InitDataStorage() +{ + distributedDataStorage_ = std::make_shared(); + if (!distributedDataStorage_->Init()) { + HILOGE("InitDataStorage DistributedDataStorage init failed!"); + return ERR_NULL_OBJECT; + } + return ERR_NONE; +} + +int32_t DistributedSchedMissionManager::StopDataStorage() +{ + if (distributedDataStorage_ == nullptr) { + HILOGE("StopDataStorage DistributedDataStorage null!"); + return ERR_NULL_OBJECT; + } + if (!distributedDataStorage_->Stop()) { + HILOGE("StopDataStorage DistributedDataStorage stop failed!"); + return ERR_NULL_OBJECT; + } + return ERR_NONE; +} + +int32_t DistributedSchedMissionManager::StoreSnapshotInfo(const std::string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) +{ + if (distributedDataStorage_ == nullptr) { + HILOGE("StoreSnapshotInfo DistributedDataStorage null!"); + return ERR_NULL_OBJECT; + } + if (!distributedDataStorage_->Insert(deviceId, missionId, byteStream, len)) { + HILOGE("StoreSnapshotInfo DistributedDataStorage insert failed!"); + return ERR_NULL_OBJECT; + } + return ERR_NONE; +} + +int32_t DistributedSchedMissionManager::RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) +{ + if (distributedDataStorage_ == nullptr) { + HILOGE("RemoveSnapshotInfo DistributedDataStorage null!"); + return ERR_NULL_OBJECT; + } + if (!distributedDataStorage_->Delete(deviceId, missionId)) { + HILOGE("RemoveSnapshotInfo DistributedDataStorage delete failed!"); + return ERR_NULL_OBJECT; + } + return ERR_NONE; +} + +std::unique_ptr DistributedSchedMissionManager::GetRemoteSnapshotInfo(const std::string& deviceId, + int32_t missionId) +{ + if (!AllowMissionUid(IPCSkeleton::GetCallingUid())) { + HILOGE("GetRemoteSnapshotInfo permission denied!"); + return nullptr; + } + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + if (uuid.empty()) { + HILOGE("GetRemoteSnapshotInfo uuid empty!"); + return nullptr; + } + std::unique_ptr snapshot = DequeueCachedSnapshotInfo(uuid, missionId); + if (snapshot != nullptr) { + return snapshot; + } + if (distributedDataStorage_ == nullptr) { + HILOGE("GetRemoteSnapshotInfo DistributedDataStorage null!"); + return nullptr; + } + DistributedKv::Value value; + bool ret = distributedDataStorage_->Query(deviceId, missionId, value); + if (!ret) { + HILOGE("GetRemoteSnapshotInfo DistributedDataStorage query failed!"); + return nullptr; + } + snapshot = Snapshot::Create(value.Data()); + if (snapshot == nullptr) { + HILOGE("GetRemoteSnapshotInfo snapshot create failed!"); + return nullptr; + } + return snapshot; +} + +void DistributedSchedMissionManager::DeviceOnlineNotify(const std::string& deviceId) +{ + if (deviceId.empty()) { + HILOGW("DeviceOnlineNotify deviceId empty!"); + return; + } + + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + if (missionHandler_ != nullptr) { + HILOGI("DeviceOnlineNotify RemoveTask"); + missionHandler_->RemoveTask(DELETE_DATA_STORAGE + uuid); + } +} + +void DistributedSchedMissionManager::DeviceOfflineNotify(const std::string& deviceId) +{ + if (deviceId.empty()) { + HILOGW("DeviceOfflineNotify deviceId empty!"); + return; + } + UnRegisterMissionListenerFromRemote(deviceId); + CleanMissionResources(deviceId); + { + std::lock_guard autoLock(remoteDmsLock_); + auto iter = remoteDmsMap_.find(deviceId); + if (iter != remoteDmsMap_.end()) { + iter->second->AsObject()->RemoveDeathRecipient(remoteDmsRecipient_); + remoteDmsMap_.erase(iter); + } + } + int64_t begin = GetTickCount(); + { + std::lock_guard autoLock(osdSwitchLock_); + connCapSupportOsdMap_.erase(deviceId); + } + HILOGI("DeviceOfflineNotify erase value for deviceId: %{public}s spend %{public}" PRId64 " ms", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str(), GetTickCount() - begin); +} + +void DistributedSchedMissionManager::UpdateConnCapSupportOsd(const std::string& deviceId) +{ + HILOGI("UpdateConnCapSupportOsd begin, deviceId is %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + bool isSupportOsd = IsConnCapSupportOsd(deviceId); + bool needNotifyChanged = false; + int32_t switchVal = MISSION_OSD_NOT_SUPPORTED; + { + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + std::lock_guard autoLock(osdSwitchLock_); + auto iter = connCapSupportOsdMap_.find(deviceId); + if (iter != connCapSupportOsdMap_.end()) { + needNotifyChanged = (iter->second != isSupportOsd); + } else { + needNotifyChanged = true; + } + connCapSupportOsdMap_[deviceId] = isSupportOsd; + HILOGI("UpdateConnCapSupportOsd end, isSupportOsd is %{public}d", isSupportOsd); + auto iterOsdSwitch = osdSwitchValueMap_.find(uuid); + if (isSupportOsd && iterOsdSwitch == osdSwitchValueMap_.end()) { + HILOGI("UpdateConnCapSupportOsd can not find osd switch value!"); + return; + } + switchVal = isSupportOsd ? iterOsdSwitch->second : MISSION_OSD_NOT_SUPPORTED; + } + NotifyOsdSwitchChanged(needNotifyChanged, deviceId, switchVal); +} + +bool DistributedSchedMissionManager::IsConnCapSupportOsd(const std::string& deviceId) +{ + return true; +} + +void DistributedSchedMissionManager::DeleteDataStorage(const std::string& deviceId, bool isDelayed) +{ + if (distributedDataStorage_ == nullptr) { + HILOGE("DeleteDataStorage DistributedDataStorage null!"); + return; + } + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + auto callback = [this, uuid]() { + if (!distributedDataStorage_->FuzzyDelete(uuid)) { + HILOGE("DeleteDataStorage storage delete failed!"); + } else { + HILOGI("DeleteDataStorage storage delete successfully!"); + } + }; + if (isDelayed) { + if (missionHandler_ != nullptr) { + HILOGI("DeleteDataStorage PostTask"); + missionHandler_->PostTask(callback, DELETE_DATA_STORAGE + uuid, DELETE_DATA_STORAGE_DELAYED); + } + } else { + if (missionHandler_ != nullptr) { + HILOGI("DeleteDataStorage RemoveTask"); + missionHandler_->RemoveTask(DELETE_DATA_STORAGE + uuid); + } + callback(); + } +} + +int32_t DistributedSchedMissionManager::RegisterRemoteMissionListener(const std::u16string& devId, + const sptr& listener) +{ + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(Str16ToStr8(devId)); + if (missionHandler_ != nullptr) { + HILOGI("RemoveTask"); + missionHandler_->RemoveTask(DELETE_DATA_STORAGE + uuid); + } + if (listener == nullptr) { + return INVALID_PARAMETERS_ERR; + } + if (!AllowMissionUid(IPCSkeleton::GetCallingUid())) { + HILOGE("permission denied!"); + return DMS_PERMISSION_DENIED; + } + std::string localDeviceId; + std::string remoteDeviceId = Str16ToStr8(devId); + if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localDeviceId) + || localDeviceId == remoteDeviceId) { + HILOGE("check deviceId failed!"); + return INVALID_PARAMETERS_ERR; + } + { + std::lock_guard autoLock(listenDeviceLock_); + auto& listenerInfo = listenDeviceMap_[devId]; + if (!listenerInfo.Emplace(listener)) { + HILOGW("RegisterSyncListener listener has alread inserted!"); + return ERR_NONE; + } + bool ret = listener->AddDeathRecipient(listenerDeath_); + if (!ret) { + HILOGW("RegisterSyncListener AddDeathRecipient failed!"); + } + if (listenerInfo.Size() > 1) { + HILOGI("RegisterRemoteMissionListener not notify remote DMS!"); + return ERR_NONE; + } + } + + if (CheckOsdSwitch(remoteDeviceId) != MISSION_OSD_ENABLED) { + NotifyOsdSwitchChanged(true, remoteDeviceId, MISSION_OSD_NOT_SUPPORTED); + return MISSION_OSD_NOT_SUPPORTED; + } + return ERR_NONE; +} + +int32_t DistributedSchedMissionManager::PrepareAndSyncMissions(const std::string& dstDevId, + const std::string& localDevId) +{ + std::u16string devId = Str8ToStr16(dstDevId); + { + std::lock_guard autoLock(listenDeviceLock_); + auto iterItem = listenDeviceMap_.find(devId); + if (iterItem == listenDeviceMap_.end()) { + } + bool callFlag = iterItem->second.called; + if (callFlag) { + HILOGI("PrepareAndSyncMissions already called!"); + } + } + sptr remoteDms = GetRemoteDms(dstDevId); + if (remoteDms == nullptr) { + HILOGE("get remoteDms failed!"); + RetryStartRemoteSyncMission(dstDevId, localDevId, 0); + return GET_REMOTE_DMS_FAIL; + } + int32_t ret = PrepareAndSyncMissions(dstDevId, remoteDms); + if (ret == ERR_NONE) { + std::lock_guard autoLock(listenDeviceLock_); + auto iterItem = listenDeviceMap_.find(devId); + if (iterItem != listenDeviceMap_.end()) { + iterItem->second.called = true; + } + } + return ret; +} + +int32_t DistributedSchedMissionManager::PrepareAndSyncMissions(const std::string& dstDevId, + const sptr& remoteDms) +{ + std::vector missionInfos; + CallerInfo callerInfo; + if (!GenerateCallerInfo(callerInfo)) { + return GET_LOCAL_DEVICE_ERR; + } + int64_t begin = GetTickCount(); + int32_t ret = remoteDms->PrepareAndSyncMissionsFromRemote(callerInfo, missionInfos); + HILOGI("[PerformanceTest] ret:%{public}d, spend %{public}" PRId64 " ms", + ret, GetTickCount() - begin); + if (ret == ERR_NONE) { + RebornMissionCache(dstDevId, missionInfos); + } + return ret; +} + +int32_t DistributedSchedMissionManager::UnRegisterRemoteMissionListener(const std::u16string& devId, + const sptr& listener) +{ + if (listener == nullptr) { + return INVALID_PARAMETERS_ERR; + } + if (!AllowMissionUid(IPCSkeleton::GetCallingUid())) { + HILOGE("UnRegisterRemoteMissionListener permission denied!"); + return DMS_PERMISSION_DENIED; + } + std::string localDeviceId; + if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localDeviceId) + || localDeviceId == Str16ToStr8(devId)) { + HILOGE("UnRegisterRemoteMissionListener check deviceId fail"); + return INVALID_PARAMETERS_ERR; + } + { + std::lock_guard autoLock(listenDeviceLock_); + auto iterItem = listenDeviceMap_.find(devId); + if (iterItem == listenDeviceMap_.end()) { + return ERR_NONE; + } + auto& listenerInfo = iterItem->second; + auto ret = listenerInfo.Find(listener); + if (!ret) { + HILOGI("UnRegisterRemoteMissionListener listener not registered!"); + return ERR_NONE; + } + listener->RemoveDeathRecipient(listenerDeath_); + listenerInfo.Erase(listener); + if (!listenerInfo.Empty()) { + return ERR_NONE; + } + listenDeviceMap_.erase(iterItem); + } + return UnRegisterRemoteMissionListenerInner(Str16ToStr8(devId), false, true); +} + +void DistributedSchedMissionManager::CleanMissionResources(const std::string& dstDevId) +{ + { + std::lock_guard autoLock(listenDeviceLock_); + auto iterDevice = listenDeviceMap_.find(Str8ToStr16(dstDevId)); + if (iterDevice == listenDeviceMap_.end()) { + return; + } + auto& listenerInfo = iterDevice->second; + for (sptr listener : listenerInfo.listenerSet) { + if (listener != nullptr) { + listener->RemoveDeathRecipient(listenerDeath_); + } + } + listenDeviceMap_.erase(iterDevice); + } + UnRegisterRemoteMissionListenerInner(dstDevId, true); +} + +int32_t DistributedSchedMissionManager::UnRegisterRemoteMissionListenerInner(const std::string& dstDevId, + bool offline, bool exit) +{ + CleanMissionCache(dstDevId); + DeleteCachedSnapshotInfo(dstDevId); + DeleteDataStorage(dstDevId, true); + + if (offline) { + return ERR_NONE; + } + sptr remoteDms = GetRemoteDms(dstDevId); + if (remoteDms == nullptr) { + HILOGE("UnRegisterRemoteMissionListener DMS get remoteDms failed"); + return GET_REMOTE_DMS_FAIL; + } + + CallerInfo callerInfo; + if (!GenerateCallerInfo(callerInfo)) { + return GET_LOCAL_DEVICE_ERR; + } + int64_t begin = GetTickCount(); + int32_t ret = remoteDms->UnRegisterMissionListenerFromRemote(callerInfo); + HILOGI("[PerformanceTest] UnRegisterMissionListenerFromRemote ret:%d, spend %{public}" PRId64 " ms", + ret, GetTickCount() - begin); + return ret; +} + +int32_t DistributedSchedMissionManager::PrepareAndSyncMissions(const std::u16string& dstDevId, bool fixConflict, + int64_t tag) +{ + std::string localDeviceId; + if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localDeviceId)) { + HILOGE("check deviceId fail"); + return INVALID_PARAMETERS_ERR; + } + std::string deviceId = Str16ToStr8(dstDevId); + HILOGI("begin, deviceId is %{public}s, local deviceId is %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str(), + DnetworkAdapter::AnonymizeDeviceId(localDeviceId).c_str()); + if (deviceId != INVAILD_LOCAL_DEVICE_ID && deviceId != localDeviceId && + CheckOsdSwitch(deviceId) != MISSION_OSD_ENABLED) { + NotifyOsdSwitchChanged(true, deviceId, MISSION_OSD_NOT_SUPPORTED); + return MISSION_OSD_NOT_SUPPORTED; + } + auto ret = PrepareAndSyncMissions(deviceId, localDeviceId); + if (ret != ERR_NONE) { + HILOGE("PrepareAndSyncMissions failed, %{public}d", ret); + return ret; + } + return ERR_NONE; +} + +int32_t DistributedSchedMissionManager::PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) +{ + auto deviceId = callerInfo.sourceDeviceId; + HILOGD("remote version is %{public}d!", callerInfo.dmsVersion); + { + std::lock_guard autoLock(remoteSyncDeviceLock_); + remoteSyncDeviceSet_.emplace(deviceId); + if (remoteSyncDeviceSet_.size() == 1) { + DistributedSchedAdapter::GetInstance().OnOsdEventOccur(REGISTER_MISSION_LISTENER); + } + } + if (GetOsdSwitchValueFromRemote() != MISSION_OSD_ENABLED) { + HILOGI("osd function is disable!"); + return ERR_NONE; + } + if (distributedDataStorage_ != nullptr) { + if (!distributedDataStorage_->Sync(deviceId)) { + HILOGE("DistributedDataStorage push sync failed!"); + } + } + if (!isRegMissionChange_) { + DistributedSchedAdapter::GetInstance().RegisterMissionChange(true); + isRegMissionChange_ = true; + } + return DistributedSchedAdapter::GetInstance().GetLocalMissionInfos(Mission::GET_MAX_MISSIONS, missionInfos); +} + +void DistributedSchedMissionManager::UnRegisterMissionListenerFromRemote(const std::string& deviceId) +{ + HILOGD(" %{private}s!", deviceId.c_str()); + { + std::lock_guard autoLock(remoteSyncDeviceLock_); + remoteSyncDeviceSet_.erase(deviceId); + if (remoteSyncDeviceSet_.empty()) { + DistributedSchedAdapter::GetInstance().RegisterMissionChange(false); + DistributedSchedAdapter::GetInstance().OnOsdEventOccur(UNREGISTER_MISSION_LISTENER); + isRegMissionChange_ = false; + } + } +} + +bool DistributedSchedMissionManager::needSyncDevice(const std::string& deviceId) +{ + std::lock_guard autoLock(remoteSyncDeviceLock_); + if (remoteSyncDeviceSet_.count(deviceId) == 0) { + return false; + } + return true; +} + +bool DistributedSchedMissionManager::HasSyncListener(const std::string& dstDeviceId) +{ + std::lock_guard autoLock(listenDeviceLock_); + auto iter = listenDeviceMap_.find(Str8ToStr16(dstDeviceId)); + if (iter != listenDeviceMap_.end()) { + return iter->second.called; + } + return false; +} + +void DistributedSchedMissionManager::NotifySnapshotChanged(const std::string& devId, int32_t missionId) +{ + std::u16string u16DevId = Str8ToStr16(devId); + std::lock_guard autoLock(listenDeviceLock_); + auto iter = listenDeviceMap_.find(u16DevId); + if (iter == listenDeviceMap_.end()) { + return; + } + auto& listenerInfo = iter->second; + for (auto& listener : listenerInfo.listenerSet) { + MissionChangedNotify::NotifySnapshot(listener, u16DevId, missionId); + } +} + +void DistributedSchedMissionManager::OnRemoteDied(const wptr& remote) +{ + HILOGD("OnRemoteDied!"); + sptr listener = remote.promote(); + if (listener == nullptr) { + return; + } + auto remoteDiedFunc = [this, listener]() { + OnMissionListenerDied(listener); + }; + if (missionHandler_ != nullptr) { + missionHandler_->PostTask(remoteDiedFunc); + } +} + +void DistributedSchedMissionManager::ListenerDeathRecipient::OnRemoteDied(const wptr& remote) +{ + DistributedSchedMissionManager::GetInstance().OnRemoteDied(remote); +} + +void DistributedSchedMissionManager::EnqueueCachedSnapshotInfo(const std::string& deviceId, int32_t missionId, + std::unique_ptr snapshot) +{ + if (deviceId.empty() || snapshot == nullptr) { + HILOGW("EnqueueCachedSnapshotInfo invalid input param!"); + return; + } + std::lock_guard autoLock(listenDeviceLock_); + std::string keyInfo = GenerateKeyInfo(deviceId, missionId); + auto iter = cachedSnapshotInfos_.find(keyInfo); + if (iter != cachedSnapshotInfos_.end()) { + if (snapshot->GetCreatedTime() < iter->second->GetCreatedTime()) { + return; + } + } + + if (cachedSnapshotInfos_.size() == MAX_CACHED_ITEM) { + int64_t oldest = -1; + auto iterOldest = cachedSnapshotInfos_.end(); + for (auto iterItem = cachedSnapshotInfos_.begin(); iterItem != cachedSnapshotInfos_.end(); ++iterItem) { + if (oldest == -1 || iterItem->second->GetLastAccessTime() < oldest) { + oldest = iterItem->second->GetLastAccessTime(); + iterOldest = iterItem; + } + } + if (iterOldest != cachedSnapshotInfos_.end()) { + cachedSnapshotInfos_.erase(iterOldest); + } + } + cachedSnapshotInfos_[keyInfo] = std::move(snapshot); +} + +std::unique_ptr DistributedSchedMissionManager::DequeueCachedSnapshotInfo(const std::string& deviceId, + int32_t missionId) +{ + if (deviceId.empty()) { + HILOGW("DequeueCachedSnapshotInfo invalid input param!"); + return nullptr; + } + std::lock_guard autoLock(listenDeviceLock_); + auto iter = cachedSnapshotInfos_.find(GenerateKeyInfo(deviceId, missionId)); + if (iter != cachedSnapshotInfos_.end()) { + std::unique_ptr snapshot = std::move(iter->second); + snapshot->UpdateLastAccessTime(GetTickCount()); + iter->second = nullptr; + cachedSnapshotInfos_.erase(iter); + return snapshot; + } + return nullptr; +} + +void DistributedSchedMissionManager::DeleteCachedSnapshotInfo(const std::string& networkId) +{ + if (networkId.empty()) { + return; + } + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(networkId); + if (uuid.empty()) { + return; + } + std::lock_guard autoLock(listenDeviceLock_); + auto iter = cachedSnapshotInfos_.begin(); + while (iter != cachedSnapshotInfos_.end()) { + if (iter->first.find(uuid) != std::string::npos) { + iter = cachedSnapshotInfos_.erase(iter); + } else { + ++iter; + } + } +} + +int32_t DistributedSchedMissionManager::FetchCachedRemoteMissions(const std::string& srcId, int32_t numMissions, + std::vector& missionInfos) +{ + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(srcId); + if (uuid.empty()) { + HILOGE("uuid empty!"); + return INVALID_PARAMETERS_ERR; + } + std::lock_guard autoLock(remoteMissionInfosLock_); + auto iter = deviceMissionInfos_.find(uuid); + if (iter == deviceMissionInfos_.end()) { + HILOGE("can not find uuid, deviceId: %{public}s!", + DnetworkAdapter::AnonymizeDeviceId(srcId).c_str()); + return ERR_NULL_OBJECT; + } + + // get at most numMissions missions + int32_t actualNums = static_cast((iter->second).size()); + if (actualNums < 0) { + HILOGE("invalid size!"); + return ERR_NULL_OBJECT; + } + missionInfos.assign((iter->second).begin(), + (actualNums > numMissions) ? (iter->second).begin() + numMissions : (iter->second).end()); + return ERR_NONE; +} + +void DistributedSchedMissionManager::RebornMissionCache(const std::string& deviceId, + const std::vector& missionInfos) +{ + HILOGI("start! deviceId is %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + if (uuid.empty()) { + HILOGE("uuid empty!"); + return; + } + { + std::lock_guard autoLock(remoteMissionInfosLock_); + deviceMissionInfos_[uuid] = missionInfos; + } + HILOGI("RebornMissionCache end!"); +} + +void DistributedSchedMissionManager::CleanMissionCache(const std::string& deviceId) +{ + HILOGI("CleanMissionCache start! deviceId is %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + if (uuid.empty()) { + HILOGE("CleanMissionCache uuid empty!"); + return; + } + { + std::lock_guard autoLock(remoteMissionInfosLock_); + deviceMissionInfos_.erase(uuid); + } + HILOGI("CleanMissionCache end!"); +} + +int32_t DistributedSchedMissionManager::NotifyMissionsChangedFromRemote(const CallerInfo& callerInfo, + const std::vector& missionInfos) +{ + HILOGI("NotifyMissionsChangedFromRemote version is %{public}d!", callerInfo.dmsVersion); + std::u16string u16DevId = Str8ToStr16(callerInfo.sourceDeviceId); + { + std::lock_guard autoLock(listenDeviceLock_); + if (listenDeviceMap_.count(u16DevId) == 0) { + HILOGW("NotifyMissionsChangedFromRemote exit for invaid device"); + return INVALID_PARAMETERS_ERR; + } + } + RebornMissionCache(callerInfo.sourceDeviceId, missionInfos); + { + HILOGI("NotifyMissionsChangedFromRemote notify mission start!"); + std::lock_guard autoLock(listenDeviceLock_); + auto iter = listenDeviceMap_.find(u16DevId); + if (iter == listenDeviceMap_.end()) { + HILOGE("NotifyMissionsChangedFromRemote notify mission no listener!"); + return INVALID_PARAMETERS_ERR; + } + auto& listenerSet = iter->second.listenerSet; + auto notifyChanged = [listenerSet, u16DevId] () { + for (const auto& listener : listenerSet) { + MissionChangedNotify::NotifyMissionsChanged(listener, u16DevId); + } + }; + if (missionHandler_ != nullptr) { + missionHandler_->PostTask(notifyChanged); + HILOGI("NotifyMissionsChangedFromRemote end!"); + return ERR_NONE; + } + } + return INVALID_PARAMETERS_ERR; +} + +int32_t DistributedSchedMissionManager::NotifyMissionsChangedToRemote(const std::vector& missionInfos) +{ + CallerInfo callerInfo; + if (!GenerateCallerInfo(callerInfo)) { + return GET_LOCAL_DEVICE_ERR; + } + std::lock_guard autoLock(remoteSyncDeviceLock_); + for (const auto& destDeviceId : remoteSyncDeviceSet_) { + auto handler = FetchDeviceHandler(destDeviceId); + if (handler == nullptr) { + HILOGE("NotifyMissionsChangedToRemote fetch handler failed!"); + continue; + } + auto callback = [destDeviceId, missionInfos, callerInfo, this] () { + NotifyMissionsChangedToRemoteInner(destDeviceId, missionInfos, callerInfo); + }; + if (!handler->PostTask(callback)) { + HILOGE("NotifyMissionsChangedToRemote PostTask failed!"); + return ERR_NULL_OBJECT; + } + } + + return ERR_NONE; +} + +void DistributedSchedMissionManager::NotifyMissionsChangedToRemoteInner(const std::string& deviceId, + const std::vector& missionInfos, const CallerInfo& callerInfo) +{ + sptr remoteDms = GetRemoteDms(deviceId); + if (remoteDms == nullptr) { + HILOGE("NotifyMissionsChangedToRemote DMS get remoteDms failed"); + return; + } + int64_t begin = GetTickCount(); + int32_t result = remoteDms->NotifyMissionsChangedFromRemote(missionInfos, callerInfo); + HILOGI("[PerformanceTest] NotifyMissionsChangedFromRemote ret:%d, spend %{public}" PRId64 " ms", + result, GetTickCount() - begin); +} + +bool DistributedSchedMissionManager::GenerateCallerInfo(CallerInfo& callerInfo) +{ + std::string localUuid; + if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localUuid)) { + HILOGE("get local uuid failed!"); + return false; + } + callerInfo.uid = IPCSkeleton::GetCallingUid(); + callerInfo.pid = IPCSkeleton::GetCallingPid(); + callerInfo.callerType = CALLER_TYPE_HARMONY; + callerInfo.sourceDeviceId = localUuid; + callerInfo.dmsVersion = VERSION; + return true; +} + +std::shared_ptr DistributedSchedMissionManager::FetchDeviceHandler( + const std::string& deviceId) +{ + if (!IsDeviceIdValidated(deviceId)) { + HILOGW("FetchDeviceHandler device:%{public}s offline.", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + return nullptr; + } + + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + if (uuid.empty()) { + HILOGE("FetchDeviceHandler uuid empty!"); + return nullptr; + } + + auto iter = deviceHandle_.find(uuid); + if (iter != deviceHandle_.end()) { + return iter->second; + } + + auto anonyUuid = DnetworkAdapter::AnonymizeDeviceId(uuid); + auto runner = AppExecFwk::EventRunner::Create("MissionN_" + anonyUuid); + auto handler = std::make_shared(runner); + if (handler != nullptr) { + deviceHandle_.emplace(uuid, handler); + } + return handler; +} + +bool DistributedSchedMissionManager::GetConnCapSupportOsd(const std::string& deviceId) +{ + HILOGI("GetConnCapSupportOsd begin, deviceId is %{public}s", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + std::lock_guard autoLock(osdSwitchLock_); + return GetConnCapSupportOsdInnerLocked(deviceId); +} + +bool DistributedSchedMissionManager::GetConnCapSupportOsdInnerLocked(const std::string& deviceId) +{ + bool connCapSupportOsd = false; + auto iter = connCapSupportOsdMap_.find(deviceId); + if (iter != connCapSupportOsdMap_.end()) { + connCapSupportOsd = iter->second; + HILOGI("CheckSupportOsd find connCapSupportOsd is %{public}d", connCapSupportOsd); + } else { + HILOGI("CheckSupportOsd can not find connCapSupportOsd, try to get it!"); + connCapSupportOsd = IsConnCapSupportOsd(deviceId); + connCapSupportOsdMap_[deviceId] = connCapSupportOsd; + } + return connCapSupportOsd; +} + +bool DistributedSchedMissionManager::PreCheckSupportOsd(const std::string& deviceId) +{ + if (!AllowMissionUid(IPCSkeleton::GetCallingUid())) { + HILOGE("CheckSupportOsd permission denied!"); + return false; + } + if (!IsDeviceIdValidated(deviceId)) { + HILOGE("DeviceId is inValidated!"); + return false; + } + if (!GetConnCapSupportOsd(deviceId)) { + HILOGI("CheckSupportOsd conn cap not support osd!"); + return false; + } + return true; +} + +int32_t DistributedSchedMissionManager::CheckSupportOsd(const std::string& deviceId) +{ + HILOGI("CheckSupportOsd start, deviceId: %{public}s!", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + if (!PreCheckSupportOsd(deviceId)) { + return MISSION_OSD_NOT_SUPPORTED; + } + int64_t begin = GetTickCount(); + { + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + std::lock_guard autoLock(osdSwitchLock_); + auto iter = osdSwitchValueMap_.find(uuid); + if (iter != osdSwitchValueMap_.end()) { + HILOGI("CheckSupportOsd find value spend %{public}" PRId64 " ms", GetTickCount() - begin); + return iter->second; + } + } + HILOGI("CheckSupportOsd can not find value spend %{public}" PRId64 " ms", GetTickCount() - begin); + + sptr remoteDms = GetRemoteDms(deviceId); + if (remoteDms == nullptr) { + HILOGE("CheckSupportOsd DMS get remoteDms failed"); + return MISSION_OSD_NOT_SUPPORTED; + } + begin = GetTickCount(); + int32_t osdSwitchVal = remoteDms->GetOsdSwitchValueFromRemote(); + HILOGI("[PerformanceTest] GetOsdSwitchValueFromRemote osdSwitch:%d, spend %{public}" PRId64 " ms", + osdSwitchVal, GetTickCount() - begin); + if (osdSwitchVal == IPC_STUB_UNKNOW_TRANS_ERR) { + HILOGI("GetOsdSwitchValueFromRemote destUuid: %{public}s does not support osd result: %{public}d", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str(), osdSwitchVal); + osdSwitchVal = MISSION_OSD_NOT_SUPPORTED; + } + if (!IsValidOsdSwitchValue(osdSwitchVal)) { + HILOGE("CheckSupportOsd osdSwitch %{public}d is invalid!", osdSwitchVal); + return MISSION_OSD_NOT_SUPPORTED; + } + begin = GetTickCount(); + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + std::lock_guard autoLock(osdSwitchLock_); + osdSwitchValueMap_[uuid] = osdSwitchVal; + HILOGI("CheckSupportOsd insert value spend %{public}" PRId64 " ms", GetTickCount() - begin); + return osdSwitchVal; +} + +int32_t DistributedSchedMissionManager::CheckOsdSwitch(const std::string& deviceId) +{ + HILOGI("CheckOsdSwitch start, deviceId: %{public}s!", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + if (!PreCheckSupportOsd(deviceId)) { + return MISSION_OSD_NOT_SUPPORTED; + } + int64_t begin = GetTickCount(); + { + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + std::lock_guard autoLock(osdSwitchLock_); + auto iter = osdSwitchValueMap_.find(uuid); + if (iter != osdSwitchValueMap_.end()) { + HILOGI("CheckOsdSwitch find value spend %{public}" PRId64 " ms", GetTickCount() - begin); + return iter->second; + } + } + HILOGI("CheckOsdSwitch can not find value spend %{public}" PRId64 " ms", GetTickCount() - begin); + return MISSION_OSD_ENABLED; +} + +void DistributedSchedMissionManager::GetCachedOsdSwitch(std::vector& deviceIds, + std::vector& values) +{ + HILOGI("GetCachedOsdSwitch start"); + if (!AllowMissionUid(IPCSkeleton::GetCallingUid())) { + HILOGE("GetCachedOsdSwitch permission denied!"); + return; + } + std::lock_guard autoLock(osdSwitchLock_); + for (const auto& [uuid, value] : osdSwitchValueMap_) { + std::string deviceId = DtbschedmgrDeviceInfoStorage::GetInstance().GetNetworkIdByUuid(uuid); + deviceIds.emplace_back(Str8ToStr16(deviceId)); + bool connCapSupportOsd = GetConnCapSupportOsdInnerLocked(deviceId); + values.emplace_back(connCapSupportOsd ? value : MISSION_OSD_NOT_SUPPORTED); + } +} + +int32_t DistributedSchedMissionManager::GetOsdSwitchValueFromRemote() +{ + HILOGI("GetOsdSwitchValueFromRemote start!"); + return DistributedSchedAdapter::GetInstance().GetOsdSwitch(); +} + +bool DistributedSchedMissionManager::AllowMissionUid(int32_t uid) +{ + int32_t appId = uid % MULTIUSER_HAP_PER_USER_RANGE; + if (appId < FIRST_APPLICATION_UID) { + return true; + } + std::lock_guard autoLock(allowMissionUidsLock_); + if (allowMissionUids_.count(appId) == 0) { + int64_t begin = GetTickCount(); + bool ret = DistributedSchedAdapter::GetInstance().AllowMissionUid(uid); + HILOGI("AllowMissionUid ret:%{public}s, spend %{public}" PRId64 " ms!", + (ret ? "succ" : "fail"), GetTickCount() - begin); + if (!ret) { + HILOGW("AllowMissionUid failed!"); + return false; + } + allowMissionUids_.insert(appId); + } + return true; +} + +void DistributedSchedMissionManager::RemoteDmsDeathRecipient::OnRemoteDied(const wptr& remote) +{ + HILOGI("OnRemoteDied received died notify!"); + DistributedSchedMissionManager::GetInstance().OnRemoteDmsDied(remote); +} + +void DistributedSchedMissionManager::OnRemoteDmsDied(const wptr& remote) +{ + sptr diedRemoted = remote.promote(); + if (diedRemoted == nullptr) { + HILOGW("OnRemoteDmsDied promote failed!"); + return; + } + HILOGD("delete diedRemoted"); + auto remoteDmsDiedFunc = [this, diedRemoted]() { + OnRemoteDmsDied(diedRemoted); + }; + if (missionHandler_ != nullptr) { + missionHandler_->PostTask(remoteDmsDiedFunc); + } +} + +void DistributedSchedMissionManager::RetryStartRemoteSyncMission(const std::string& dstDeviceId, + const std::string& localDevId, int32_t retryTimes) +{ + auto retryFunc = [this, dstDeviceId, localDevId, retryTimes]() { + bool ret = HasSyncListener(dstDeviceId); + if (!ret) { + return; + } + sptr remoteDms = GetRemoteDms(dstDeviceId); + if (remoteDms == nullptr) { + HILOGI("RetryStartRemoteSyncMission DMS get remoteDms failed"); + RetryStartRemoteSyncMission(dstDeviceId, localDevId, retryTimes + 1); + return; + } + int32_t errNo = PrepareAndSyncMissions(dstDeviceId, remoteDms); + HILOGI("RetryStartRemoteSyncMission result:%{public}d", errNo); + }; + if (missionHandler_ != nullptr && retryTimes < MAX_RETRY_TIMES) { + missionHandler_->PostTask(retryFunc, RETRY_DELAYED); + } +} + +int32_t DistributedSchedMissionManager::UpdateOsdSwitchValueFromRemote(int32_t switchVal, + const std::string& deviceId) +{ + HILOGI("UpdateOsdSwitchValueFromRemote notify start, switchVal: %{public}d, deviceId: %{public}s!", + switchVal, DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + bool needNotifyChanged = false; + bool connCap = false; + int64_t begin = GetTickCount(); + { + std::string uuid = DtbschedmgrDeviceInfoStorage::GetInstance().GetUuidByNetworkId(deviceId); + std::lock_guard autoLock(osdSwitchLock_); + auto iter = osdSwitchValueMap_.find(uuid); + if (iter != osdSwitchValueMap_.end()) { + needNotifyChanged = (iter->second != switchVal); + } else { + needNotifyChanged = true; + } + osdSwitchValueMap_[uuid] = switchVal; + connCap = GetConnCapSupportOsdInnerLocked(deviceId); + } + HILOGI("UpdateOsdSwitchValueFromRemote update value spend %{public}" PRId64 " ms", GetTickCount() - begin); + NotifyOsdSwitchChanged(needNotifyChanged, deviceId, connCap ? switchVal : MISSION_OSD_NOT_SUPPORTED); + HILOGD("UpdateOsdSwitchValueFromRemote end!"); + return ERR_NONE; +} + +void DistributedSchedMissionManager::NotifyOsdSwitchChanged(bool needNotifyChanged, const std::string& deviceId, + int32_t switchVal) +{ + std::lock_guard autoLock(listenDeviceLock_); + if (!needNotifyChanged) { + HILOGI("NotifyOsdSwitchChanged no need to notify!"); + return; + } + auto iter = listenDeviceMap_.find(Str8ToStr16(deviceId)); + if (iter == listenDeviceMap_.end()) { + HILOGI("NotifyOsdSwitchChanged notify no listener!"); + return; + } + + auto& listenerSet = iter->second.listenerSet; + auto notifyChanged = [listenerSet, deviceId, switchVal, this] () { + HILOGI("NotifyOsdSwitchChanged %{public}s!", + DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str()); + bool isSwitchOn = (switchVal == MISSION_OSD_ENABLED); + for (const auto& listener : listenerSet) { + MissionChangedNotify::NotifyOsdSwitchChanged(listener, Str8ToStr16(deviceId), isSwitchOn); + } + }; + if (missionHandler_ != nullptr && !missionHandler_->PostTask(notifyChanged)) { + HILOGE("NotifyOsdSwitchChanged PostTask failed!"); + } +} + +int32_t DistributedSchedMissionManager::UpdateSwitchValueToRemote() +{ + auto callback = [this] () { + std::string localNetworkId; + if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localNetworkId)) { + HILOGE("UpdateSwitchValueToRemote get local uuid failed!"); + return; + } + std::set remoteSyncDeviceSet; + DtbschedmgrDeviceInfoStorage::GetInstance().GetDeviceIdSet(remoteSyncDeviceSet); + UpdateSwitchValueToRemoteInner(remoteSyncDeviceSet, localNetworkId); + }; + if (updateHandler_ == nullptr) { + HILOGE("UpdateSwitchValueToRemote updateHandler_ is nullptr"); + return ERR_NULL_OBJECT; + } + if (!updateHandler_->PostTask(callback)) { + HILOGE("UpdateSwitchValueToRemote PostTask failed!"); + return ERR_NULL_OBJECT; + } + return ERR_NONE; +} + +void DistributedSchedMissionManager::UpdateSwitchValueToRemoteInner(std::set& remoteSyncDeviceSet, + const std::string& localNetworkId) +{ + HILOGD("UpdateSwitchValueToRemote Start"); + for (auto iter = remoteSyncDeviceSet.begin(); iter != remoteSyncDeviceSet.end(); iter++) { + TryUpdateSwitchValueToRemote(localNetworkId, *iter, 0); + } +} + +void DistributedSchedMissionManager::TryUpdateSwitchValueToRemote(const std::string& localNetworkId, + const std::string& destUuid, int32_t retryTime) +{ + std::lock_guard autoLock(remoteSyncDeviceLock_); + auto handler = FetchDeviceHandler(destUuid); + auto callback = [retryTime, localNetworkId, destUuid, this] () { + sptr remoteDms = GetRemoteDms(destUuid); + int32_t result = ERR_FLATTEN_OBJECT; + if (remoteDms != nullptr) { + int64_t begin = GetTickCount(); + int32_t switchVal = DistributedSchedAdapter::GetInstance().GetOsdSwitch(); + HILOGI("TryUpdateSwitchValueToRemote switchVal: %{public}d, destUuid: %{public}s retry:%{public}d", + switchVal, DnetworkAdapter::AnonymizeDeviceId(destUuid).c_str(), retryTime); + if (!IsValidOsdSwitchValue(switchVal)) { + HILOGI("UpdateSwitchValueToRemote invalid switch value %{public}d!", switchVal); + return; + } + result = remoteDms->UpdateOsdSwitchValueFromRemote(switchVal, localNetworkId); + HILOGI("[PerformanceTest] TryUpdateSwitchValueToRemote ret:%d, spend %{public}" PRId64 " ms", + result, GetTickCount() - begin); + } else { + HILOGE("TryUpdateSwitchValueToRemote DMS get remoteDms failed"); + } + if (result == IPC_STUB_UNKNOW_TRANS_ERR) { + HILOGI("TryUpdateSwitchValueToRemote destUuid: %{public}s does not support osd result: %{public}d", + DnetworkAdapter::AnonymizeDeviceId(destUuid).c_str(), result); + return; + } + if (result != ERR_NONE) { + TryUpdateSwitchValueToRemote(localNetworkId, destUuid, retryTime + 1); + HILOGI("DMS TryUpdateSwitchValueToRemote retry"); + } + HILOGI("DMS TryUpdateSwitchValueToRemote result:%{public}d", result); + }; + if (handler != nullptr && retryTime < MAX_RETRY_TIMES) { + handler->PostTask(callback, DELAY_TIME); + } +} + +bool DistributedSchedMissionManager::IsValidOsdSwitchValue(int32_t osdSwitchVal) +{ + return osdSwitchVal == MISSION_OSD_NOT_SUPPORTED || osdSwitchVal == MISSION_OSD_NOT_ENABLED || + osdSwitchVal == MISSION_OSD_ENABLED || osdSwitchVal == MISSION_OSD_CCM_NOT_SUPPORTED || + osdSwitchVal == MISSION_OSD_WIFI_OFF || osdSwitchVal == MISSION_OSD_CHILDMODE_ON || + osdSwitchVal == MISSION_OSD_CLOUD_SWITCH_OFF; +} + +void DistributedSchedMissionManager::OnMissionListenerDied(const sptr& remote) +{ + HILOGI("OnMissionListenerDied"); + std::set deviceSet; + { + std::lock_guard autoLock(listenDeviceLock_); + auto iterItem = listenDeviceMap_.begin(); + while (iterItem != listenDeviceMap_.end()) { + auto& listenerInfo = iterItem->second; + auto ret = listenerInfo.Find(remote); + if (!ret) { + ++iterItem; + continue; + } + remote->RemoveDeathRecipient(listenerDeath_); + listenerInfo.Erase(remote); + if (listenerInfo.Empty()) { + if (listenerInfo.called) { + deviceSet.emplace(Str16ToStr8(iterItem->first)); + } + iterItem = listenDeviceMap_.erase(iterItem); + } else { + ++iterItem; + } + } + } + if (deviceSet.empty()) { + return; + } + for (auto& devId : deviceSet) { + UnRegisterRemoteMissionListenerInner(devId, false); + } +} + +void DistributedSchedMissionManager::OnRemoteDmsDied(const sptr& remote) +{ + HILOGI("OnRemoteDmsDied"); + std::string devId; + { + std::lock_guard autoLock(remoteDmsLock_); + for (auto iter = remoteDmsMap_.begin(); iter != remoteDmsMap_.end(); ++iter) { + if (iter->second->AsObject() == remote) { + iter->second->AsObject()->RemoveDeathRecipient(remoteDmsRecipient_); + devId = iter->first; + remoteDmsMap_.erase(iter); + break; + } + } + } + if (devId.empty()) { + return; + } + bool ret = HasSyncListener(devId); + if (ret) { + std::string localDeviceId; + if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localDeviceId)) { + return; + } + RetryStartRemoteSyncMission(devId, localDeviceId, 0); + } +} + +void DistributedSchedMissionManager::NotifyDmsProxyProcessDied() +{ + HILOGI("NotifyDmsProxyProcessDied!"); + std::lock_guard autoLock(remoteSyncDeviceLock_); + if (!isRegMissionChange_) { + return; + } + RetryRegisterMissionChange(0); +} + +void DistributedSchedMissionManager::RetryRegisterMissionChange(int32_t retryTimes) +{ + auto remoteDiedFunc = [this, retryTimes]() { + HILOGI("RetryRegisterMissionChange retryTimes:%{public}d begin", retryTimes); + { + std::lock_guard autoLock(remoteSyncDeviceLock_); + if (!isRegMissionChange_) { + return; + } + } + int32_t ret = DistributedSchedAdapter::GetInstance().RegisterMissionChange(true); + if (ret == ERR_NULL_OBJECT) { + RetryRegisterMissionChange(retryTimes + 1); + HILOGI("RetryRegisterMissionChange dmsproxy null, retry!"); + return; + } + HILOGI("RetryRegisterMissionChange result:%{public}d", ret); + }; + if (missionHandler_ != nullptr && retryTimes < MAX_RETRY_TIMES) { + missionHandler_->PostTask(remoteDiedFunc, RETRY_DELAYED); + } +} + +void DistributedSchedMissionManager::OnDnetDied() +{ + auto dnetDiedFunc = [this]() { + HILOGI("OnDnetDied"); + std::lock_guard autoLock(remoteSyncDeviceLock_); + if (!isRegMissionChange_) { + return; + } + remoteSyncDeviceSet_.clear(); + DistributedSchedAdapter::GetInstance().RegisterMissionChange(false); + DistributedSchedAdapter::GetInstance().OnOsdEventOccur(UNREGISTER_MISSION_LISTENER); + isRegMissionChange_ = false; + }; + if (missionHandler_ != nullptr) { + missionHandler_->PostTask(dnetDiedFunc); + } +} +} // naemespace DistributedSchedule +} // namespace OHOS diff --git a/services/dtbschedmgr/src/mission/mission_changed_notify.cpp b/services/dtbschedmgr/src/mission/mission_changed_notify.cpp new file mode 100644 index 00000000..b82f8e1a --- /dev/null +++ b/services/dtbschedmgr/src/mission/mission_changed_notify.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mission/mission_changed_notify.h" + +#include "datetime_ex.h" +#include "parcel_helper.h" + +namespace OHOS { +namespace DistributedSchedule { +namespace { +constexpr int32_t CODE_NOTIFY_MISSION = 1; +constexpr int32_t NOTIFY_SNAP_SHOT = 2; +constexpr int32_t NOTIFY_NET_DISCONNECT = 3; +constexpr int32_t CODE_NOTIFY_SWITCH = 4; + +const std::u16string DESCRIPTOR = u"ohos.distributedschedule.dmissionmanagerkit.IDistributedMissionChangedListener"; +const std::string TAG = "MissionChangedNotify"; +} +void MissionChangedNotify::NotifyMissionsChanged(const sptr& remoteObject, + const std::u16string& deviceId) +{ + if (remoteObject == nullptr) { + HILOGE("NotifyMissionsChanged remote service is null!"); + return; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!data.WriteInterfaceToken(DESCRIPTOR)) { + HILOGE("NotifyMissionsChanged write interface token failed!"); + return; + } + PARCEL_WRITE_HELPER_NORET(data, String16, deviceId); + HILOGI("[PerformanceTest] NotifyMissionsChanged called, IPC begin = %{public}" PRId64, GetTickCount()); + int32_t error = remoteObject->SendRequest(CODE_NOTIFY_MISSION, data, reply, option); + if (error != ERR_NONE) { + HILOGE("NotifyMissionsChanged fail, error: %{public}d", error); + return; + } + HILOGI("NotifyMissionsChanged finished!"); +} + +void MissionChangedNotify::NotifySnapshot(const sptr& remoteObject, const std::u16string& deviceId, + int32_t missionId) +{ + if (remoteObject == nullptr) { + HILOGE("NotifySnapshot remote service is null!"); + return; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!data.WriteInterfaceToken(DESCRIPTOR)) { + HILOGE("NotifySnapshot write interface token failed!"); + return; + } + PARCEL_WRITE_HELPER_NORET(data, String16, deviceId); + PARCEL_WRITE_HELPER_NORET(data, Int32, missionId); + HILOGI("[PerformanceTest] NotifySnapshot called, IPC begin = %{public}" PRId64, GetTickCount()); + int32_t error = remoteObject->SendRequest(NOTIFY_SNAP_SHOT, data, reply, option); + if (error != ERR_NONE) { + HILOGE("NotifySnapshot fail, error: %{public}d", error); + return; + } + HILOGI("NotifySnapshot finished!"); +} + +void MissionChangedNotify::NotifyNetDisconnect(const sptr& remoteObject, const std::u16string& deviceId, + int32_t state) +{ + if (remoteObject == nullptr) { + HILOGE("NotifyNetDisconnect remote service is null!"); + return; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!data.WriteInterfaceToken(DESCRIPTOR)) { + HILOGE("NotifyNetDisconnect write interface token failed!"); + return; + } + PARCEL_WRITE_HELPER_NORET(data, String16, deviceId); + PARCEL_WRITE_HELPER_NORET(data, Int32, state); + HILOGI("[PerformanceTest] NotifyNetDisconnect called, IPC begin = %{public}" PRId64, GetTickCount()); + int32_t error = remoteObject->SendRequest(NOTIFY_NET_DISCONNECT, data, reply, option); + if (error != ERR_NONE) { + HILOGE("NotifyNetDisconnect fail, error: %{public}d", error); + return; + } + HILOGI("NotifyNetDisconnect finished!"); +} + +void MissionChangedNotify::NotifyOsdSwitchChanged(const sptr& remoteObject, + const std::u16string& deviceId, bool isSwitchOn) +{ + HILOGI("NotifyOsdSwitchChanged start!"); + if (remoteObject == nullptr) { + HILOGE("NotifyOsdSwitchChanged remote service is null!"); + return; + } + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!data.WriteInterfaceToken(DESCRIPTOR)) { + HILOGE("NotifyOsdSwitchChanged write interface token failed!"); + return; + } + PARCEL_WRITE_HELPER_NORET(data, String16, deviceId); + PARCEL_WRITE_HELPER_NORET(data, Bool, isSwitchOn); + HILOGI("[PerformanceTest] NotifyOsdSwitchChanged called, IPC begin = %{public}" PRId64, GetTickCount()); + int32_t error = remoteObject->SendRequest(CODE_NOTIFY_SWITCH, data, reply, option); + if (error != ERR_NONE) { + HILOGE("NotifyOsdSwitchChanged fail, error: %{public}d", error); + return; + } + HILOGI("NotifyOsdSwitchChanged finished!"); +} +} // namespace DistributedSchedule +} // namespace OHOS diff --git a/services/dtbschedmgr/src/mission/mission_info.cpp b/services/dtbschedmgr/src/mission/mission_info.cpp new file mode 100644 index 00000000..57377345 --- /dev/null +++ b/services/dtbschedmgr/src/mission/mission_info.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mission/mission_info.h" + +#include "adapter/adapter_constant.h" +#include "dtbschedmgr_log.h" +#include "parcel_helper.h" +#include "string_ex.h" + +namespace OHOS { +namespace DistributedSchedule { +using namespace Constants::Adapter; +namespace { +const std::string TAG = "MissionInfo"; +} + +bool MissionInfo::ReadFromParcel(Parcel& parcel) +{ + id = parcel.ReadInt32(); + runingState = parcel.ReadInt32(); + userId = parcel.ReadInt32(); + missionStackId = parcel.ReadInt32(); + if (!parcel.ReadInt32Vector(&combinedMissionIds)) { + return false; + } + windowMode = parcel.ReadInt32(); + boundsLeft = parcel.ReadInt32(); + boundsTop = parcel.ReadInt32(); + boundsRight = parcel.ReadInt32(); + boundsBottom = parcel.ReadInt32(); + baseWant.reset(parcel.ReadParcelable()); + topAbility.reset(parcel.ReadParcelable()); + baseAbility.reset(parcel.ReadParcelable()); + reservedAbility.reset(parcel.ReadParcelable()); + lastMissionActiveTime = parcel.ReadInt64(); + displayId = parcel.ReadInt32(); + label = Str16ToStr8(parcel.ReadString16()); + size = parcel.ReadInt32(); + iconPath = Str16ToStr8(parcel.ReadString16()); + color = parcel.ReadInt32(); + windowType = parcel.ReadInt32(); + supportsMultiWindow = parcel.ReadBool(); + missionType = parcel.ReadInt32(); + windowTypeMode = parcel.ReadInt32(); + + return true; +} + +MissionInfo* MissionInfo::Unmarshalling(Parcel& parcel) +{ + MissionInfo* info = new MissionInfo(); + if (info && !info->ReadFromParcel(parcel)) { + HILOGE("read from parcel failed!"); + delete info; + info = nullptr; + } + return info; +} + +bool MissionInfo::Marshalling(Parcel& parcel) const +{ + PARCEL_WRITE_HELPER_RET(parcel, Int32, id, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, runingState, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, userId, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, missionStackId, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32Vector, combinedMissionIds, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, windowMode, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, boundsLeft, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, boundsTop, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, boundsRight, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, boundsBottom, false); + PARCEL_WRITE_HELPER_RET(parcel, Parcelable, baseWant.get(), false); + PARCEL_WRITE_HELPER_RET(parcel, Parcelable, topAbility.get(), false); + PARCEL_WRITE_HELPER_RET(parcel, Parcelable, baseAbility.get(), false); + PARCEL_WRITE_HELPER_RET(parcel, Parcelable, reservedAbility.get(), false); + PARCEL_WRITE_HELPER_RET(parcel, Int64, lastMissionActiveTime, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, displayId, false); + PARCEL_WRITE_HELPER_RET(parcel, String16, Str8ToStr16(label), false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, size, false); + PARCEL_WRITE_HELPER_RET(parcel, String16, Str8ToStr16(iconPath), false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, color, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, windowType, false); + PARCEL_WRITE_HELPER_RET(parcel, Bool, supportsMultiWindow, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, missionType, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, windowTypeMode, false); + + return true; +} + +bool MissionInfo::ReadMissionInfoVectorFromParcel(Parcel& parcel, std::vector &missionInfos) +{ + int32_t empty = parcel.ReadInt32(); + if (empty == VALUE_OBJECT) { + int32_t len = parcel.ReadInt32(); + HILOGD("ReadMissionInfoVectorFromParcel::readLength is:%{public}d", len); + if (len < 0) { + return false; + } + size_t size = static_cast(len); + if ((size > parcel.GetReadableBytes()) || (missionInfos.max_size() < size)) { + HILOGE("Failed to read MissionInfo vector, size = %{public}zu", size); + return false; + } + missionInfos.clear(); + for (size_t i = 0; i < size; i++) { + MissionInfo *ptr = parcel.ReadParcelable(); + if (ptr == nullptr) { + return false; + } + HILOGD("read MissionInfo is:%{private}s", ptr->ToString().c_str()); + missionInfos.emplace_back(*ptr); + delete ptr; + } + } + + HILOGI("read ReadMissionInfoVectorFromParcel end. info size is:%{public}zu", missionInfos.size()); + return true; +} + +bool MissionInfo::WriteMissionInfoVectorFromParcel(Parcel& parcel, const std::vector &missionInfos) +{ + size_t size = missionInfos.size(); + if (size == 0) { + PARCEL_WRITE_HELPER_RET(parcel, Int32, VALUE_NULL, false); + return true; + } + + PARCEL_WRITE_HELPER_RET(parcel, Int32, VALUE_OBJECT, false); + PARCEL_WRITE_HELPER_RET(parcel, Int32, size, false); + for (auto& info : missionInfos) { + PARCEL_WRITE_HELPER_RET(parcel, Parcelable, &info, false); + } + return true; +} + +std::string MissionInfo::ToString() const +{ + std::string str = "id: " + std::to_string(id); + str += " runingState: " + std::to_string(runingState); + str += " userId: " + std::to_string(userId); + str += " missionStackId: " + std::to_string(missionStackId); + str += " windowMode: " + std::to_string(windowMode); + str += " boundsLeft: " + std::to_string(boundsLeft); + str += " boundsTop: " + std::to_string(boundsTop); + str += " boundsRight: " + std::to_string(boundsRight); + str += " boundsBottom: " + std::to_string(boundsBottom); + if (baseWant == nullptr) { + str += " baseWant: nullptr"; + } else { + str += " baseWant: " + baseWant->GetBundle(); + } + if (topAbility == nullptr) { + str += " topAbility: nullptr"; + } else { + str += " topAbility: " + topAbility->GetBundleName(); + } + if (baseAbility == nullptr) { + str += " baseAbility: nullptr"; + } else { + str += " baseAbility: " + baseAbility->GetBundleName(); + } + if (reservedAbility == nullptr) { + str += " reservedAbility: nullptr"; + } else { + str += " reservedAbility: " + reservedAbility->GetBundleName(); + } + str += " lastMissionActiveTime: " + std::to_string(lastMissionActiveTime); + str += " displayId: " + std::to_string(displayId); + str += " label: " + label; + str += " size: " + std::to_string(size); + str += " iconPath: " + iconPath; + str += " color: " + std::to_string(color); + str += " windowType: " + std::to_string(windowType); + str += " supportsMultiWindow: "; + str += supportsMultiWindow ? "true" : "false"; + str += " missionType: " + std::to_string(missionType); + str += " windowTypeMode: " + std::to_string(windowTypeMode); + return str; +} +} // namespace DistributedSchedule +} // namespace OHOS \ No newline at end of file diff --git a/services/dtbschedmgr/src/mission/mission_info_converter.cpp b/services/dtbschedmgr/src/mission/mission_info_converter.cpp new file mode 100644 index 00000000..947d6cba --- /dev/null +++ b/services/dtbschedmgr/src/mission/mission_info_converter.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mission/mission_info_converter.h" + +#include "dtbschedmgr_log.h" + +using namespace std; + +namespace OHOS { +namespace DistributedSchedule { +int32_t MissionInfoConverter::ConvertToMissionInfos(std::vector& abilityMissionInfos, + std::vector& missionInfos) +{ + if (abilityMissionInfos.empty()) { + return INVALID_PARAMETERS_ERR; + } + for (auto iter = abilityMissionInfos.begin(); iter != abilityMissionInfos.end(); iter++) { + MissionInfo missionInfo; + missionInfo.id = iter->id; + missionInfo.runingState = iter->runingState; + missionInfo.missionStackId = iter->missionStackId; + shared_ptr spWant = make_shared(iter->baseWant); + missionInfo.baseWant = spWant; + shared_ptr spTopAbility = make_shared(iter->topAbility); + missionInfo.topAbility = spTopAbility; + shared_ptr spBaseAbility = make_shared(iter->baseAbility); + missionInfo.baseAbility = spBaseAbility; + missionInfo.size = iter->size; + missionInfo.label = iter->missionDescription.label; + missionInfo.iconPath = iter->missionDescription.iconPath; + missionInfos.push_back(missionInfo); + } + return ERR_OK; +} + +int32_t MissionInfoConverter::ConvertToAbilityMissionInfos(std::vector& missionInfos, + std::vector& abilityMissionInfos) +{ + if (missionInfos.empty()) { + return INVALID_PARAMETERS_ERR; + } + for (auto iter = missionInfos.begin(); iter != missionInfos.end(); iter++) { + AbilityMissionInfo missionInfo; + missionInfo.id = iter->id; + missionInfo.runingState = iter->runingState; + missionInfo.missionStackId = iter->missionStackId; + missionInfo.baseWant = *(iter->baseWant); + missionInfo.topAbility = *(iter->topAbility); + missionInfo.baseAbility = *(iter->baseAbility); + missionInfo.size = iter->size; + missionInfo.missionDescription.label = iter->label; + missionInfo.missionDescription.iconPath = iter->iconPath; + abilityMissionInfos.push_back(missionInfo); + } + return ERR_OK; +} +} +} diff --git a/services/dtbschedmgr/src/mission/snapshot.cpp b/services/dtbschedmgr/src/mission/snapshot.cpp new file mode 100644 index 00000000..2eb52079 --- /dev/null +++ b/services/dtbschedmgr/src/mission/snapshot.cpp @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "datetime_ex.h" +#include "dtbschedmgr_log.h" +#include "image_source.h" +#include "mission/snapshot.h" +#include "parcel_helper.h" +#include "pixel_map_parcel.h" +#include "string_ex.h" + +using namespace std; +using namespace OHOS::Media; + +namespace OHOS { +namespace DistributedSchedule { +namespace { +const std::string TAG = "Snapshot"; +} + +Snapshot::~Snapshot() +{ + HILOGD("Snapshot destruct!"); +} + +bool Snapshot::WriteToParcel(MessageParcel& data) const +{ + PARCEL_WRITE_HELPER_RET(data, Int32, 1, false); + PARCEL_WRITE_HELPER_RET(data, Int32, orientation_, false); + if (rect_ != nullptr) { + PARCEL_WRITE_HELPER_RET(data, Parcelable, rect_.get(), false); + } else { + PARCEL_WRITE_HELPER_RET(data, Parcelable, nullptr, false); + } + PARCEL_WRITE_HELPER_RET(data, Bool, reducedResolution_, false); + PARCEL_WRITE_HELPER_RET(data, Float, scale_, false); + PARCEL_WRITE_HELPER_RET(data, Bool, isRealSnapshot_, false); + PARCEL_WRITE_HELPER_RET(data, Int32, windowingMode_, false); + PARCEL_WRITE_HELPER_RET(data, Int32, systemUiVisibility_, false); + PARCEL_WRITE_HELPER_RET(data, Bool, isTranslucent_, false); + if (windowBounds_ != nullptr) { + PARCEL_WRITE_HELPER_RET(data, Parcelable, windowBounds_.get(), false); + } else { + PARCEL_WRITE_HELPER_RET(data, Parcelable, nullptr, false); + } + PARCEL_WRITE_HELPER_RET(data, String16, applicationLabel_, false); + PARCEL_WRITE_HELPER_RET(data, String16, activityLabel_, false); + PARCEL_WRITE_HELPER_RET(data, UInt8Vector, icon_, false); + PARCEL_WRITE_HELPER_RET(data, String16, secApplicationLabel_, false); + PARCEL_WRITE_HELPER_RET(data, String16, secActivityLabel_, false); + PARCEL_WRITE_HELPER_RET(data, UInt8Vector, secIcon_, false); + PARCEL_WRITE_HELPER_RET(data, String16, sourceDeviceTips_, false); + if (pixelMap_ != nullptr) { + PARCEL_WRITE_HELPER_RET(data, Int32, 1, false); + bool ret = PixelMapParcel::WriteToParcel(pixelMap_.get(), data); + if (!ret) { + HILOGE("Snapshot WriteToParcel pixelMap failed!"); + return false; + } + } else { + PARCEL_WRITE_HELPER_RET(data, Parcelable, nullptr, false); + } + return true; +} + +unique_ptr Snapshot::FillSnapShot(MessageParcel& data) +{ + int32_t version = 0; + PARCEL_READ_HELPER_RET(data, Int32, version, nullptr); + int32_t orientation = 0; + PARCEL_READ_HELPER_RET(data, Int32, orientation, nullptr); + unique_ptr rect(data.ReadParcelable()); + bool reduced = false; + PARCEL_READ_HELPER_RET(data, Bool, reduced, nullptr); + float scale = 0.0; + PARCEL_READ_HELPER_RET(data, Float, scale, nullptr); + bool isRealSnapshot = false; + PARCEL_READ_HELPER_RET(data, Bool, isRealSnapshot, nullptr); + int32_t windowingMode = 0; + PARCEL_READ_HELPER_RET(data, Int32, windowingMode, nullptr); + int32_t systemUiVisibility = 0; + PARCEL_READ_HELPER_RET(data, Int32, systemUiVisibility, nullptr); + bool isTranslucent = false; + PARCEL_READ_HELPER_RET(data, Bool, isTranslucent, nullptr); + unique_ptr windowBounds(data.ReadParcelable()); + std::u16string applicationLabel = data.ReadString16(); + std::u16string activityLabel = data.ReadString16(); + std::vector icon; + PARCEL_READ_HELPER_RET(data, UInt8Vector, &icon, nullptr); + std::u16string secApplicationLabel = data.ReadString16(); + std::u16string secActivityLabel = data.ReadString16(); + std::vector secIcon; + PARCEL_READ_HELPER_RET(data, UInt8Vector, &secIcon, nullptr); + std::u16string sourceDeviceTips = data.ReadString16(); + unique_ptr snapShot = make_unique(); + snapShot->version_ = version; + snapShot->orientation_ = orientation; + snapShot->rect_ = std::move(rect); + snapShot->reducedResolution_ = reduced; + snapShot->scale_ = scale; + snapShot->isRealSnapshot_ = isRealSnapshot; + snapShot->windowingMode_ = windowingMode; + snapShot->systemUiVisibility_ = systemUiVisibility; + snapShot->isTranslucent_ = isTranslucent; + snapShot->windowBounds_ = std::move(windowBounds); + snapShot->applicationLabel_ = applicationLabel; + snapShot->activityLabel_ = activityLabel; + snapShot->icon_ = icon; + snapShot->secApplicationLabel_ = secApplicationLabel; + snapShot->secActivityLabel_ = secActivityLabel; + snapShot->secIcon_ = secIcon; + snapShot->sourceDeviceTips_ = sourceDeviceTips; + return snapShot; +} + +unique_ptr Snapshot::CreatePixelMap(const uint8_t* buffer, uint32_t bufferSize) +{ + if (buffer == nullptr || bufferSize == 0) { + HILOGE("Snapshot CreatePixelMap invalid params !"); + return nullptr; + } + SourceOptions opts; + uint32_t errCode = 0; + opts.formatHint = "image/jpeg"; + unique_ptr imageSource = ImageSource::CreateImageSource(buffer, bufferSize, opts, errCode); + if (imageSource == nullptr) { + HILOGE("Snapshot CreatePixelMap create image source failed!"); + return nullptr; + } + DecodeOptions decodeOpt; + decodeOpt.allocatorType = AllocatorType::SHARE_MEM_ALLOC; + decodeOpt.desiredPixelFormat = PixelFormat::RGB_565; + int64_t begin = GetTickCount(); + unique_ptr pixelMap = imageSource->CreatePixelMap(decodeOpt, errCode); + HILOGI("[PerformanceTest] Create PixelMap spend %{public}" PRId64 " ms", GetTickCount() - begin); + if (pixelMap == nullptr || errCode != 0) { + HILOGW("Snapshot: CreatePixelMap failed, errCode:%{public}d!", errCode); + return nullptr; + } + return pixelMap; +} + +unique_ptr Snapshot::Create(const vector& data) +{ + auto dataBuffer = data.data(); + auto totalSize = data.size(); + if (totalSize < sizeof(int32_t)) { + HILOGE("Snapshot invalid data !"); + return nullptr; + } + uint32_t msgSize = *reinterpret_cast(dataBuffer); + if (msgSize >= totalSize || msgSize + sizeof(uint32_t) >= totalSize) { + HILOGE("Snapshot dataParcel invalid data !"); + return nullptr; + } + dataBuffer += sizeof(uint32_t); + MessageParcel dataParcel; + bool ret = dataParcel.WriteBuffer(dataBuffer, msgSize); + if (!ret) { + HILOGE("Snapshot dataParcel write failed!"); + return nullptr; + } + unique_ptr snapShot = FillSnapShot(dataParcel); + if (snapShot == nullptr) { + HILOGW("Snapshot: FillSnapShot failed!"); + return nullptr; + } + dataBuffer += msgSize; + uint32_t remainSize = totalSize - msgSize - sizeof(uint32_t); + if (remainSize < sizeof(uint32_t)) { + HILOGE("Snapshot dataParcel remainSize invalid!"); + return nullptr; + } + uint32_t pixelmapLen = *reinterpret_cast(dataBuffer); + if (pixelmapLen >= remainSize || pixelmapLen + sizeof(uint32_t) > remainSize) { + HILOGE("Snapshot dataParcel buffer broken, should not happens!"); + return nullptr; + } + dataBuffer += sizeof(uint32_t); + unique_ptr pixelMap = CreatePixelMap(dataBuffer, pixelmapLen); + if (pixelMap != nullptr) { + HILOGD("Snapshot: dataParcel pixelMap width:%d, height:%d, byteCount:%d, pixelformat:%d", + pixelMap->GetWidth(), pixelMap->GetHeight(), pixelMap->GetByteCount(), + static_cast(pixelMap->GetPixelFormat())); + snapShot->pixelMap_ = std::move(pixelMap); + } + snapShot->createdTime_ = GetTickCount(); + snapShot->lastAccessTime_ = snapShot->createdTime_; + return snapShot; +} + +int64_t Snapshot::GetCreatedTime() const +{ + return createdTime_; +} + +int64_t Snapshot::GetLastAccessTime() const +{ + return lastAccessTime_; +} + +void Snapshot::UpdateLastAccessTime(int64_t accessTime) +{ + lastAccessTime_ = accessTime; +} +} +} diff --git a/services/dtbschedmgr/test/BUILD.gn b/services/dtbschedmgr/test/BUILD.gn old mode 100755 new mode 100644 index eb9475c6..c9727c57 --- a/services/dtbschedmgr/test/BUILD.gn +++ b/services/dtbschedmgr/test/BUILD.gn @@ -38,8 +38,10 @@ dsched_deps = [ "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//utils/native/base:utils", ] @@ -56,14 +58,13 @@ dsched_public_deps = [ ] dtbschedmgr_sources = [ + "${distributed_service}/dtbschedmgr/src/ability_connection_wrapper_proxy.cpp", "${distributed_service}/dtbschedmgr/src/ability_connection_wrapper_stub.cpp", "${distributed_service}/dtbschedmgr/src/adapter/dnetwork_adapter.cpp", "${distributed_service}/dtbschedmgr/src/bundle/bundle_manager_internal.cpp", "${distributed_service}/dtbschedmgr/src/connect_death_recipient.cpp", - "${distributed_service}/dtbschedmgr/src/continuation_callback_death_recipient.cpp", "${distributed_service}/dtbschedmgr/src/deviceManager/dms_device_info.cpp", "${distributed_service}/dtbschedmgr/src/distributed_device_node_listener.cpp", - "${distributed_service}/dtbschedmgr/src/distributed_sched_ability_shell.cpp", "${distributed_service}/dtbschedmgr/src/distributed_sched_adapter.cpp", "${distributed_service}/dtbschedmgr/src/distributed_sched_continuation.cpp", "${distributed_service}/dtbschedmgr/src/distributed_sched_dumper.cpp", @@ -72,6 +73,13 @@ dtbschedmgr_sources = [ "${distributed_service}/dtbschedmgr/src/distributed_sched_service.cpp", "${distributed_service}/dtbschedmgr/src/distributed_sched_stub.cpp", "${distributed_service}/dtbschedmgr/src/dtbschedmgr_device_info_storage.cpp", + "${distributed_service}/dtbschedmgr/src/mission/distributed_data_change_listener.cpp", + "${distributed_service}/dtbschedmgr/src/mission/distributed_data_storage.cpp", + "${distributed_service}/dtbschedmgr/src/mission/distributed_sched_mission_manager.cpp", + "${distributed_service}/dtbschedmgr/src/mission/mission_changed_notify.cpp", + "${distributed_service}/dtbschedmgr/src/mission/mission_info.cpp", + "${distributed_service}/dtbschedmgr/src/mission/mission_info_converter.cpp", + "${distributed_service}/dtbschedmgr/src/mission/snapshot.cpp", ] ohos_unittest("distributedschedsvrtest") { @@ -92,7 +100,6 @@ ohos_unittest("dschedcontinuetest") { module_out_path = module_output_path sources = [ - "unittest/distributed_sched_ability_shell_test.cpp", "unittest/distributed_sched_continuation_test.cpp", "unittest/mock_distributed_sched.cpp", ] @@ -134,12 +141,26 @@ ohos_unittest("dschedpermissiontest") { } } +ohos_unittest("dschedmissionmanagertest") { + module_out_path = module_output_path + sources = [ "unittest/mission/dms_mission_manager_test.cpp" ] + configs = [ ":test_config" ] + configs += dsched_configs + deps = dsched_deps + deps += [ "${distributed_service}/dtbschedmgr:distributedschedsvr" ] + if (is_standard_system) { + external_deps = dsched_external_deps + public_deps = dsched_public_deps + } +} + group("unittest") { testonly = true deps = [ ":distributedschedsvrtest", ":dschedconnecttest", ":dschedcontinuetest", + ":dschedmissionmanagertest", ":dschedpermissiontest", ] } diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/build.gradle b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/build.gradle new file mode 100644 index 00000000..c2c8bbae --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/build.gradle @@ -0,0 +1,34 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +apply plugin: 'com.huawei.ohos.app' + +//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 +ohos { + compileSdkVersion 7 + supportSystem "standard" +} + +buildscript { + repositories { + maven { + url 'https://repo.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + } + dependencies { + classpath 'com.huawei.ohos:hap:3.0.3.4' + classpath 'com.huawei.ohos:decctest:1.2.6.0' + } +} + +allprojects { + repositories { + maven { + url 'https://repo.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + } +} diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/build.gradle b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/build.gradle new file mode 100644 index 00000000..fa90d267 --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/build.gradle @@ -0,0 +1,22 @@ +apply plugin: 'com.huawei.ohos.hap' +//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 +ohos { + compileSdkVersion 7 + defaultConfig { + compatibleSdkVersion 7 + } + buildTypes { + release { + proguardOpt { + proguardEnabled false + rulesFiles 'proguard-rules.pro' + } + } + } + arkEnabled false +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) + testImplementation 'junit:junit:4.13.1' +} diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/config.json b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/config.json new file mode 100644 index 00000000..ed424311 --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/config.json @@ -0,0 +1,102 @@ +{ + "app": { + "bundleName": "ohos.dms.etsDemo", + "vendor": "dms", + "version": { + "code": 1000000, + "name": "1.0.0" + } + }, + "deviceConfig": {}, + "module": { + "package": "ohos.dms.etsDemo", + "name": ".MyApplication", + "mainAbility": ".RemoteAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry", + "installationFree": false + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "RemoteAbility", + "name": ".RemoteAbility", + "srcLanguage": "ets", + "icon": "$media:icon", + "description": "$string:description_remoteability", + "formsEnabled": false, + "label": "$string:entry_MainAbility", + "type": "page", + "launchType": "standard" + }, + { + "orientation": "unspecified", + "visible": true, + "srcPath": "LocalAbility", + "name": ".LocalAbility", + "srcLanguage": "ets", + "icon": "$media:icon", + "description": "$string:description_localability", + "formsEnabled": false, + "label": "$string:entry_MainAbility", + "type": "page", + "launchType": "standard" + }, + { + "visible": true, + "srcPath": "ServiceAbility", + "name": ".ServiceAbility", + "icon": "$media:icon", + "srcLanguage": "ets", + "description": "$string:description_serviceability", + "type": "service" + } + ], + "js": [ + { + "mode": { + "syntax": "ets", + "type": "pageAbility" + }, + "pages": [ + "pages/index" + ], + "name": ".RemoteAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + }, + { + "mode": { + "syntax": "ets", + "type": "pageAbility" + }, + "pages": [ + "pages/index" + ], + "name": ".LocalAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/app.ets b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/app.ets new file mode 100644 index 00000000..bf28e58b --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/app.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + onCreate() { + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/pages/index.ets b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/pages/index.ets new file mode 100644 index 00000000..5f048476 --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/LocalAbility/pages/index.ets @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@Entry +@Component +struct Index { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Second Ability') + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + .height('100%') + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/app.ets b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/app.ets new file mode 100644 index 00000000..0f712ef1 --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/app.ets @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + onCreate() { + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + onStartContinuation() { + console.info('onStartContinuation'); + return true; + }, + onRestoreData(data) { + console.info('onRestoreData' + data); + return true; + }, + onSaveData(data) { + console.info('onSaveData'); + return true; + }, + onCompleteContinuation(result) { + console.info('onCompleteContinuation:' + result); + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/pages/index.ets b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/pages/index.ets new file mode 100644 index 00000000..007c761d --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/RemoteAbility/pages/index.ets @@ -0,0 +1,543 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import featureAbility from '@ohos.ability.featureAbility'; +import prompt from '@system.prompt'; +import rpc from "@ohos.rpc"; +import RemoteDeviceModel from '../../model/RemoteDeviceModel.ets'; + +var connectedAbility; +var localDeviceId = ""; +var mRemote; +var remoteDeviceModel = new RemoteDeviceModel; +var mIndex; +var mDiscoveredSize = 0; +var mDeviceSize = 0; + +enum Operation { + AuthDeviceOperation, + StartRemoteAbilityOperation, + ContinueAbilityOperation, + ConnectRemoteServiceOperation, +} +let mOperation = Operation.AuthDeviceOperation; + +function RegisterDeviceListCallback() { + console.info('[dmsDemo] RegisterDeviceListCallback begin'); + remoteDeviceModel.registerDeviceListCallback(() => { + console.info('[dmsDemo] RegisterDeviceListCallback, callback entered'); + let discoveredDevices = remoteDeviceModel.discoverList.length; + let numDevices = remoteDeviceModel.deviceList.length; + mDiscoveredSize = discoveredDevices; + mDeviceSize = numDevices; + console.info('[dmsDemo] mDiscoveredSize =' + mDiscoveredSize); + console.info('[dmsDemo] mDeviceSize =' + mDeviceSize); + console.info('[dmsDemo] RegisterDeviceListCallback on remote device updated, count=' + numDevices); + if (numDevices === 0) { + if (discoveredDevices > 0) { + prompt.showToast({ + message: "RegisterDeviceListCallback dicovered " + discoveredDevices + " devices, need to authenticate" + }); + } else { + prompt.showToast({ + message: "RegisterDeviceListCallback no device discovered" + }); + } + } + if (numDevices >= 1) { + prompt.showToast({ + message: "RegisterDeviceListCallback at least one device is successfully networked" + }); + } + }); + console.info('[dmsDemo] RegisterDeviceListCallback end'); +} + +function AuthDevice(index) { + console.info('[dmsDemo] AuthDevice begin'); + if (remoteDeviceModel.deviceList.length >= 1 && remoteDeviceModel.discoverList.length == 0) { + prompt.showToast({ + message: "AuthDevice all devices networking success, no need authenticate" + }); + return; + } + if (remoteDeviceModel.discoverList.length > 0) { + remoteDeviceModel.authDevice(remoteDeviceModel.discoverList[index - 1].deviceId, () => { + console.info('[dmsDemo] AuthDevice, callback entered'); + prompt.showToast({ + message: "AuthDevice authenticate success" + }); + }); + } else { + prompt.showToast({ + message: "AuthDevice no device discovered" + }); + } + console.info('[dmsDemo] AuthDevice end'); +} + +function UnregisterDeviceListCallback() { + console.info('[dmsDemo] UnregisterDeviceListCallback begin'); + remoteDeviceModel.unregisterDeviceListCallback(); + console.info('[dmsDemo] UnregisterDeviceListCallback end'); +} + +function onStartLocalAbility() { + console.info('[dmsDemo] onStartLocalAbility begin'); + console.info('[dmsDemo] onStartLocalAbility deviceId is ' + localDeviceId); + var wantValue = { + deviceId: localDeviceId, + bundleName: 'ohos.dms.etsDemo', + abilityName: 'ohos.dms.etsDemo.LocalAbility', + }; + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('[dmsDemo] featureAbility.startAbility finished, ' + JSON.stringify(data)); + }); + console.info('[dmsDemo] onStartLocalAbility end'); +} + +function onStartRemoteAbility(index) { + console.info('[dmsDemo] onStartRemoteAbility begin'); + let numDevices = remoteDeviceModel.deviceList.length; + if (numDevices === 0) { + prompt.showToast({ + message: "onStartRemoteAbility no device found" + }); + return; + } + let deviceIdForStart = remoteDeviceModel.deviceList[index - 1].deviceId; + console.info('[dmsDemo] onStartRemoteAbility deviceId is ' + deviceIdForStart); + var params; + var wantValue = { + bundleName: 'ohos.dms.etsDemo', + abilityName: 'ohos.dms.etsDemo.RemoteAbility', + deviceId: deviceIdForStart, + parameters: params + }; + console.info('[dmsDemo] onStartRemoteAbility want=' + JSON.stringify(wantValue)); + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('[dmsDemo] onStartRemoteAbility finished, ' + JSON.stringify(data)); + }); + console.info('[dmsDemo] onStartRemoteAbility end'); +} + +async function onContinueLocalAbility() { + console.info('[dmsDemo] onContinueLocalAbility begin'); + console.info('[dmsDemo] onContinueLocalAbility deviceId is ' + localDeviceId); + let continueAbilityOptions = { + reversible: false, + deviceId: localDeviceId, + }; + function ContinueAbilityCallback(err, data) { + console.info("[dmsDemo] onContinueLocalAbility ContinueAbilityCallback, result err = " + JSON.stringify(err)); + console.info("[dmsDemo] onContinueLocalAbility ContinueAbilityCallback, result data= " + JSON.stringify(data)); + }; + await featureAbility.continueAbility(continueAbilityOptions, ContinueAbilityCallback); + console.info('[dmsDemo] onContinueLocalAbility end'); +} + +async function onContinueAbility(index) { + console.info('[dmsDemo] onContinueAbility begin'); + let numDevices = remoteDeviceModel.deviceList.length; + if (numDevices === 0) { + prompt.showToast({ + message: "onContinueAbility no device found" + }); + return; + } + let deviceIdForContinue = remoteDeviceModel.deviceList[index - 1].deviceId; + console.info('[dmsDemo] onContinueAbility deviceId is ' + deviceIdForContinue); + let continueAbilityOptions = { + reversible: false, + deviceId: deviceIdForContinue, + }; + function ContinueAbilityCallback(err, data) { + console.info("[dmsDemo] onContinueAbility ContinueAbilityCallback, result err = " + JSON.stringify(err)); + console.info("[dmsDemo] onContinueAbility ContinueAbilityCallback, result data= " + JSON.stringify(data)); + }; + await featureAbility.continueAbility(continueAbilityOptions, ContinueAbilityCallback); + console.info('[dmsDemo] onContinueAbility end'); +} + +function onConnectLocalService() { + console.info('[dmsDemo] onConnectLocalService begin'); + console.info('[dmsDemo] onConnectLocalService deviceId is ' + localDeviceId); + async function onConnectCallback(element, remote) { + console.log('[dmsDemo] onConnectLocalService onConnectDone element: ' + element); + console.log('[dmsDemo] onConnectLocalService onConnectDone remote: ' + remote); + mRemote = remote; + if (mRemote == null) { + prompt.showToast({ + message: "onConnectLocalService not connected yet" + }); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); + await mRemote.sendRequest(1, data, reply, option); + let msg = reply.readInt(); + prompt.showToast({ + message: "onConnectLocalService connect result: " + msg, + duration: 3000 + }); + } + + function onDisconnectCallback(element) { + console.log('[dmsDemo] onConnectLocalService onDisconnectDone element: ' + element); + } + + function onFailedCallback(code) { + console.log('[dmsDemo] onConnectLocalService onFailed errCode: ' + code) + prompt.showToast({ + message: "onConnectLocalService onFailed: " + code + }); + } + + connectedAbility = featureAbility.connectAbility( + { + deviceId: localDeviceId, + bundleName: "ohos.dms.js", + abilityName: "ohos.dms.js.ServiceAbility", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, + ); + console.log('[dmsDemo] onConnectLocalService connectedAbility: ' + connectedAbility) +} + +function onConnectRemoteService(index) { + console.info('[dmsDemo] onConnectRemoteService begin'); + async function onConnectCallback(element, remote) { + console.log('[dmsDemo] onConnectRemoteService onConnectDone element: ' + element); + console.log('[dmsDemo] onConnectRemoteService onConnectDone remote: ' + remote); + mRemote = remote; + if (mRemote == null) { + prompt.showToast({ + message: "onConnectRemoteService not connected yet" + }); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); + await mRemote.sendRequest(1, data, reply, option); + let msg = reply.readInt(); + prompt.showToast({ + message: "onConnectRemoteService connect result: " + msg, + duration: 3000 + }); + } + + function onDisconnectCallback(element) { + console.log('[dmsDemo] onConnectRemoteService onDisconnectDone element: ' + element); + } + + function onFailedCallback(code) { + console.log('[dmsDemo] onConnectRemoteService onFailed errCode: ' + code) + prompt.showToast({ + message: "onConnectRemoteService onFailed: " + code + }); + } + + let numDevices = remoteDeviceModel.deviceList.length; + if (numDevices === 0) { + prompt.showToast({ + message: "onConnectRemoteService no device found" + }); + return; + } + let deviceIdForConnect = remoteDeviceModel.deviceList[index - 1].deviceId; + console.info('[dmsDemo] onConnectRemoteService deviceId is ' + deviceIdForConnect); + connectedAbility = featureAbility.connectAbility( + { + deviceId: deviceIdForConnect, + bundleName: "ohos.dms.js", + abilityName: "ohos.dms.js.ServiceAbility", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, + ); + console.log('[dmsDemo] onConnectRemoteService connectedAbility: ' + connectedAbility) +} + +async function onDisconnectService() { + console.log('[dmsDemo] onDisconnectService begin'); + if (connectedAbility == null) { + prompt.showToast({ + message: "onDisconnectService not connected yet" + }); + return; + } + await featureAbility.disconnectAbility(connectedAbility); + connectedAbility = null; + prompt.showToast({ + message: "onDisconnectService disconnect done" + }); +} + +@CustomDialog +struct CustomDialogExample { + controller: CustomDialogController + cancel: () => void + confirm: () => void + + build() { + Column() { + TextInput({placeholder:'please input device index', text:''}) + .type(InputType.Number) + .enterKeyType(EnterKeyType.Send) + .onChange((value) => { + console.log('[dmsDemo] TextInput onChange:' + value); + mIndex = value; + }).onSubmit((enterKey) => { + console.log('[dmsDemo] TextInput onSubmit:' + enterKey); + }).onEditChanged((isEditing) => { + console.log('[dmsDemo] TextInput onEditChanged:' + isEditing); + }).width(250).height(50) + Flex({ justifyContent: FlexAlign.SpaceAround }) { + Button('cancel') + .onClick(() => { + this.controller.close() + this.cancel() + }).backgroundColor(0xffffff).fontColor(Color.Black) + Button('submit') + .onClick(() => { + this.controller.close() + this.confirm() + }).backgroundColor(0xffffff).fontColor(Color.Red) + }.margin({ bottom: 10 }) + } + } +} + +@Entry +@Component +struct Index { + dialogController: CustomDialogController = new CustomDialogController({ + builder: CustomDialogExample({ cancel: this.onCancel, confirm: this.onAccept }), + cancel: this.existApp, + autoCancel: true + }) + + onCancel() { + console.info('[dmsDemo] Callback when onCancel button is clicked'); + } + onAccept() { + console.info('[dmsDemo] Callback when onAccept button is clicked, mOperation is ' + mOperation); + if (mIndex <= 0) { + prompt.showToast({ + message: "Please input correct device index." + }); + return; + } + if (mOperation === Operation.AuthDeviceOperation) { + console.info('[dmsDemo] call AuthDevice, device index: ' + mIndex); + if (mIndex > mDiscoveredSize) { + prompt.showToast({ + message: "Please input correct device index." + }); + return; + } + AuthDevice(mIndex); + } else if (mOperation === Operation.StartRemoteAbilityOperation) { + console.info('[dmsDemo] call onStartRemoteAbility, device index: ' + mIndex); + if (mIndex > mDeviceSize) { + prompt.showToast({ + message: "Please input correct device index." + }); + return; + } + onStartRemoteAbility(mIndex); + } else if (mOperation === Operation.ContinueAbilityOperation) { + console.info('[dmsDemo] call onContinueAbility, device index: ' + mIndex); + if (mIndex > mDeviceSize) { + prompt.showToast({ + message: "Please input correct device index." + }); + return; + } + onContinueAbility(mIndex); + } else if (mOperation === Operation.ConnectRemoteServiceOperation){ + console.info('[dmsDemo] call onConnectRemoteService, device index: ' + mIndex); + if (mIndex > mDeviceSize) { + prompt.showToast({ + message: "Please input correct device index." + }); + return; + } + onConnectRemoteService(mIndex); + } + } + existApp() { + console.info('[dmsDemo] Click the callback in the blank area'); + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Button() { + Text('RegisterDeviceListCallback') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + RegisterDeviceListCallback(); + }) + + Button() { + Text('AuthDevice') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + mOperation = Operation.AuthDeviceOperation; + this.dialogController.open(); + }) + + Button() { + Text('UnregisterDeviceListCallback') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + UnregisterDeviceListCallback(); + }) + + Button() { + Text('StartLocalAbility') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + onStartLocalAbility(); + }) + + Button() { + Text('StartRemoteAbility') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + mOperation = Operation.StartRemoteAbilityOperation; + console.info('[dmsDemo] StartRemoteAbility onClick, mOperation is ' + mOperation); + this.dialogController.open(); + }) + + Button() { + Text('ContinueLocalAbility') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + onContinueLocalAbility(); + }) + + Button() { + Text('ContinueAbility') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + mOperation = Operation.ContinueAbilityOperation; + this.dialogController.open(); + }) + + Button() { + Text('ConnectLocalService') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + onConnectLocalService(); + }) + + Button() { + Text('ConnectRemoteService') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + mOperation = Operation.ConnectRemoteServiceOperation; + this.dialogController.open(); + }) + + Button() { + Text('DisConnectService') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .onClick(() => { + onDisconnectService(); + }) + + } + .width('100%') + .height('100%') + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/ServiceAbility/service.ts b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/ServiceAbility/service.ts new file mode 100644 index 00000000..ea78023e --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/ServiceAbility/service.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import rpc from "@ohos.rpc"; + +class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + console.log("ServiceAbility onRemoteRequest called"); + if (code === 1) { + let op1 = data.readInt(); + let op2 = data.readInt(); + console.log("op1 = " + op1 + ", op2 = " + op2); + reply.writeInt(op1 + op2); + } else { + console.log("ServiceAbility unknown request code"); + } + return true; + } +} + +export default { + onStart() { + console.info('ServiceAbility onStart'); + }, + onStop() { + console.info('ServiceAbility onStop'); + }, + onConnect(want) { + console.log("ServiceAbility onConnect"); + try { + let value = JSON.stringify(want); + console.log("ServiceAbility want:" + value); + } catch (error) { + console.log("ServiceAbility error:" + error); + } + return new FirstServiceAbilityStub("first ts service stub");; + }, + onDisconnect(want) { + console.log("ServiceAbility onDisconnect"); + let value = JSON.stringify(want); + console.log("ServiceAbility want:" + value); + }, + onCommand(want, startId) { + console.info('ServiceAbility onCommand'); + let value = JSON.stringify(want); + console.log("ServiceAbility want:" + value); + console.log("ServiceAbility startId:" + startId); + } +}; \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/model/RemoteDeviceModel.ets b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/model/RemoteDeviceModel.ets new file mode 100644 index 00000000..73b6d7c8 --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/ets/model/RemoteDeviceModel.ets @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import deviceManager from '@ohos.distributedHardware.deviceManager'; + +var SUBSCRIBE_ID = 100; + +export default class RemoteDeviceModel { + deviceList = []; + discoverList = []; + callback; + authCallback = null; + #deviceManager; + + constructor() { + } + + registerDeviceListCallback(callback) { + if (typeof (this.#deviceManager) === 'undefined') { + console.log('[dmsDemo] deviceManager.createDeviceManager begin'); + let self = this; + deviceManager.createDeviceManager('com.ohos.distributedmusicplayer', (error, value) => { + if (error) { + console.error('createDeviceManager failed.'); + return; + } + self.#deviceManager = value; + self.registerDeviceListCallback_(callback); + console.log('[dmsDemo] createDeviceManager callback returned, error=' + error + ' value=' + value); + }); + console.log('[dmsDemo] deviceManager.createDeviceManager end'); + } else { + this.registerDeviceListCallback_(callback); + } + } + + registerDeviceListCallback_(callback) { + console.info('[dmsDemo] registerDeviceListCallback'); + this.callback = callback; + if (this.#deviceManager == undefined) { + console.error('[dmsDemo] deviceManager has not initialized'); + this.callback(); + return; + } + + console.info('[dmsDemo] getTrustedDeviceListSync begin'); + var list = this.#deviceManager.getTrustedDeviceListSync(); + console.info('[dmsDemo] getTrustedDeviceListSync end, deviceList=' + JSON.stringify(list)); + if (typeof (list) != 'undefined' && typeof (list.length) != 'undefined') { + this.deviceList = list; + } + this.callback(); + console.info('[dmsDemo] callback finished'); + + let self = this; + this.#deviceManager.on('deviceStateChange', (data) => { + console.info('[dmsDemo] deviceStateChange data=' + JSON.stringify(data)); + switch (data.action) { + case 0: + self.deviceList[self.deviceList.length] = data.device; + console.info('[dmsDemo] online, updated device list=' + JSON.stringify(self.deviceList)); + self.callback(); + if (self.authCallback != null) { + self.authCallback(); + self.authCallback = null; + } + break; + case 2: + if (self.deviceList.length > 0) { + for (var i = 0; i < self.deviceList.length; i++) { + if (self.deviceList[i].deviceId === data.device.deviceId) { + self.deviceList[i] = data.device; + break; + } + } + } + console.info('[dmsDemo] change, updated device list=' + JSON.stringify(self.deviceList)); + self.callback(); + break; + case 1: + if (self.deviceList.length > 0) { + var list = []; + for (var i = 0; i < self.deviceList.length; i++) { + if (self.deviceList[i].deviceId != data.device.deviceId) { + list[i] = data.device; + } + } + self.deviceList = list; + } + console.info('[dmsDemo] offline, updated device list=' + JSON.stringify(data.device)); + self.callback(); + break; + default: + break; + } + }); + this.#deviceManager.on('deviceFound', (data) => { + console.info('[dmsDemo] deviceFound data=' + JSON.stringify(data)); + console.info('[dmsDemo] deviceFound self.deviceList=' + self.deviceList); + console.info('[dmsDemo] deviceFound self.deviceList.length=' + self.deviceList.length); + for (var i = 0; i < self.discoverList.length; i++) { + if (self.discoverList[i].deviceId === data.device.deviceId) { + console.info('[dmsDemo] device founded, ignored'); + return; + } + } + self.discoverList[self.discoverList.length] = data.device; + self.callback(); + }); + this.#deviceManager.on('discoverFail', (data) => { + console.info('[dmsDemo] discoverFail data=' + JSON.stringify(data)); + }); + this.#deviceManager.on('serviceDie', () => { + console.error('[dmsDemo] serviceDie'); + }); + + SUBSCRIBE_ID = Math.floor(65536 * Math.random()); + var info = { + subscribeId: SUBSCRIBE_ID, + mode: 0xAA, + medium: 2, + freq: 2, + isSameAccount: false, + isWakeRemote: true, + capability: 0 + }; + console.info('[dmsDemo] startDeviceDiscovery ' + SUBSCRIBE_ID); + this.#deviceManager.startDeviceDiscovery(info); + } + + authDevice(deviceId, callback) { + console.info('[dmsDemo] authDevice ' + deviceId); + for (var i = 0; i < this.discoverList.length; i++) { + if (this.discoverList[i].deviceId === deviceId) { + console.info('[dmsDemo] device founded, ignored'); + let extraInfo = { + "targetPkgName": 'com.ohos.distributedmusicplayer', + "appName": 'Music', + "appDescription": 'Music player application', + "business": '0' + }; + let authParam = { + "authType": 1, + "appIcon": '', + "appThumbnail": '', + "extraInfo": extraInfo + }; + console.info('[dmsDemo] authenticateDevice ' + JSON.stringify(this.discoverList[i])); + let self = this; + this.#deviceManager.authenticateDevice(this.discoverList[i], authParam, (err, data) => { + if (err) { + console.info('[dmsDemo] authenticateDevice failed, err=' + JSON.stringify(err)); + self.authCallback = null; + } else { + console.info('[dmsDemo] authenticateDevice succeed, data=' + JSON.stringify(data)); + self.authCallback = callback; + } + }); + } + } + } + + unregisterDeviceListCallback() { + console.info('[dmsDemo] stopDeviceDiscovery ' + SUBSCRIBE_ID); + this.#deviceManager.stopDeviceDiscovery(SUBSCRIBE_ID); + this.#deviceManager.off('deviceStateChange'); + this.#deviceManager.off('deviceFound'); + this.#deviceManager.off('discoverFail'); + this.#deviceManager.off('serviceDie'); + this.deviceList = []; + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json new file mode 100644 index 00000000..19a445ba --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json @@ -0,0 +1,20 @@ +{ + "string": [ + { + "name": "entry_MainAbility", + "value": "DmsDemo" + }, + { + "name": "description_remoteability", + "value": "ETS_Empty Ability" + }, + { + "name": "description_localability", + "value": "ETS_Empty Ability" + }, + { + "name": "description_serviceability", + "value": "hap sample empty service" + } + ] +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/resources/base/media/icon.png b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/entry/src/main/resources/base/media/icon.png new file mode 100644 index 00000000..e69de29b diff --git a/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/settings.gradle b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/settings.gradle new file mode 100644 index 00000000..4773db73 --- /dev/null +++ b/services/dtbschedmgr/test/etsDmsDemo/dmsDemo/settings.gradle @@ -0,0 +1 @@ +include ':entry' diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/build.gradle b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/build.gradle new file mode 100644 index 00000000..c2c8bbae --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/build.gradle @@ -0,0 +1,34 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +apply plugin: 'com.huawei.ohos.app' + +//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 +ohos { + compileSdkVersion 7 + supportSystem "standard" +} + +buildscript { + repositories { + maven { + url 'https://repo.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + } + dependencies { + classpath 'com.huawei.ohos:hap:3.0.3.4' + classpath 'com.huawei.ohos:decctest:1.2.6.0' + } +} + +allprojects { + repositories { + maven { + url 'https://repo.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + } +} diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/build.gradle b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/build.gradle new file mode 100644 index 00000000..fa90d267 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/build.gradle @@ -0,0 +1,22 @@ +apply plugin: 'com.huawei.ohos.hap' +//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 +ohos { + compileSdkVersion 7 + defaultConfig { + compatibleSdkVersion 7 + } + buildTypes { + release { + proguardOpt { + proguardEnabled false + rulesFiles 'proguard-rules.pro' + } + } + } + arkEnabled false +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) + testImplementation 'junit:junit:4.13.1' +} diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/config.json b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/config.json new file mode 100644 index 00000000..39c95561 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/config.json @@ -0,0 +1,94 @@ +{ + "app": { + "bundleName": "ohos.dms.jsDemo", + "vendor": "dms", + "version": { + "code": 1000000, + "name": "1.0.0" + } + }, + "deviceConfig": {}, + "module": { + "package": "ohos.dms.jsDemo", + "name": ".MyApplication", + "mainAbility": ".RemoteAbility", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry", + "installationFree": false + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "RemoteAbility", + "name": ".RemoteAbility", + "srcLanguage": "js", + "icon": "$media:icon", + "description": "$string:description_remoteability", + "formsEnabled": false, + "label": "$string:entry_MainAbility", + "type": "page", + "launchType": "standard" + }, + { + "orientation": "unspecified", + "visible": true, + "srcPath": "LocalAbility", + "name": ".LocalAbility", + "srcLanguage": "js", + "icon": "$media:icon", + "description": "$string:description_localability", + "formsEnabled": false, + "label": "$string:entry_MainAbility", + "type": "page", + "launchType": "standard" + }, + { + "visible": true, + "srcPath": "ServiceAbility", + "name": ".ServiceAbility", + "icon": "$media:icon", + "srcLanguage": "js", + "description": "$string:description_serviceability", + "type": "service" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": ".RemoteAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + }, + { + "pages": [ + "pages/index/index" + ], + "name": ".LocalAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/app.js b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/app.js new file mode 100644 index 00000000..58d12b7b --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/app.js @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + onCreate() { + console.info("Application onCreate"); + }, + onDestroy() { + console.info("Application onDestroy"); + } +}; diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/en-US.json b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/en-US.json new file mode 100644 index 00000000..08e34eac --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/en-US.json @@ -0,0 +1,11 @@ +{ + "strings": { + "hello": "Hello", + "world": "World", + "page": "Second Page", + "next": "Next Page", + "back": "Back" + }, + "Files": { + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/zh-CN.json b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/zh-CN.json new file mode 100644 index 00000000..3dd53b3a --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/i18n/zh-CN.json @@ -0,0 +1,11 @@ +{ + "strings": { + "hello": "您好", + "world": "世界", + "page": "第二页", + "next": "下一页", + "back": "返回" + }, + "Files": { + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.css b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.css new file mode 100644 index 00000000..8b5cce53 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.css @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +.container { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 100%; + height: 100%; +} + +.title { + font-size: 60px; + text-align: center; + width: 100%; + height: 40%; + margin: 10px; +} + +.btn { + width: 50%; + height: 100px; + font-size: 40px; +} diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.hml b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.hml new file mode 100644 index 00000000..38ee4c43 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.hml @@ -0,0 +1,20 @@ + + +
+ + {{ $t('strings.hello') }} {{ title }} + +
diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.js b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.js new file mode 100644 index 00000000..d631e1bb --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/LocalAbility/pages/index/index.js @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + data: { + title: "" + }, + onInit() { + this.title = this.$t('strings.world'); + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/app.js b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/app.js new file mode 100644 index 00000000..4660b2cc --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/app.js @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export default { + onCreate() { + console.info('Application onCreate'); + }, + onDestroy() { + console.info('Application onDestroy'); + }, + onStartContinuation() { + console.info('onStartContinuation'); + return true; + }, + onRestoreData(data) { + console.info('onRestoreData' + data); + return true; + }, + onSaveData(data) { + console.info('onSaveData'); + return true; + }, + onCompleteContinuation(result) { + console.info('onCompleteContinuation:' + result); + } +}; diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/en-US.json b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/en-US.json new file mode 100644 index 00000000..08e34eac --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/en-US.json @@ -0,0 +1,11 @@ +{ + "strings": { + "hello": "Hello", + "world": "World", + "page": "Second Page", + "next": "Next Page", + "back": "Back" + }, + "Files": { + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/zh-CN.json b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/zh-CN.json new file mode 100644 index 00000000..3dd53b3a --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/i18n/zh-CN.json @@ -0,0 +1,11 @@ +{ + "strings": { + "hello": "您好", + "world": "世界", + "page": "第二页", + "next": "下一页", + "back": "返回" + }, + "Files": { + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.css b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.css new file mode 100644 index 00000000..d8d68ea7 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.css @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-image: url(common/media/bg_blurry.png); + background-size: cover; + background-position: center center; + padding-start: 6%; + padding-end: 6%; +} + +.title { + width: 100%; + margin-top: 10%; + color: #FFF; + text-align: center; +} + +.album_section { + flex: 1 1px; + flex-direction: row; + align-items: center; +} + +.album_image { + align-items: center; + object-fit: contain; +} + +.progress_section { + margin-bottom: 4%; + flex-direction: column; +} + +.timer { + width: 100%; + flex-direction: row; + justify-content: space-between; +} + +.progress_time { + color: #FFF; + text-align: center; +} + +.total_time { + color: #FFF; + text-align: center; +} + +.music_slider { + width: 100%; + color: #64CCE7FF; + padding-left: 0; + padding-right: 0; +} + +.control_section { + width: 100%; + height: 10%; + justify-content: space-between; + flex-direction: row; + margin-bottom: 4%; +} + +.control_button { + width: 20%; + aspect-ratio: 1; +} + +.txt { + color: #000; + font-weight: bold; + font-size: 39px; +} + +.dialog-main { + width: 500px; +} + +.dialog-div { + flex-direction: column; + align-items: center; +} + +.dialog_title_text { + width: 434px; + height: 80px; + font-size: 32px; + font-weight: 600; +} + +.inner-btn { + width: 400px; + height: 120px; + justify-content: space-around; + align-items: center; +} + +.dialog_cancel_button { + width: 100%; + font-size: 32px; +} + +.dialog_device_list { + width: 434px; + max-height: 150px; +} + +.device_list_item { + width: 434px; + height: 80px; + flex-direction: row; + align-items: center; +} + +.device_item_radio { +} + +.device_item_title { + width: 80%; + height: 80px; + text-align: start; +} + +.btn { + width: 60%; + height: 8%; + margin-top: 40px; +} + +@media screen and (device-type: tablet) and (orientation: landscape) { + +} + +@media screen and (device-type: wearable) { + +} + +@media screen and (device-type: tv) { + +} + +@media screen and (device-type: phone) and (orientation: landscape) { + +} diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.hml b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.hml new file mode 100644 index 00000000..10e7579b --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.hml @@ -0,0 +1,78 @@ + + +
+ + + + + + + + + +
+ 选择设备 + + + + + + +
+ +
+
+
+ + +
+ 选择设备 + + + + + + +
+ +
+
+
+ + +
+ 选择设备 + + + + + + +
+ +
+
+
+
diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.js b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.js new file mode 100644 index 00000000..f5beeec2 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/RemoteAbility/pages/index/index.js @@ -0,0 +1,438 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import featureAbility from '@ohos.ability.featureAbility'; +import RemoteDeviceModel from '../../../model/RemoteDeviceModel.js'; +import rpc from "@ohos.rpc"; +import prompt from '@system.prompt'; + +var mRemote; +var DEVICE_LIST_LOCALHOST; +var connectedAbility; +var localDeviceId = ""; + +export default { + data: { + title: '', + remoteDeviceModel: new RemoteDeviceModel, + deviceList: [], + btnPlaySrc: '/common/media/ic_play.svg', + albumSrc: '/common/media/album.png', + isDialogShowing: false, + isSwitching: false, + hasInitialized: false, + }, + onInit() { + DEVICE_LIST_LOCALHOST = { + name: this.$t('localhost'), + id: 'localhost', + }; + this.deviceList = [DEVICE_LIST_LOCALHOST]; + let self = this; + this.remoteDeviceModel.registerDeviceListCallback(() => { + console.info('registerDeviceListCallback, callback entered'); + var list = []; + list[0] = DEVICE_LIST_LOCALHOST; + var deviceList; + if (self.remoteDeviceModel.discoverList.length > 0) { + deviceList = self.remoteDeviceModel.discoverList; + } else { + deviceList = self.remoteDeviceModel.deviceList; + } + console.info('on remote device updated, count=' + deviceList.length); + for (var i = 0; i < deviceList.length; i++) { + console.info('device ' + i + '/' + deviceList.length + ' deviceId=' + + deviceList[i].deviceId + ' deviceName=' + deviceList[i].deviceName + ' deviceType=' + + deviceList[i].deviceType); + list[i + 1] = { + name: deviceList[i].deviceName, + id: deviceList[i].deviceId, + }; + } + self.deviceList = list; + }); + console.info('onInit end'); + }, + onDestroy() { + console.info('onDestroy begin'); + this.remoteDeviceModel.unregisterDeviceListCallback(); + console.info('onDestroy end'); + }, + + onStartLocalAbilityClick() { + console.info('[dmsDemo] onStartLocalAbilityClick begin'); + console.info('[dmsDemo] onStartLocalAbilityClick deviceId is ' + localDeviceId); + var wantValue = { + bundleName: 'ohos.dms.jsDemo', + abilityName: 'ohos.dms.jsDemo.LocalAbility', + deviceId: localDeviceId, + }; + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('[dmsDemo] featureAbility.startAbility finished, ' + JSON.stringify(data)); + }); + console.info('[dmsDemo] onStartLocalAbilityClick end'); + }, + + onStartAbilityClick() { + console.info('[dmsDemo] onStartAbilityClick begin'); + this.$element('dialogForStartAbility').show(); + this.isDialogShowing = true; + console.info('[dmsDemo] onStartAbilityClick end'); + }, + + onRadioChangeForStart(inputValue, e) { + console.info('[dmsDemo] onRadioChangeForStart ' + inputValue + ', ' + e.value); + if (inputValue === e.value) { + if (e.value === 'localhost') { + this.$element('dialogForStartAbility').close(); + return; + } + if (this.remoteDeviceModel.discoverList.length > 0) { + console.info('[dmsDemo] start to device'); + var name = null; + for (var i = 0; i < this.remoteDeviceModel.discoverList.length; i++) { + if (this.remoteDeviceModel.discoverList[i].deviceId === e.value) { + name = this.remoteDeviceModel.discoverList[i].deviceName; + break; + } + } + if (name == null) { + console.error('[dmsDemo] onRadioChangeForStart failed, can not get name from discoverList'); + return; + } + console.info('[dmsDemo] onRadioChangeForStart name=' + name); + + let self = this; + this.remoteDeviceModel.authDevice(e.value, () => { + console.info('[dmsDemo] onRadioChangeForStart auth and online finished'); + for (i = 0; i < self.remoteDeviceModel.deviceList.length; i++) { + if (self.remoteDeviceModel.deviceList[i].deviceName === name) { + this.startRemoteAbility(self.remoteDeviceModel.deviceList[i].deviceId, self.remoteDeviceModel.deviceList[i].deviceName); + } + } + }); + } else { + console.info('[dmsDemo] onRadioChangeForStart start to authed device'); + for (i = 0; i < this.remoteDeviceModel.deviceList.length; i++) { + if (this.remoteDeviceModel.deviceList[i].deviceId === e.value) { + this.startRemoteAbility(this.remoteDeviceModel.deviceList[i].deviceId, this.remoteDeviceModel.deviceList[i].deviceName); + } + } + } + } + }, + + startRemoteAbility(deviceId, deviceName) { + this.$element('dialogForStartAbility').close(); + var params; + console.info('[dmsDemo] featureAbility.startAbility deviceId=' + deviceId + + ' deviceName=' + deviceName); + var wantValue = { + bundleName: 'ohos.dms.jsDemo', + abilityName: 'ohos.dms.jsDemo.RemoteAbility', + deviceId: deviceId, + parameters: params + }; + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('[dmsDemo] featureAbility.startAbility finished, ' + JSON.stringify(data)); + }); + console.info('[dmsDemo] featureAbility.startAbility want=' + JSON.stringify(wantValue)); + console.info('[dmsDemo] featureAbility.startAbility end'); + }, + + async onContinueLocalAbilityClicked(){ + console.info('[dmsDemo] ContinueLocalAbility begin'); + console.info('[dmsDemo] ContinueLocalAbility deviceId is ' + localDeviceId); + let continueAbilityOptions = { + reversible: false, + deviceId: localDeviceId, + } + function ContinueAbilityCallback(err, data) { + console.info("[dmsDemo] ContinueAbilityCallback, result err = " + JSON.stringify(err)); + console.info("[dmsDemo] ContinueAbilityCallback, result data= " + JSON.stringify(data)); + } + await featureAbility.continueAbility(continueAbilityOptions, ContinueAbilityCallback); + done(); + console.info('[dmsDemo] ContinueLocalAbility end'); + }, + + onContinueAbilityClicked(){ + console.info('[dmsDemo] ContinueAbility begin'); + this.$element('dialogForContinueAbility').show(); + this.isDialogShowing = true; + console.info('[dmsDemo] ContinueAbility end'); + }, + + onRadioChangeForContinue(inputValue, e) { + console.info('[dmsDemo] onRadioChangeForContinue ' + inputValue + ', ' + e.value); + if (inputValue === e.value) { + if (e.value === 'localhost') { + this.$element('dialogForContinueAbility').close(); + return; + } + if (this.remoteDeviceModel.discoverList.length > 0) { + console.info('[dmsDemo] onRadioChangeForContinue to device'); + var name = null; + for (var i = 0; i < this.remoteDeviceModel.discoverList.length; i++) { + if (this.remoteDeviceModel.discoverList[i].deviceId === e.value) { + name = this.remoteDeviceModel.discoverList[i].deviceName; + break; + } + } + if (name == null) { + console.error('[dmsDemo] onRadioChangeForContinue failed, can not get name from discoverList'); + return; + } + console.info('[dmsDemo] onRadioChangeForContinue name=' + name); + + let self = this; + this.remoteDeviceModel.authDevice(e.value, () => { + console.info('[dmsDemo] onRadioChangeForContinue auth and online finished'); + for (i = 0; i < self.remoteDeviceModel.deviceList.length; i++) { + if (self.remoteDeviceModel.deviceList[i].deviceName === name) { + this.StartContinueAbility(self.remoteDeviceModel.deviceList[i].deviceId, self.remoteDeviceModel.deviceList[i].deviceName); + } + } + }); + } else { + console.info('[dmsDemo] onRadioChangeForContinue continue to authed device'); + for (i = 0; i < this.remoteDeviceModel.deviceList.length; i++) { + if (this.remoteDeviceModel.deviceList[i].deviceId === e.value) { + this.StartContinueAbility(this.remoteDeviceModel.deviceList[i].deviceId, this.remoteDeviceModel.deviceList[i].deviceName); + } + } + } + } + }, + + async StartContinueAbility(deviceId, deviceName) { + this.$element('dialogForContinueAbility').close(); + console.info('[dmsDemo] featureAbility.StartContinueAbility deviceId=' + deviceId + + ' deviceName=' + deviceName); + let continueAbilityOptions = { + reversible: false, + deviceId: deviceId, + } + function ContinueAbilityCallback(err, data) { + console.info("[dmsDemo] ContinueAbilityCallback, result err = " + JSON.stringify(err)); + console.info("[dmsDemo] ContinueAbilityCallback, result data= " + JSON.stringify(data)); + } + await featureAbility.continueAbility(continueAbilityOptions, ContinueAbilityCallback); + done(); + console.info('[dmsDemo] featureAbility.StartContinueAbility end'); + }, + + async ConnectLocalService(){ + console.log('[dmsDemo] ConnectLocalService begin'); + async function onConnectCallback(element, remote){ + console.log('[dmsDemo] ConnectLocalService onConnectDone element: ' + element); + console.log('[dmsDemo] ConnectLocalService onConnectDone remote: ' + remote); + mRemote = remote; + if (mRemote == null) { + prompt.showToast({ + message: "not connected yet" + }); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); + await mRemote.sendRequest(1, data, reply, option); + let msg = reply.readInt(); + prompt.showToast({ + message: "connect result: " + msg, + duration: 3000 + }); + } + function onDisconnectCallback(element){ + console.log('[dmsDemo] ConnectLocalService onDisconnectDone element: ' + element); + } + function onFailedCallback(code){ + console.log('[dmsDemo] ConnectLocalService onFailed errCode: ' + code) + prompt.showToast({ + message: "ConnectLocalService onFailed: " + code + }); + } + + console.info('[dmsDemo] ConnectLocalAbility deviceId is: ' + localDeviceId) + connectedAbility = featureAbility.connectAbility( + { + deviceId: localDeviceId, + bundleName: "ohos.dms.jsDemo", + abilityName: "ohos.dms.jsDemo.ServiceAbility", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, + ); + console.info('[dmsDemo] ConnectLocalService is: ' + connectedAbility) + }, + + onConnectRemoteServiceClicked() { + console.info('[dmsDemo] ConnectRemoteService begin'); + this.$element('dialogForConnectService').show(); + this.isDialogShowing = true; + console.info('[dmsDemo] ConnectRemoteService end'); + }, + + onRadioChangeForConnect(inputValue, e) { + console.info('[dmsDemo] onRadioChangeForConnect ' + inputValue + ', ' + e.value); + if (inputValue === e.value) { + if (e.value === 'localhost') { + this.$element('dialogForConnectService').close(); + return; + } + if (this.remoteDeviceModel.discoverList.length > 0) { + console.info('[dmsDemo] onRadioChangeForConnect to device'); + var name = null; + for (var i = 0; i < this.remoteDeviceModel.discoverList.length; i++) { + if (this.remoteDeviceModel.discoverList[i].deviceId === e.value) { + name = this.remoteDeviceModel.discoverList[i].deviceName; + break; + } + } + if (name == null) { + console.error('[dmsDemo] onRadioChangeForConnect failed, can not get name from discoverList'); + return; + } + console.info('[dmsDemo] onRadioChangeForConnect name=' + name); + + let self = this; + this.remoteDeviceModel.authDevice(e.value, () => { + console.info('[dmsDemo] onRadioChangeForConnect auth and online finished'); + for (i = 0; i < self.remoteDeviceModel.deviceList.length; i++) { + if (self.remoteDeviceModel.deviceList[i].deviceName === name) { + this.ConnectRemoteService(self.remoteDeviceModel.deviceList[i].deviceId, self.remoteDeviceModel.deviceList[i].deviceName); + } + } + }); + } else { + console.info('[dmsDemo] onRadioChangeForConnect continue to authed device'); + for (i = 0; i < this.remoteDeviceModel.deviceList.length; i++) { + if (this.remoteDeviceModel.deviceList[i].deviceId === e.value) { + this.ConnectRemoteService(this.remoteDeviceModel.deviceList[i].deviceId, this.remoteDeviceModel.deviceList[i].deviceName); + } + } + } + } + }, + + async ConnectRemoteService(deviceId, deviceName){ + this.$element('dialogForConnectService').close(); + console.info('[dmsDemo] featureAbility.connectAbility deviceId=' + deviceId + + ' deviceName=' + deviceName); + async function onConnectCallback(element, remote){ + console.log('[dmsDemo] ConnectRemoteService onConnectDone element: ' + element); + console.log('[dmsDemo] ConnectRemoteService onConnectDone remote: ' + remote); + mRemote = remote; + if (mRemote == null) { + prompt.showToast({ + message: "not connected yet" + }); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); + await mRemote.sendRequest(1, data, reply, option); + let msg = reply.readInt(); + prompt.showToast({ + message: "connect result: " + msg, + duration: 3000 + }); + } + function onDisconnectCallback(element){ + console.log('[dmsDemo] ConnectRemoteService onDisconnectDone element: ' + element); + } + function onFailedCallback(code){ + console.log('[dmsDemo] ConnectRemoteService onFailed errCode: ' + code) + prompt.showToast({ + message: "ConnectRemoteService onFailed: " + code + }); + } + + connectedAbility = featureAbility.connectAbility( + { + deviceId: deviceId, + bundleName: "ohos.dms.jsDemo", + abilityName: "ohos.dms.jsDemo.ServiceAbility", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, + ); + console.info('[dmsDemo] ConnectedAbility is: ' + connectedAbility) + }, + + async DisConnectService() { + console.log('[dmsDemo] DisConnectService begin'); + if (connectedAbility == null) { + prompt.showToast({ + message: "not connected yet" + }); + return; + } + await featureAbility.disconnectAbility(connectedAbility); + connectedAbility = null; + prompt.showToast({ + message: "disconnect done" + }); + }, + + cancelDialog(e) { + this.remoteDeviceModel.unregisterDeviceListCallback(); + this.isDialogShowing = false; + this.$element('dialogForStartAbility').close(); + this.$element('dialogForContinueAbility').close(); + this.$element('dialogForConnectService').close(); + }, + onDismissDialogForStartClicked(e) { + this.dismissDialogForStart(); + }, + dismissDialogForStart() { + this.$element('dialogForStartAbility').close(); + this.remoteDeviceModel.unregisterDeviceListCallback(); + this.isDialogShowing = false; + }, + onDismissDialogForContinueClicked(e) { + this.dismissDialogForContinue(); + }, + dismissDialogForContinue() { + this.$element('dialogForContinueAbility').close(); + this.remoteDeviceModel.unregisterDeviceListCallback(); + this.isDialogShowing = false; + }, + onDismissDialogForConnectClicked(e) { + this.dismissDialogForConnect(); + }, + dismissDialogForConnect() { + this.$element('dialogForConnectService').close(); + this.remoteDeviceModel.unregisterDeviceListCallback(); + this.isDialogShowing = false; + }, + +}; diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/ServiceAbility/service.js b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/ServiceAbility/service.js new file mode 100644 index 00000000..0f8053e0 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/ServiceAbility/service.js @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import rpc from "@ohos.rpc"; + +class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + console.log("FirstServiceAbilityStub onRemoteRequest called"); + if (code === 1) { + let op1 = data.readInt(); + let op2 = data.readInt(); + console.log("op1 = " + op1 + ", op2 = " + op2); + reply.writeInt(op1 + op2); + } else { + console.log("FirstServiceAbilityStub unknown request code"); + } + return true; + } +} + +export default { + onStop() { + console.log('FirstServiceAbilityStub onStop'); + }, + onStart() { + console.log("FirstServiceAbilityStub onStart"); + }, + onConnect(want) { + console.log("FirstServiceAbilityStub onConnect"); + try { + let value = JSON.stringify(want); + console.log("FirstServiceAbilityStub want:" + value); + } catch (error) { + console.log("FirstServiceAbilityStub error:" + error); + } + return new FirstServiceAbilityStub("first js service stub"); + }, + onDisconnect(want) { + console.log("FirstServiceAbilityStub onDisconnect"); + let value = JSON.stringify(want); + console.log("FirstServiceAbilityStub want:" + value); + }, + onCommand(want, startId) { + console.log("FirstServiceAbilityStub onCommand"); + let value = JSON.stringify(want); + console.log("FirstServiceAbilityStub want:" + value); + console.log("FirstServiceAbilityStub startId:" + startId); + } +}; diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/model/RemoteDeviceModel.js b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/model/RemoteDeviceModel.js new file mode 100644 index 00000000..73b6d7c8 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/js/model/RemoteDeviceModel.js @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import deviceManager from '@ohos.distributedHardware.deviceManager'; + +var SUBSCRIBE_ID = 100; + +export default class RemoteDeviceModel { + deviceList = []; + discoverList = []; + callback; + authCallback = null; + #deviceManager; + + constructor() { + } + + registerDeviceListCallback(callback) { + if (typeof (this.#deviceManager) === 'undefined') { + console.log('[dmsDemo] deviceManager.createDeviceManager begin'); + let self = this; + deviceManager.createDeviceManager('com.ohos.distributedmusicplayer', (error, value) => { + if (error) { + console.error('createDeviceManager failed.'); + return; + } + self.#deviceManager = value; + self.registerDeviceListCallback_(callback); + console.log('[dmsDemo] createDeviceManager callback returned, error=' + error + ' value=' + value); + }); + console.log('[dmsDemo] deviceManager.createDeviceManager end'); + } else { + this.registerDeviceListCallback_(callback); + } + } + + registerDeviceListCallback_(callback) { + console.info('[dmsDemo] registerDeviceListCallback'); + this.callback = callback; + if (this.#deviceManager == undefined) { + console.error('[dmsDemo] deviceManager has not initialized'); + this.callback(); + return; + } + + console.info('[dmsDemo] getTrustedDeviceListSync begin'); + var list = this.#deviceManager.getTrustedDeviceListSync(); + console.info('[dmsDemo] getTrustedDeviceListSync end, deviceList=' + JSON.stringify(list)); + if (typeof (list) != 'undefined' && typeof (list.length) != 'undefined') { + this.deviceList = list; + } + this.callback(); + console.info('[dmsDemo] callback finished'); + + let self = this; + this.#deviceManager.on('deviceStateChange', (data) => { + console.info('[dmsDemo] deviceStateChange data=' + JSON.stringify(data)); + switch (data.action) { + case 0: + self.deviceList[self.deviceList.length] = data.device; + console.info('[dmsDemo] online, updated device list=' + JSON.stringify(self.deviceList)); + self.callback(); + if (self.authCallback != null) { + self.authCallback(); + self.authCallback = null; + } + break; + case 2: + if (self.deviceList.length > 0) { + for (var i = 0; i < self.deviceList.length; i++) { + if (self.deviceList[i].deviceId === data.device.deviceId) { + self.deviceList[i] = data.device; + break; + } + } + } + console.info('[dmsDemo] change, updated device list=' + JSON.stringify(self.deviceList)); + self.callback(); + break; + case 1: + if (self.deviceList.length > 0) { + var list = []; + for (var i = 0; i < self.deviceList.length; i++) { + if (self.deviceList[i].deviceId != data.device.deviceId) { + list[i] = data.device; + } + } + self.deviceList = list; + } + console.info('[dmsDemo] offline, updated device list=' + JSON.stringify(data.device)); + self.callback(); + break; + default: + break; + } + }); + this.#deviceManager.on('deviceFound', (data) => { + console.info('[dmsDemo] deviceFound data=' + JSON.stringify(data)); + console.info('[dmsDemo] deviceFound self.deviceList=' + self.deviceList); + console.info('[dmsDemo] deviceFound self.deviceList.length=' + self.deviceList.length); + for (var i = 0; i < self.discoverList.length; i++) { + if (self.discoverList[i].deviceId === data.device.deviceId) { + console.info('[dmsDemo] device founded, ignored'); + return; + } + } + self.discoverList[self.discoverList.length] = data.device; + self.callback(); + }); + this.#deviceManager.on('discoverFail', (data) => { + console.info('[dmsDemo] discoverFail data=' + JSON.stringify(data)); + }); + this.#deviceManager.on('serviceDie', () => { + console.error('[dmsDemo] serviceDie'); + }); + + SUBSCRIBE_ID = Math.floor(65536 * Math.random()); + var info = { + subscribeId: SUBSCRIBE_ID, + mode: 0xAA, + medium: 2, + freq: 2, + isSameAccount: false, + isWakeRemote: true, + capability: 0 + }; + console.info('[dmsDemo] startDeviceDiscovery ' + SUBSCRIBE_ID); + this.#deviceManager.startDeviceDiscovery(info); + } + + authDevice(deviceId, callback) { + console.info('[dmsDemo] authDevice ' + deviceId); + for (var i = 0; i < this.discoverList.length; i++) { + if (this.discoverList[i].deviceId === deviceId) { + console.info('[dmsDemo] device founded, ignored'); + let extraInfo = { + "targetPkgName": 'com.ohos.distributedmusicplayer', + "appName": 'Music', + "appDescription": 'Music player application', + "business": '0' + }; + let authParam = { + "authType": 1, + "appIcon": '', + "appThumbnail": '', + "extraInfo": extraInfo + }; + console.info('[dmsDemo] authenticateDevice ' + JSON.stringify(this.discoverList[i])); + let self = this; + this.#deviceManager.authenticateDevice(this.discoverList[i], authParam, (err, data) => { + if (err) { + console.info('[dmsDemo] authenticateDevice failed, err=' + JSON.stringify(err)); + self.authCallback = null; + } else { + console.info('[dmsDemo] authenticateDevice succeed, data=' + JSON.stringify(data)); + self.authCallback = callback; + } + }); + } + } + } + + unregisterDeviceListCallback() { + console.info('[dmsDemo] stopDeviceDiscovery ' + SUBSCRIBE_ID); + this.#deviceManager.stopDeviceDiscovery(SUBSCRIBE_ID); + this.#deviceManager.off('deviceStateChange'); + this.#deviceManager.off('deviceFound'); + this.#deviceManager.off('discoverFail'); + this.#deviceManager.off('serviceDie'); + this.deviceList = []; + } +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json new file mode 100644 index 00000000..0296523b --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/resources/base/element/string.json @@ -0,0 +1,20 @@ +{ + "string": [ + { + "name": "entry_MainAbility", + "value": "DmsDemo" + }, + { + "name": "description_remoteability", + "value": "JS_Empty Ability" + }, + { + "name": "description_localability", + "value": "JS_Empty Ability" + }, + { + "name": "description_serviceability", + "value": "hap sample empty service" + } + ] +} \ No newline at end of file diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/resources/base/media/icon.png b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/entry/src/main/resources/base/media/icon.png new file mode 100644 index 00000000..e69de29b diff --git a/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/settings.gradle b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/settings.gradle new file mode 100644 index 00000000..4773db73 --- /dev/null +++ b/services/dtbschedmgr/test/jsDmsDemo/dmsDemo/settings.gradle @@ -0,0 +1 @@ +include ':entry' diff --git a/services/dtbschedmgr/test/unittest/distributed_sched_ability_shell_test.cpp b/services/dtbschedmgr/test/unittest/distributed_sched_ability_shell_test.cpp deleted file mode 100755 index 05f6be51..00000000 --- a/services/dtbschedmgr/test/unittest/distributed_sched_ability_shell_test.cpp +++ /dev/null @@ -1,571 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "distributed_sched_ability_shell.h" -#include "distributed_sched_service.h" -#include "dtbschedmgr_log.h" -#include "gtest/gtest.h" -#include "if_system_ability_manager.h" -#include "iservice_registry.h" -#include "mock_distributed_sched.h" -#include "ohos/aafwk/content/want.h" -#include "system_ability_definition.h" -#include "test_log.h" - -using namespace std; -using namespace testing; -using namespace testing::ext; -using namespace OHOS; -using namespace AAFwk; -using namespace AppExecFwk; - -namespace OHOS { -namespace DistributedSchedule { -namespace { -constexpr int32_t LOOP_TIMES = 100; -} - -class DistributedSchedAbilityShellTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); - sptr proxy_; -protected: - sptr GetDms(); -}; - -void DistributedSchedAbilityShellTest::SetUpTestCase() -{ -} - -void DistributedSchedAbilityShellTest::TearDownTestCase() -{ -} - -void DistributedSchedAbilityShellTest::SetUp() -{ -} - -void DistributedSchedAbilityShellTest::TearDown() -{ -} - -sptr DistributedSchedAbilityShellTest::GetDms() -{ - if (proxy_ != nullptr) { - return proxy_; - } - auto sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - EXPECT_TRUE(sm != nullptr); - if (sm == nullptr) { - DTEST_LOG << "DistributedSchedAbilityShellTest sm is nullptr" << std::endl; - return nullptr; - } - auto distributedObject = sm->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); - EXPECT_TRUE(distributedObject != nullptr); - proxy_ = iface_cast(distributedObject); - if (proxy_ == nullptr) { - DTEST_LOG << "DistributedSchedAbilityShellTest distributedObject is nullptr" << std::endl; - } - return proxy_; -} - -/** - * @tc.name: RegisterAbilityToken001 - * @tc.desc: register ability token with null token. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken001, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken001 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with null token - * @tc.expected: step1. return ERR_NULL_OBJECT. - */ - int result = proxy->RegisterAbilityToken(nullptr, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - EXPECT_EQ(static_cast(ERR_NULL_OBJECT), result); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken001 end" << std::endl; -} - -/** - * @tc.name: RegisterAbilityToken002 - * @tc.desc: register ability token with null callback. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken002, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken002 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with null callback - * @tc.expected: step1. return ERR_NULL_OBJECT. - */ - int result = proxy->RegisterAbilityToken(token, nullptr); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - EXPECT_EQ(static_cast(ERR_NULL_OBJECT), result); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken002 end" << std::endl; -} - -/** - * @tc.name: RegisterAbilityToken003 - * @tc.desc: register ability token with callback and token. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken003, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken003 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - EXPECT_EQ(static_cast(ERR_OK), result); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken003 end" << std::endl; -} - -/** - * @tc.name: RegisterAbilityToken004 - * @tc.desc: register ability token with callback and two tokens. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken004, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken004 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr token1 = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - /** - * @tc.steps: step2. register ability token with callback and token1 - * @tc.expected: step2. return ERR_OK. - */ - int result1 = proxy->RegisterAbilityToken(token1, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - - EXPECT_EQ(static_cast(ERR_OK), result); - EXPECT_EQ(static_cast(ERR_OK), result1); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken004 end" << std::endl; -} - -/** - * @tc.name: RegisterAbilityToken005 - * @tc.desc: register ability token with two callbacks and two tokens. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken005, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken005 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr token1 = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr continuationCallback1 = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - /** - * @tc.steps: step2. register ability token with callback1 and token1 - * @tc.expected: step2. return ERR_OK. - */ - int result1 = proxy->RegisterAbilityToken(token1, continuationCallback1); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - - EXPECT_EQ(static_cast(ERR_OK), result); - EXPECT_EQ(static_cast(ERR_OK), result1); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken005 end" << std::endl; -} - -/** - * @tc.name: RegisterAbilityToken006 - * @tc.desc: register ability token with callback and two repeat tokens. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken006, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken006 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - /** - * @tc.steps: step2. register ability token with callback and repeat token - * @tc.expected: step2. return REG_REPEAT_ABILITY_TOKEN_ERR. - */ - int result1 = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - - EXPECT_EQ(static_cast(REG_REPEAT_ABILITY_TOKEN_ERR), result1); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken006 end" << std::endl; -} - -/** - * @tc.name: RegisterAbilityToken007 - * @tc.desc: register ability token with two callbacks and two tokens with dms. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken007, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken007 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr token1 = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr continuationCallback1 = new MockDistributedSched(); - - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = DistributedSchedService::GetInstance().RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - /** - * @tc.steps: step2. register ability token with callback1 and token1 - * @tc.expected: step2. return ERR_OK. - */ - int result1 = DistributedSchedService::GetInstance().RegisterAbilityToken(token1, continuationCallback1); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - - EXPECT_EQ(static_cast(ERR_OK), result); - EXPECT_EQ(static_cast(ERR_OK), result1); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken007 end" << std::endl; -} - -/** - * @tc.name: RegisterAbilityToken008 - * @tc.desc: register ability token with callback and two repeat tokens. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterAbilityToken008, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken008 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = DistributedSchedService::GetInstance().RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - /** - * @tc.steps: step2. register ability token with callback and repeat token - * @tc.expected: step2. return REG_REPEAT_ABILITY_TOKEN_ERR. - */ - int result1 = DistributedSchedService::GetInstance().RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - - EXPECT_EQ(static_cast(REG_REPEAT_ABILITY_TOKEN_ERR), result1); - sptr continuationCallback1 = new MockDistributedSched(); - DistributedSchedService::GetInstance().UnregisterAbilityToken(token, continuationCallback1); - DistributedSchedService::GetInstance().UnregisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterAbilityToken008 end" << std::endl; -} - -/** - * @tc.name: UnregisterAbilityToken001 - * @tc.desc: unregister ability token with null token. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, UnregisterAbilityToken001, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken001 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. unregister ability token with null token - * @tc.expected: step1. return ERR_NULL_OBJECT. - */ - int result = proxy->UnregisterAbilityToken(nullptr, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - EXPECT_EQ(static_cast(ERR_NULL_OBJECT), result); - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken001 end" << std::endl; -} - -/** - * @tc.name: UnregisterAbilityToken002 - * @tc.desc: unregister ability token with null token. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, UnregisterAbilityToken002, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken002 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. unregister ability token with null callback - * @tc.expected: step1. return ERR_NULL_OBJECT. - */ - int result = proxy->UnregisterAbilityToken(token, nullptr); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - EXPECT_EQ(static_cast(ERR_NULL_OBJECT), result); - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken002 end" << std::endl; -} - -/** - * @tc.name: UnregisterAbilityToken003 - * @tc.desc: unregister ability token with callback and token. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, UnregisterAbilityToken003, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken003 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - EXPECT_EQ(static_cast(ERR_OK), result); - /** - * @tc.steps: step2. unregister ability token with token and callback - * @tc.expected: step2. return ERR_OK. - */ - int result1 = proxy->UnregisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - EXPECT_EQ(static_cast(ERR_OK), result1); - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken003 end" << std::endl; -} - -/** - * @tc.name: UnregisterAbilityToken004 - * @tc.desc: unregister ability token with wrong callback. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, UnregisterAbilityToken004, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken004 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - EXPECT_EQ(static_cast(ERR_OK), result); - /** - * @tc.steps: step2. unregister ability token with token and callback - * @tc.expected: step2. return NO_APP_THREAD_ERR. - */ - sptr continuationCallback1 = new MockDistributedSched(); - int result1 = proxy->UnregisterAbilityToken(token, continuationCallback1); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - EXPECT_EQ(static_cast(NO_APP_THREAD_ERR), result1); - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken004 end" << std::endl; -} - -/** - * @tc.name: UnregisterAbilityToken005 - * @tc.desc: unregister ability token with wrong callback. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, UnregisterAbilityToken005, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken005 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = proxy->RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - EXPECT_EQ(static_cast(ERR_OK), result); - /** - * @tc.steps: step2. unregister ability token with token and callback - * @tc.expected: step2. return NO_ABILITY_TOKEN_ERR. - */ - sptr token1 = new MockDistributedSched(); - int result1 = proxy->UnregisterAbilityToken(token1, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl; - EXPECT_EQ(static_cast(NO_ABILITY_TOKEN_ERR), result1); - DTEST_LOG << "DistributedSchedAbilityShellTest UnregisterAbilityToken005 end" << std::endl; -} - -/** - * @tc.name: RegisterUnregisterAbilityTokenPressure001 - * @tc.desc: register and unregister ability token pressure. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RegisterUnregisterAbilityTokenPressure001, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterUnregisterAbilityTokenPressure001 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - sptr proxy = GetDms(); - if (proxy == nullptr) { - return; - } - /** - * @tc.steps: step1. register ability token for 100 times - */ - for (int index = 0; index < LOOP_TIMES; ++index) { - proxy->RegisterAbilityToken(token, continuationCallback); - } - - /** - * @tc.steps: step2. unregister ability token for 100 times - */ - for (int index = 0; index < LOOP_TIMES; ++index) { - proxy->UnregisterAbilityToken(token, continuationCallback); - } - DTEST_LOG << "DistributedSchedAbilityShellTest RegisterUnregisterAbilityTokenPressure001 end" << std::endl; -} - -/** - * @tc.name: RemoveContinuationCallback001 - * @tc.desc: remove continuation callback with dms. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, RemoveContinuationCallback001, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest RemoveContinuationCallback001 start" << std::endl; - AppExecFwk::AbilityInfo abilityInfo; - sptr token = new MockDistributedSched(); - sptr continuationCallback = new MockDistributedSched(); - /** - * @tc.steps: step1. register ability token with callback and token - * @tc.expected: step1. return ERR_OK. - */ - int result = DistributedSchedService::GetInstance().RegisterAbilityToken(token, continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest result: "<< result << std::endl; - - /** - * @tc.steps: step2. remove continuation callback with dms - * @tc.expected: step2. return ERR_OK. - */ - DistributedSchedAbilityShell::GetInstance().RemoveContinuationCallback(continuationCallback); - - EXPECT_EQ(static_cast(ERR_OK), result); - DTEST_LOG << "DistributedSchedAbilityShellTest RemoveContinuationCallback001 end" << std::endl; -} - -/** - * @tc.name: ContinuationCallbackAddDeathRecipient001 - * @tc.desc: add death recipient for continuation callback. - * @tc.type: FUNC - */ - -HWTEST_F(DistributedSchedAbilityShellTest, ContinuationCallbackAddDeathRecipient001, TestSize.Level1) -{ - DTEST_LOG << "DistributedSchedAbilityShellTest ContinuationCallbackAddDeathRecipient001 start" << std::endl; - sptr continuationCallback = new MockDistributedSched(); - /** - * @tc.steps: step1. add death recipient for continuation callback - */ - sptr(new ContinuationCallbackDeathRecipient())->OnRemoteDied(continuationCallback); - DTEST_LOG << "DistributedSchedAbilityShellTest ContinuationCallbackAddDeathRecipient001 end" << std::endl; -} -} // DistributedSchedule -} // namespace OHOS diff --git a/services/dtbschedmgr/test/unittest/distributed_sched_connect_test.cpp b/services/dtbschedmgr/test/unittest/distributed_sched_connect_test.cpp old mode 100755 new mode 100644 index 4f13ce42..042bb9b1 --- a/services/dtbschedmgr/test/unittest/distributed_sched_connect_test.cpp +++ b/services/dtbschedmgr/test/unittest/distributed_sched_connect_test.cpp @@ -46,6 +46,20 @@ public: int32_t resultCode) override; }; +class AbilityConnectionWrapperStubTest : public AAFwk::AbilityConnectionStub { +public: + explicit AbilityConnectionWrapperStubTest(sptr connection) : distributedConnection_(connection) {} + ~AbilityConnectionWrapperStubTest() = default; + + void OnAbilityConnectDone(const AppExecFwk::ElementName& element, + const sptr& remoteObject, int32_t resultCode) override; + void OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, + int32_t resultCode) override; + +private: + sptr distributedConnection_; +}; + class DistributedSchedConnectTest : public testing::Test { public: static void SetUpTestCase(); @@ -54,8 +68,15 @@ public: void TearDown(); void AddSession(const sptr& connect, const std::string& localDeviceId, - const std::string& remoteDeviceId, const AAFwk::Want& want); - void RemoveSession(const sptr& connect); + const std::string& remoteDeviceId, const AAFwk::Want& want) const; + void RemoveSession(const sptr& connect) const; + + void AddConnectInfo(const sptr& connect, const std::string& localDeviceId, + const std::string& remoteDeviceId) const; + void RemoveConnectInfo(const sptr& connect) const; + + void AddConnectCount(int32_t uid) const; + void DecreaseConnectCount(int32_t uid) const; }; void AbilityConnectCallbackTest::OnAbilityConnectDone(const AppExecFwk::ElementName& element, @@ -68,6 +89,16 @@ void AbilityConnectCallbackTest::OnAbilityDisconnectDone(const AppExecFwk::Eleme { } +void AbilityConnectionWrapperStubTest::OnAbilityConnectDone(const AppExecFwk::ElementName& element, + const sptr& remoteObject, int32_t resultCode) +{ +} + +void AbilityConnectionWrapperStubTest::OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, + int32_t resultCode) +{ +} + void DistributedSchedConnectTest::SetUpTestCase() { } @@ -85,7 +116,7 @@ void DistributedSchedConnectTest::TearDown() } void DistributedSchedConnectTest::AddSession(const sptr& connect, - const std::string& localDeviceId, const std::string& remoteDeviceId, const AAFwk::Want& want) + const std::string& localDeviceId, const std::string& remoteDeviceId, const AAFwk::Want& want) const { if (connect == nullptr) { return; @@ -101,7 +132,7 @@ void DistributedSchedConnectTest::AddSession(const sptr& connect, remoteDeviceId, want.GetElement(), callerInfo, TargetComponent::HARMONY_COMPONENT); } -void DistributedSchedConnectTest::RemoveSession(const sptr& connect) +void DistributedSchedConnectTest::RemoveSession(const sptr& connect) const { if (connect == nullptr) { return; @@ -111,6 +142,54 @@ void DistributedSchedConnectTest::RemoveSession(const sptr& conne DistributedSchedService::GetInstance().distributedConnectAbilityMap_.erase(connect); } +void DistributedSchedConnectTest::AddConnectInfo(const sptr& connect, + const std::string& localDeviceId, const std::string& remoteDeviceId) const +{ + if (connect == nullptr) { + return; + } + + std::lock_guard autoLock(DistributedSchedService::GetInstance().distributedLock_); + CallerInfo callerInfo; + callerInfo.uid = IPCSkeleton::GetCallingUid(); + callerInfo.pid = IPCSkeleton::GetCallingPid(); + callerInfo.sourceDeviceId = localDeviceId; + callerInfo.callerType = CALLER_TYPE_HARMONY; + + sptr callbackWrapper = new AbilityConnectionWrapperStubTest(connect); + ConnectInfo connectInfo {callerInfo, callbackWrapper}; + DistributedSchedService::GetInstance().connectAbilityMap_.emplace(connect, connectInfo); +} + +void DistributedSchedConnectTest::RemoveConnectInfo(const sptr& connect) const +{ + if (connect == nullptr) { + return; + } + + std::lock_guard autoLock(DistributedSchedService::GetInstance().distributedLock_); + DistributedSchedService::GetInstance().connectAbilityMap_.erase(connect); +} + +void DistributedSchedConnectTest::AddConnectCount(int32_t uid) const +{ + if (uid < 0) { + return; + } + + auto& trackingUidMap = DistributedSchedService::GetInstance().trackingUidMap_; + ++trackingUidMap[uid]; +} + +void DistributedSchedConnectTest::DecreaseConnectCount(int32_t uid) const +{ + if (uid < 0) { + return; + } + + DistributedSchedService::GetInstance().DecreaseConnectLocked(uid); +} + /** * @tc.name: DumpConnectInfo_001 * @tc.desc: dump connect ability info by call Dump @@ -236,6 +315,81 @@ HWTEST_F(DistributedSchedConnectTest, ProcessConnectDied002, TestSize.Level0) RemoveSession(connect); } +/** + * @tc.name: ProcessConnectDied003 + * @tc.desc: process connect died and check the trackingUidMap_ + * @tc.type: FUNC + * @tc.require: AR000GI8IE + */ +HWTEST_F(DistributedSchedConnectTest, ProcessConnectDied003, TestSize.Level1) +{ + DTEST_LOG << "DistributedSchedServiceTest ProcessConnectDied003 start" << std::endl; + OHOS::AAFwk::Want want; + want.SetElementName("", "ohos.demo.bundleName", "abilityName"); + sptr connect = new AbilityConnectCallbackTest(); + AddSession(connect, "123_local_device_id", "123_remote_device_id", want); + + auto& trackingUidMap = DistributedSchedService::GetInstance().trackingUidMap_; + /** + * @tc.steps: step1. Increase connect count + * @tc.expected: step1. connect count increase one + */ + + int32_t uid = IPCSkeleton::GetCallingUid(); + uint32_t oldCount = trackingUidMap[uid]; + AddConnectCount(uid); + EXPECT_EQ(trackingUidMap[uid] - oldCount, static_cast(1)); + + /** + * @tc.steps: step2. process connect died and then check the trackingUidMap_ + * @tc.expected: step2. the connect count is decrease + */ + DistributedSchedService::GetInstance().ProcessConnectDied(connect); + auto iter = trackingUidMap.find(uid); + if (iter != trackingUidMap.end()) { + EXPECT_EQ(trackingUidMap[uid], oldCount); + } + + RemoveConnectInfo(connect); +} + +/** + * @tc.name: ProcessConnectDied004 + * @tc.desc: process connect died and check the connectAbilityMap_ + * @tc.type: FUNC + * @tc.require: AR000GI8IE + */ +HWTEST_F(DistributedSchedConnectTest, ProcessConnectDied004, TestSize.Level1) +{ + DTEST_LOG << "DistributedSchedServiceTest ProcessConnectDied004 start" << std::endl; + auto& connectAbilityMap = DistributedSchedService::GetInstance().connectAbilityMap_; + auto& distributedLock = DistributedSchedService::GetInstance().distributedLock_; + + /** + * @tc.steps: step1. add one connectInfo + * @tc.expected: step1. can find the newly-added connectInfo + */ + sptr connect = new AbilityConnectCallbackTest(); + AddConnectInfo(connect, "123_local_device_id", "123_remote_device_id"); + { + std::lock_guard autoLock(distributedLock); + EXPECT_EQ(connectAbilityMap.size(), static_cast(1)); + } + + /** + * @tc.steps: step2. process connect died and then check the connectAbilityMap_ + * @tc.expected: step2. the connectInfo is removed + */ + DistributedSchedService::GetInstance().DisconnectAbilityFromRemote(connect, + IPCSkeleton::GetCallingUid(), "123_local_device_id"); + { + std::lock_guard autoLock(distributedLock); + EXPECT_EQ(connectAbilityMap.size(), static_cast(0)); + } + + RemoveConnectInfo(connect); +} + /** * @tc.name: ProcessDeviceOffline001 * @tc.desc: process device offline with only one connection @@ -340,6 +494,79 @@ HWTEST_F(DistributedSchedConnectTest, ProcessDeviceOffline003, TestSize.Level0) RemoveSession(connect); } +/** + * @tc.name: ProcessDeviceOffline004 + * @tc.desc: process device offline and check the trackingUidMap_ + * @tc.type: FUNC + * @tc.require: AR000GI8IE + */ +HWTEST_F(DistributedSchedConnectTest, ProcessDeviceOffline004, TestSize.Level1) +{ + DTEST_LOG << "DistributedSchedServiceTest ProcessDeviceOffline004 start" << std::endl; + OHOS::AAFwk::Want want; + want.SetElementName("", "ohos.demo.bundleName", "abilityName"); + sptr connect = new AbilityConnectCallbackTest(); + AddSession(connect, "123_local_device_id", "123_remote_device_id", want); + + auto& trackingUidMap = DistributedSchedService::GetInstance().trackingUidMap_; + /** + * @tc.steps: step1. Increase connect count + * @tc.expected: step1. connect count increase one + */ + int32_t uid = IPCSkeleton::GetCallingUid(); + uint32_t oldCount = trackingUidMap[uid]; + AddConnectCount(uid); + EXPECT_EQ(trackingUidMap[uid] - oldCount, static_cast(1)); + + /** + * @tc.steps: step2. process device offline and then check the trackingUidMap_ + * @tc.expected: step2. the connect count is decrease + */ + DistributedSchedService::GetInstance().ProcessDeviceOffline("123_remote_device_id"); + auto iter = trackingUidMap.find(uid); + if (iter != trackingUidMap.end()) { + EXPECT_EQ(trackingUidMap[uid], oldCount); + } + + RemoveConnectInfo(connect); +} + +/** + * @tc.name: ProcessDeviceOffline005 + * @tc.desc: process device offline and check the connectAbilityMap_ + * @tc.type: FUNC + * @tc.require: AR000GI8IE + */ +HWTEST_F(DistributedSchedConnectTest, ProcessDeviceOffline005, TestSize.Level1) +{ + DTEST_LOG << "DistributedSchedServiceTest ProcessDeviceOffline005 start" << std::endl; + auto& connectAbilityMap = DistributedSchedService::GetInstance().connectAbilityMap_; + auto& distributedLock = DistributedSchedService::GetInstance().distributedLock_; + + /** + * @tc.steps: step1. add one connectInfo + * @tc.expected: step1. can find the newly-added connectInfo + */ + sptr connect = new AbilityConnectCallbackTest(); + AddConnectInfo(connect, "123_local_device_id", "123_remote_device_id"); + { + std::lock_guard autoLock(distributedLock); + EXPECT_EQ(connectAbilityMap.size(), static_cast(1)); + } + + /** + * @tc.steps: step2. process device offline and then check the connectAbilityMap_ + * @tc.expected: step2. the connectInfo is removed + */ + DistributedSchedService::GetInstance().ProcessDeviceOffline("123_local_device_id"); + { + std::lock_guard autoLock(distributedLock); + EXPECT_EQ(connectAbilityMap.size(), static_cast(0)); + } + + RemoveConnectInfo(connect); +} + /** * @tc.name: DisconnectRemoteAbility001 * @tc.desc: disconnect remote ability @@ -370,5 +597,42 @@ HWTEST_F(DistributedSchedConnectTest, DisconnectRemoteAbility001, TestSize.Level RemoveSession(connect); } + +/** + * @tc.name: DisconnectRemoteAbility002 + * @tc.desc: disconnect remote ability and check the trackingUidMap_ + * @tc.type: FUNC + * @tc.require: AR000GI8IE + */ +HWTEST_F(DistributedSchedConnectTest, DisconnectRemoteAbility002, TestSize.Level1) +{ + DTEST_LOG << "DistributedSchedServiceTest DisconnectRemoteAbility002 start" << std::endl; + OHOS::AAFwk::Want want; + want.SetElementName("", "ohos.demo.bundleName", "abilityName"); + sptr connect = new AbilityConnectCallbackTest(); + AddSession(connect, "123_local_device_id", "123_remote_device_id", want); + + auto& trackingUidMap = DistributedSchedService::GetInstance().trackingUidMap_; + /** + * @tc.steps: step1. Increase connect count + * @tc.expected: step1. connect count increase one + */ + int32_t uid = IPCSkeleton::GetCallingUid(); + uint32_t oldCount = trackingUidMap[uid]; + AddConnectCount(uid); + EXPECT_EQ(trackingUidMap[uid] - oldCount, static_cast(1)); + + /** + * @tc.steps: step2. disconnect remote ability and then check the trackingUidMap_ + * @tc.expected: step2. the connect count is decrease + */ + DistributedSchedService::GetInstance().DisconnectRemoteAbility(connect); + auto iter = trackingUidMap.find(uid); + if (iter != trackingUidMap.end()) { + EXPECT_EQ(trackingUidMap[uid], oldCount); + } + + RemoveConnectInfo(connect); +} } } \ No newline at end of file diff --git a/services/dtbschedmgr/test/unittest/distributed_sched_continuation_test.cpp b/services/dtbschedmgr/test/unittest/distributed_sched_continuation_test.cpp old mode 100755 new mode 100644 index 6d3ac97c..f89de9c7 --- a/services/dtbschedmgr/test/unittest/distributed_sched_continuation_test.cpp +++ b/services/dtbschedmgr/test/unittest/distributed_sched_continuation_test.cpp @@ -77,23 +77,14 @@ std::shared_ptr DSchedContinuationTest::MockWant(const string& bundleName, return spWant; } -std::shared_ptr DSchedContinuationTest::MockAbilityInfo(const string& bundleName, const string& ability, - const string& devId) -{ - shared_ptr spAbility = make_shared(); - spAbility->bundleName = bundleName; - spAbility->deviceId = devId; - return spAbility; -} - int32_t DSchedContinuationTest::StartContinuation(const sptr& abilityToken, int32_t flags) { string bundleName = "bundleName"; string abilityName = "abilityName"; string devId = "devId"; shared_ptr spWant = MockWant(bundleName, abilityName, flags); - shared_ptr spAbility = MockAbilityInfo(bundleName, abilityName, devId); - return DistributedSchedService::GetInstance().StartContinuation(*spWant, *spAbility, abilityToken); + int callerUid = 0; + return DistributedSchedService::GetInstance().StartContinuation(*spWant, abilityToken, callerUid); } /** diff --git a/services/dtbschedmgr/test/unittest/distributed_sched_service_test.cpp b/services/dtbschedmgr/test/unittest/distributed_sched_service_test.cpp index 0888a14d..03103845 100644 --- a/services/dtbschedmgr/test/unittest/distributed_sched_service_test.cpp +++ b/services/dtbschedmgr/test/unittest/distributed_sched_service_test.cpp @@ -115,8 +115,7 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_001, TestSize.Level1) * @tc.expected: step1. StartRemoteAbility return INVALID_PARAMETERS_ERR */ AAFwk::Want want; - AppExecFwk::AbilityInfo abilityInfo; - int result1 = proxy->StartRemoteAbility(want, abilityInfo, 0); + int result1 = proxy->StartRemoteAbility(want, 0, 0); DTEST_LOG << "result1:" << result1 << std::endl; /** * @tc.steps: step2. StartRemoteAbility with empty want's deviceId @@ -125,7 +124,7 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_001, TestSize.Level1) AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); want.SetElement(element); - int result2 = proxy->StartRemoteAbility(want, abilityInfo, 0); + int result2 = proxy->StartRemoteAbility(want, 0, 0); DTEST_LOG << "result2:" << result2 << std::endl; EXPECT_EQ(static_cast(INVALID_PARAMETERS_ERR), result1); @@ -153,15 +152,14 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_002, TestSize.Level0) AppExecFwk::ElementName element("123456", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); want.SetElement(element); - AppExecFwk::AbilityInfo abilityInfo; - int result1 = DistributedSchedService::GetInstance().StartRemoteAbility(want, abilityInfo, 0); + int result1 = DistributedSchedService::GetInstance().StartRemoteAbility(want, 0, 0); DTEST_LOG << "result:" << result1 << std::endl; std::string deviceId; DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(deviceId); AppExecFwk::ElementName element1(deviceId, "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); want.SetElement(element1); - int result2 = DistributedSchedService::GetInstance().StartRemoteAbility(want, abilityInfo, 0); + int result2 = DistributedSchedService::GetInstance().StartRemoteAbility(want, 0, 0); DTEST_LOG << "result:" << result2 << std::endl; EXPECT_EQ(static_cast(INVALID_PARAMETERS_ERR), result1); EXPECT_EQ(static_cast(INVALID_PARAMETERS_ERR), result2); @@ -184,10 +182,7 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_003, TestSize.Level0) AppExecFwk::ElementName element("123456", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); want.SetElement(element); - AppExecFwk::AbilityInfo abilityInfo; - GetAbilityInfo("com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility", - "com.ohos.distributedmusicplayer", "192.168.43.101", abilityInfo); - int result = DistributedSchedService::GetInstance().StartRemoteAbility(want, abilityInfo, 0); + int result = DistributedSchedService::GetInstance().StartRemoteAbility(want, 0, 0); DTEST_LOG << "result:" << result << std::endl; EXPECT_EQ(static_cast(INVALID_PARAMETERS_ERR), result); DTEST_LOG << "DistributedSchedServiceTest StartRemoteAbility_003 end" << std::endl; @@ -213,10 +208,7 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_004, TestSize.Level1) AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); want.SetElement(element); - AppExecFwk::AbilityInfo abilityInfo; - GetAbilityInfo("com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility", - "com.ohos.distributedmusicplayer", "192.168.43.101", abilityInfo); - int result = proxy->StartRemoteAbility(want, abilityInfo, 0); + int result = proxy->StartRemoteAbility(want, 0, 0); DTEST_LOG << "result:" << result << std::endl; EXPECT_EQ(static_cast(INVALID_PARAMETERS_ERR), result); DTEST_LOG << "DistributedSchedServiceTest StartRemoteAbility_004 end" << std::endl; @@ -274,9 +266,7 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_002, TestSize.Level if (proxy == nullptr) { return; } - /** - * @tc.steps: step1. set want and abilityInfo - */ + AAFwk::Want want; AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); @@ -288,16 +278,10 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_002, TestSize.Level callerInfo.uid = 0; callerInfo.sourceDeviceId = "255.255.255.255"; IDistributedSched::AccountInfo accountInfo; - /** - * @tc.steps: step2. StartAbilityFromRemote with abilityInfo which is of ACTIVITY type - * @tc.expected: step2. StartAbilityFromRemote for result - */ + int result1 = proxy->StartAbilityFromRemote(want, abilityInfo, 0, callerInfo, accountInfo); DTEST_LOG << "result1 is" << result1 << std::endl; - /** - * @tc.steps: step3. StartAbilityFromRemote with abilityInfo which is of SERVICE type - * @tc.expected: step3. StartAbilityFromRemote for result - */ + AppExecFwk::ElementName element2("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbilityService"); want.SetElement(element2); @@ -354,9 +338,7 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_004, TestSize.Level { DTEST_LOG << "DistributedSchedServiceTest StartAbilityFromRemote_004 start" << std::endl; sptr proxy = GetDms(); - /** - * @tc.steps: step1. set want and abilityInfo - */ + AAFwk::Want want; AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); @@ -368,17 +350,11 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_004, TestSize.Level callerInfo.uid = 0; callerInfo.sourceDeviceId = "255.255.255.255"; IDistributedSched::AccountInfo accountInfo; - /** - * @tc.steps: step2. StartAbilityFromRemote with abilityInfo which is of ACTIVITY type - * @tc.expected: step2. StartAbilityFromRemote for result - */ + int result1 = DistributedSchedService::GetInstance().StartAbilityFromRemote(want, abilityInfo, 0, callerInfo, accountInfo); DTEST_LOG << "result1:" << result1 << std::endl; - /** - * @tc.steps: step3. StartAbilityFromRemote with abilityInfo which is of SERVICE type - * @tc.expected: step3. StartAbilityFromRemote for result - */ + AppExecFwk::ElementName element2("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbilityService"); want.SetElement(element2); @@ -401,9 +377,7 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_005, TestSize.Level { DTEST_LOG << "DistributedSchedServiceTest StartAbilityFromRemote_005 start" << std::endl; sptr proxy = GetDms(); - /** - * @tc.steps: step1. set want and abilityInfo - */ + AAFwk::Want want; AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility"); @@ -417,17 +391,11 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_005, TestSize.Level IDistributedSched::AccountInfo accountInfo; accountInfo.accountType = 1; accountInfo.groupIdList.push_back("123456"); - /** - * @tc.steps: step2. StartAbilityFromRemote with abilityInfo which is of ACTIVITY type - * @tc.expected: step2. StartAbilityFromRemote for result - */ + int result1 = DistributedSchedService::GetInstance().StartAbilityFromRemote(want, abilityInfo, 0, callerInfo, accountInfo); DTEST_LOG << "result1:" << result1 << std::endl; - /** - * @tc.steps: step3. StartAbilityFromRemote with abilityInfo which is of SERVICE type - * @tc.expected: step3. StartAbilityFromRemote for result - */ + AppExecFwk::ElementName element2("", "com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbilityService"); want.SetElement(element2); diff --git a/services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.cpp b/services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.cpp new file mode 100644 index 00000000..6b903821 --- /dev/null +++ b/services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.cpp @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dms_mission_manager_test.h" + +#include "distributed_sched_proxy.h" +#include "distributed_sched_service.h" +#include "dtbschedmgr_device_info_storage.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "mission/mission_constant.h" +#include "string_ex.h" +#include "system_ability_definition.h" +#include "test_log.h" + +#define private public +#include "mission/distributed_sched_mission_manager.h" + +using namespace std; +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace DistributedSchedule { +namespace { +const std::string DEVICE_NAME = "DEVICE_PHONE_001"; +const std::string DEVICE_ID = "123456789ABCD"; +const std::u16string U16DEVICE_ID = u"123456789ABCD"; +const std::string BUNDLE_NAME = "ohos.test.test"; +const int32_t NUM_MISSIONS = 100; +} +void DMSMissionManagerTest::SetUpTestCase() +{ +} + +void DMSMissionManagerTest::TearDownTestCase() +{ +} + +void DMSMissionManagerTest::SetUp() +{ + string localDeviceId; + if (!DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(localDeviceId)) { + DTEST_LOG << "getLocalDevicesId failed!" << std::endl; + return; + } + localDeviceId_ = localDeviceId; + localDev_ = Str8ToStr16(localDeviceId); +} + +void DMSMissionManagerTest::TearDown() +{ +} + +sptr DMSMissionManagerTest::GetDms() +{ + if (proxy_ != nullptr) { + return proxy_; + } + auto sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sm != nullptr); + if (sm == nullptr) { + DTEST_LOG << "DMSMissionManagerTest sm is nullptr" << std::endl; + return nullptr; + } + DTEST_LOG << "DMSMissionManagerTest sm is not nullptr" << std::endl; + auto distributedObject = sm->GetSystemAbility(DISTRIBUTED_SCHED_SA_ID); + EXPECT_TRUE(distributedObject != nullptr); + proxy_ = iface_cast(distributedObject); + if (proxy_ == nullptr) { + DTEST_LOG << "DMSMissionManagerTest DistributedSched is nullptr" << std::endl; + } + DTEST_LOG << "DMSMissionManagerTest DistributedSched is not nullptr" << std::endl; + return proxy_; +} + +/** + * @tc.name: testGetRemoteMissionInfo001 + * @tc.desc: get remote mission info + * @tc.type: FUNC + * @tc.require:AR000GK66R + */ +HWTEST_F(DMSMissionManagerTest, testGetRemoteMissionInfo001, TestSize.Level1) +{ + std::vector infos; + auto ret = DistributedSchedMissionManager::GetInstance().GetMissionInfos(DEVICE_ID, 0, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = DistributedSchedMissionManager::GetInstance().GetMissionInfos(localDeviceId_, 0, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = DistributedSchedMissionManager::GetInstance().GetMissionInfos("", 0, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = DistributedSchedMissionManager::GetInstance().GetMissionInfos(DEVICE_ID, -1, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = DistributedSchedMissionManager::GetInstance().GetMissionInfos(localDeviceId_, -1, infos); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testGetRemoteMissionInfo002 + * @tc.desc: get remote mission info + * @tc.type: FUNC + * @tc.require:AR000GK66R + */ +HWTEST_F(DMSMissionManagerTest, testGetRemoteMissionInfo002, TestSize.Level1) +{ + sptr proxy = GetDms(); + if (proxy == nullptr) { + return; + } + std::vector infos; + auto ret = proxy->GetMissionInfos(DEVICE_ID, 0, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = proxy->GetMissionInfos(localDeviceId_, 0, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = proxy->GetMissionInfos("", 0, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = proxy->GetMissionInfos(DEVICE_ID, -1, infos); + EXPECT_TRUE(ret != ERR_NONE); + + ret = proxy->GetMissionInfos(localDeviceId_, -1, infos); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testPrepareAndSyncMissions001 + * @tc.desc: prepare and sync missions from remote + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testPrepareAndSyncMissions001, TestSize.Level1) +{ + sptr proxy = GetDms(); + if (proxy == nullptr) { + return; + } + std::vector infos; + auto ret = proxy->PrepareAndSyncMissions(U16DEVICE_ID, false, 0); + EXPECT_TRUE(ret != ERR_NONE); + + ret = proxy->PrepareAndSyncMissions(localDev_, false, 0); + EXPECT_TRUE(ret != ERR_NONE); + + ret = proxy->PrepareAndSyncMissions(u"", false, 0); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testIsDeviceIdValidated001 + * @tc.desc: judging whether the deviceId is valid + * @tc.type: FUNC + * @tc.require:AR000GK66R + */ +HWTEST_F(DMSMissionManagerTest, testIsDeviceIdValidated001, TestSize.Level1) +{ + std::string emptyDeviceId = ""; + auto ret = DistributedSchedMissionManager::GetInstance().IsDeviceIdValidated(emptyDeviceId); + EXPECT_FALSE(ret); + + ret = DistributedSchedMissionManager::GetInstance().IsDeviceIdValidated(DEVICE_ID); + EXPECT_FALSE(ret); + + ret = DistributedSchedMissionManager::GetInstance().IsDeviceIdValidated(localDeviceId_); + EXPECT_FALSE(ret); +} + +/** + * @tc.name: testGetMissionInfos003 + * @tc.desc: get remote missions + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testGetMissionInfos001, TestSize.Level1) +{ + std::string deviceid = DEVICE_ID; + int32_t numMissions = NUM_MISSIONS; + std::vector missionInfos; + + auto ret = DistributedSchedMissionManager::GetInstance().GetMissionInfos(deviceid, numMissions, missionInfos); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testFetchCachedRemoteMissions001 + * @tc.desc: test stop fake device, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testFetchCachedRemoteMissions001, TestSize.Level1) +{ + std::vector infos; + auto ret = DistributedSchedMissionManager::GetInstance().FetchCachedRemoteMissions(DEVICE_ID, 0, infos); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testFetchCachedRemoteMissions001 + * @tc.desc: test check support osd fake device, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testCheckSupportOsd001, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().CheckSupportOsd(DEVICE_ID); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testFetchCachedRemoteMissions002 + * @tc.desc: test check support osd fake device, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testCheckSupportOsd002, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().CheckSupportOsd(DEVICE_ID); + EXPECT_TRUE(ret != ERR_NONE); + ret = DistributedSchedMissionManager::GetInstance().CheckSupportOsd(""); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: GetOsdSwitchValueFromRemote001 + * @tc.desc: test GetOsdSwitchValueFromRemote, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, GetOsdSwitchValueFromRemote001, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().GetOsdSwitchValueFromRemote(); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testUpdateOsdSwitchValueFromRemote001 + * @tc.desc: test UpdateOsdSwitchValueFromRemote fake device, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testUpdateOsdSwitchValueFromRemote001, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().UpdateOsdSwitchValueFromRemote(0, DEVICE_ID); + EXPECT_TRUE(ret == ERR_NONE); +} + +/** + * @tc.name: testUpdateOsdSwitchValueFromRemote002 + * @tc.desc: test UpdateOsdSwitchValueFromRemote fake device, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testUpdateOsdSwitchValueFromRemote002, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().UpdateOsdSwitchValueFromRemote(0, DEVICE_ID); + EXPECT_TRUE(ret == ERR_NONE); + ret = DistributedSchedMissionManager::GetInstance().UpdateOsdSwitchValueFromRemote(1, DEVICE_ID); + EXPECT_TRUE(ret == ERR_NONE); +} + +/** + * @tc.name: testUpdateOsdSwitchValueFromRemote003 + * @tc.desc: test UpdateOsdSwitchValueFromRemote fake device, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testUpdateOsdSwitchValueFromRemote003, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().UpdateOsdSwitchValueFromRemote(0, ""); + EXPECT_TRUE(ret == ERR_NONE); + ret = DistributedSchedMissionManager::GetInstance().UpdateOsdSwitchValueFromRemote(1, ""); + EXPECT_TRUE(ret == ERR_NONE); +} + +/** + * @tc.name: testUpdateSwitchValueToRemote001 + * @tc.desc: test UpdateSwitchValueToRemote, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testUpdateSwitchValueToRemote001, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().UpdateSwitchValueToRemote(); + EXPECT_TRUE(ret != ERR_NONE); +} + +/** + * @tc.name: testUpdateSwitchValueToRemote002 + * @tc.desc: test check support osd fake device, return error code + * @tc.type: FUNC + * @tc.require:AR000GK67M + */ +HWTEST_F(DMSMissionManagerTest, testUpdateSwitchValueToRemote002, TestSize.Level1) +{ + auto ret = DistributedSchedMissionManager::GetInstance().UpdateSwitchValueToRemote(); + EXPECT_TRUE(ret != ERR_NONE); + ret = DistributedSchedMissionManager::GetInstance().UpdateSwitchValueToRemote(); + EXPECT_TRUE(ret != ERR_NONE); +} +} // namespace DistributedSchedule +} // namespace OHOS diff --git a/services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.h b/services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.h new file mode 100644 index 00000000..451d043c --- /dev/null +++ b/services/dtbschedmgr/test/unittest/mission/dms_mission_manager_test.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SERVICES_DTBSCHEDMGR_TEST_UNITTEST_MISSION_DMS_MISSION_MANAGER_TEST_H +#define SERVICES_DTBSCHEDMGR_TEST_UNITTEST_MISSION_DMS_MISSION_MANAGER_TEST_H + +#include "gtest/gtest.h" + +#include "distributed_sched_interface.h" + +namespace OHOS { +namespace DistributedSchedule { +class DMSMissionManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +protected: + std::u16string localDev_; + std::string localDeviceId_; + sptr proxy_; + sptr GetDms(); +}; +} // namespace DistributedSchedule +} // namespace OHOS +#endif /* SERVICES_DTBSCHEDMGR_TEST_UNITTEST_MISSION_DMS_MISSION_MANAGER_TEST_H */ diff --git a/services/dtbschedmgr/test/unittest/mock_distributed_sched.cpp b/services/dtbschedmgr/test/unittest/mock_distributed_sched.cpp old mode 100755 new mode 100644 index 84fcfae0..88a73522 --- a/services/dtbschedmgr/test/unittest/mock_distributed_sched.cpp +++ b/services/dtbschedmgr/test/unittest/mock_distributed_sched.cpp @@ -24,7 +24,7 @@ using namespace OHOS::AppExecFwk; namespace OHOS { namespace DistributedSchedule { int32_t MockDistributedSched::StartRemoteAbility(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) + int32_t callerUid, int32_t requestCode) { return 0; } @@ -36,8 +36,8 @@ int32_t MockDistributedSched::StartAbilityFromRemote(const OHOS::AAFwk::Want& wa return 0; } -int32_t MockDistributedSched::StartContinuation(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr& abilityToken) +int32_t MockDistributedSched::StartContinuation(const OHOS::AAFwk::Want& want, const sptr& abilityToken, + int32_t callerUid) { return 0; } @@ -53,20 +53,8 @@ int32_t MockDistributedSched::NotifyContinuationResultFromRemote(int32_t session return 0; } -int32_t MockDistributedSched::RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) -{ - return 0; -} - -int32_t MockDistributedSched::UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) -{ - return 0; -} - int32_t MockDistributedSched::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, - const AppExecFwk::AbilityInfo& abilityInfo, const sptr& connect) + const sptr& connect, int32_t callerUid, int32_t callerPid) { return 0; } @@ -93,5 +81,78 @@ int32_t MockDistributedSched::NotifyProcessDiedFromRemote(const CallerInfo& call { return 0; } + +int32_t MockDistributedSched::PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::RegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::UnRegisterRemoteMissionListener(const std::u16string& devId, + const sptr& obj) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::StoreSnapshotInfo(const std::string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::NotifyMissionsChangedFromRemote(const std::vector& missionInfos, + const CallerInfo& callerInfo) +{ + expectedTrue_ = false; + return ERR_NONE; +} + +int32_t MockDistributedSched::CheckSupportOsd(const std::string& deviceId) +{ + return ERR_NONE; +} + +void MockDistributedSched::GetCachedOsdSwitch(std::vector& deviceIds, + std::vector& values) +{ + return; +} + +int32_t MockDistributedSched::GetOsdSwitchValueFromRemote() +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) +{ + return ERR_NONE; +} + +int32_t MockDistributedSched::UpdateOsdSwitchValueFromRemote(int32_t switchVal, + const std::string& sourceDeviceId) +{ + return ERR_NONE; +} } // namespace DistributedSchedule } // namespace OHOS \ No newline at end of file diff --git a/services/dtbschedmgr/test/unittest/mock_distributed_sched.h b/services/dtbschedmgr/test/unittest/mock_distributed_sched.h old mode 100755 new mode 100644 index 430d890e..d617d64c --- a/services/dtbschedmgr/test/unittest/mock_distributed_sched.h +++ b/services/dtbschedmgr/test/unittest/mock_distributed_sched.h @@ -28,27 +28,39 @@ public: } ~MockDistributedSched() = default; - int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) override; + int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) override; int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; - int32_t StartContinuation(const OHOS::AAFwk::Want& want, - const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr& abilityToken) override; + int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr& abilityToken, + int32_t callerUid) override; void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override; int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override; - int32_t RegisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) override; - int32_t UnregisterAbilityToken(const sptr& abilityToken, - const sptr& continuationCallback) override; - int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, - const sptr& connect) override; + int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid) override; int32_t DisconnectRemoteAbility(const sptr& connect) override; int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, const sptr& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; int32_t DisconnectAbilityFromRemote(const sptr& connect, int32_t uid, const std::string& sourceDeviceId) override; int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) override; + int32_t PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) override; + int32_t RegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) override; + int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr& obj) override; + int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions, + std::vector& missionInfos) override; + int32_t StoreSnapshotInfo(const std::string& deviceId, int32_t missionId, + const uint8_t* byteStream, size_t len) override; + int32_t RemoveSnapshotInfo(const std::string& deviceId, int32_t missionId) override; + int32_t NotifyMissionsChangedFromRemote(const std::vector& missionInfos, + const CallerInfo& callerInfo) override; + int32_t CheckSupportOsd(const std::string& deviceId) override; + void GetCachedOsdSwitch(std::vector& deviceIds, std::vector& values) override; + int32_t GetOsdSwitchValueFromRemote() override; + int32_t UpdateOsdSwitchValueFromRemote(int32_t switchVal, const std::string& sourceDeviceId) override; + int32_t PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, + std::vector& missionInfos) override; + int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) override; private: bool expectedTrue_ = false; };