sync code to master

Signed-off-by: majiajun <864428661@qq.com>

Change-Id: I7593eafe27246f0e9bc7e038a3232c91029478a9
This commit is contained in:
majiajun 2021-12-20 22:54:21 -08:00
parent 5990ea57fa
commit fd7a1fc30d
91 changed files with 7377 additions and 1301 deletions

View File

@ -58,6 +58,9 @@ Note:If the text contains special characters, please escape them according to th
<filefilter name="copyrightPolicyFilter" desc="copyright文件头校验策略的过滤条件" > <filefilter name="copyrightPolicyFilter" desc="copyright文件头校验策略的过滤条件" >
<filteritem type="filepath" name="etc/init/distributedsched.cfg" desc="cfg文件为json格式,无法添加版权头"/> <filteritem type="filepath" name="etc/init/distributedsched.cfg" desc="cfg文件为json格式,无法添加版权头"/>
</filefilter> </filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="binaryFileType校验策略的过滤条件" >
<filteritem type="filename" name="*.png" desc="README文件的自研开源图片"/>
</filefilter>
</filefilterlist> </filefilterlist>
</oatconfig> </oatconfig>
</configuration> </configuration>

21
etc/profile/BUILD.gn Normal file
View File

@ -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"
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!--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.
-->
<info>
<name>distributedsched</name>
<said>1401</said> <!-- distributed schedule service -->
<said>6001</said> <!-- device profile service -->
</info>

7
ohos.build Executable file → Normal file
View File

@ -7,7 +7,11 @@
"header": { "header": {
"header_base": "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", "header_base": "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"header_files": [ "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" "name": "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri"
@ -15,6 +19,7 @@
], ],
"module_list": [ "module_list": [
"//foundation/distributedschedule/dmsfwk/etc/init:etc", "//foundation/distributedschedule/dmsfwk/etc/init:etc",
"//foundation/distributedschedule/dmsfwk/etc/profile:distributedsched_trust",
"//foundation/distributedschedule/dmsfwk/sa_profile:dms_sa_profile", "//foundation/distributedschedule/dmsfwk/sa_profile:dms_sa_profile",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr" "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr"
], ],

View File

@ -30,14 +30,13 @@ config("distributed_sched_config") {
ohos_shared_library("distributedschedsvr") { ohos_shared_library("distributedschedsvr") {
install_enable = true install_enable = true
sources = [ sources = [
"src/ability_connection_wrapper_proxy.cpp",
"src/ability_connection_wrapper_stub.cpp", "src/ability_connection_wrapper_stub.cpp",
"src/adapter/dnetwork_adapter.cpp", "src/adapter/dnetwork_adapter.cpp",
"src/bundle/bundle_manager_internal.cpp", "src/bundle/bundle_manager_internal.cpp",
"src/connect_death_recipient.cpp", "src/connect_death_recipient.cpp",
"src/continuation_callback_death_recipient.cpp",
"src/deviceManager/dms_device_info.cpp", "src/deviceManager/dms_device_info.cpp",
"src/distributed_device_node_listener.cpp", "src/distributed_device_node_listener.cpp",
"src/distributed_sched_ability_shell.cpp",
"src/distributed_sched_adapter.cpp", "src/distributed_sched_adapter.cpp",
"src/distributed_sched_continuation.cpp", "src/distributed_sched_continuation.cpp",
"src/distributed_sched_dumper.cpp", "src/distributed_sched_dumper.cpp",
@ -46,6 +45,13 @@ ohos_shared_library("distributedschedsvr") {
"src/distributed_sched_service.cpp", "src/distributed_sched_service.cpp",
"src/distributed_sched_stub.cpp", "src/distributed_sched_stub.cpp",
"src/dtbschedmgr_device_info_storage.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" ] 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_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//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/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimedia/image_standard/interfaces/innerkits:image_native",
"//utils/native/base:utils", "//utils/native/base:utils",
] ]

View File

@ -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<AAFwk::IAbilityConnection> {
public:
explicit AbilityConnectionWrapperProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<AAFwk::IAbilityConnection>(impl) {}
virtual ~AbilityConnectionWrapperProxy() = default;
void OnAbilityConnectDone(const AppExecFwk::ElementName& element, const sptr<IRemoteObject>& remoteObject,
int32_t resultCode) override;
void OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, int32_t resultCode) override;
private:
static inline BrokerDelegator<AbilityConnectionWrapperProxy> delegator_;
};
} // namespace DistributedSchedule
} // namespace OHOS
#endif // OHOS_DISTRIBUTED_ABILITY_CONNECTION_WRAPPER_PROXY_H

View File

@ -26,11 +26,6 @@ namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
class AbilityConnectionWrapperStub : public IRemoteStub<AAFwk::IAbilityConnection> { class AbilityConnectionWrapperStub : public IRemoteStub<AAFwk::IAbilityConnection> {
public: public:
enum {
ON_ABILITY_CONNECT_DONE = 1,
ON_ABILITY_DISCONNECT_DONE = 2
};
explicit AbilityConnectionWrapperStub(sptr<IRemoteObject> connection); explicit AbilityConnectionWrapperStub(sptr<IRemoteObject> connection);
virtual ~AbilityConnectionWrapperStub() = default; virtual ~AbilityConnectionWrapperStub() = default;
@ -43,7 +38,6 @@ public:
private: private:
DISALLOW_COPY_AND_MOVE(AbilityConnectionWrapperStub); DISALLOW_COPY_AND_MOVE(AbilityConnectionWrapperStub);
sptr<IRemoteObject> distributedConnection_; sptr<IRemoteObject> distributedConnection_;
}; };
} // namespace DistributedSchedule } // namespace DistributedSchedule

View File

@ -1,29 +1,30 @@
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#include "continuation_callback_death_recipient.h" #ifndef OHOS_DISTRIBUTED_DMS_DFX_CONSTANT_H
#include "distributed_sched_ability_shell.h" #define OHOS_DISTRIBUTED_DMS_DFX_CONSTANT_H
#include "dtbschedmgr_log.h"
#include "iremote_proxy.h" namespace OHOS {
namespace DistributedSchedule {
namespace OHOS { namespace Constants {
namespace DistributedSchedule { namespace Adapter {
void ContinuationCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote) constexpr int32_t PARCELABLE_FLAG = 1;
{ constexpr int32_t VALUE_NULL = -1;
HILOGI("%s called", __func__); constexpr int32_t VALUE_OBJECT = 1;
DistributedSchedAbilityShell::GetInstance().RemoveContinuationCallback(remote.promote()); } // Adapter
} } // Constants
} // namespace DistributedSchedule } // DistributedSchedule
} // namespace OHOS } // OHOS
#endif

View File

@ -38,7 +38,7 @@ public:
virtual void OnDeviceOnline(const NodeBasicInfo* nodeBasicInfo) = 0; virtual void OnDeviceOnline(const NodeBasicInfo* nodeBasicInfo) = 0;
virtual void OnDeviceOffline(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 { class DnetworkAdapter {
@ -49,8 +49,8 @@ public:
void Init(); void Init();
bool AddDeviceChangeListener(const std::shared_ptr<DeviceListener>& listener); bool AddDeviceChangeListener(const std::shared_ptr<DeviceListener>& listener);
void RemoveDeviceChangeListener(const std::shared_ptr<DeviceListener>& listener); void RemoveDeviceChangeListener(const std::shared_ptr<DeviceListener>& listener);
std::string GetUdidByNodeId(const std::string& nodeId); std::string GetUdidByNetworkId(const std::string& networkId);
std::string GetUuidByNodeId(const std::string& nodeId); std::string GetUuidByNetworkId(const std::string& networkId);
std::shared_ptr<NodeBasicInfo> GetLocalBasicInfo(); std::shared_ptr<NodeBasicInfo> GetLocalBasicInfo();
static std::string AnonymizeDeviceId(const std::string& deviceId); static std::string AnonymizeDeviceId(const std::string& deviceId);
@ -59,7 +59,7 @@ public:
private: private:
DISALLOW_COPY_AND_MOVE(DnetworkAdapter); 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 OnNodeOnline(NodeBasicInfo* info);
static void OnNodeOffline(NodeBasicInfo* info); static void OnNodeOffline(NodeBasicInfo* info);
static void OnNodeBasicInfoChanged(NodeBasicInfoType type, NodeBasicInfo* info); static void OnNodeBasicInfoChanged(NodeBasicInfoType type, NodeBasicInfo* info);

View File

@ -23,6 +23,10 @@ enum {
CALLER_TYPE_HARMONY = 1, CALLER_TYPE_HARMONY = 1,
}; };
enum {
VERSION_BASE = 200, // begin for 200 and step for 200
VERSION = VERSION_BASE,
};
struct CallerInfo { struct CallerInfo {
int32_t uid = -1; int32_t uid = -1;
int32_t pid = -1; int32_t pid = -1;
@ -31,6 +35,7 @@ struct CallerInfo {
int32_t duid = -1; int32_t duid = -1;
std::string callerAppId; std::string callerAppId;
std::vector<std::string> bundleNames; std::vector<std::string> bundleNames;
int32_t dmsVersion = -1;
}; };
} // namespace DistributedSchedule } // namespace DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -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 <list>
#include <map>
#include <mutex>
#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<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback);
int32_t UnregisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback);
sptr<IRemoteObject> GetContinuationCallback(const sptr<IRemoteObject>& abilityToken);
int32_t ScheduleCompleteContinuation(const sptr<IRemoteObject>& abilityToken, int32_t isSuccess);
void RemoveContinuationCallback(const sptr<IRemoteObject>& continuationCallback);
private:
DistributedSchedAbilityShell();
~DistributedSchedAbilityShell() = default;
std::map<sptr<IRemoteObject>, std::list<sptr<IRemoteObject>>> regAbilityMap_;
std::mutex regAbilityLock_;
sptr<IRemoteObject::DeathRecipient> death_;
};
} // namespace DistributedSchedule
} // namespace OHOS
#endif // OHOS_DISTRIBUTED_SCHED_ABILITY_SHELL_H

View File

@ -22,6 +22,7 @@
#include "event_handler.h" #include "event_handler.h"
#include "if_system_ability_manager.h" #include "if_system_ability_manager.h"
#include "iremote_object.h" #include "iremote_object.h"
#include "mission/mission_info.h"
#include "single_instance.h" #include "single_instance.h"
#include "uri.h" #include "uri.h"
@ -42,8 +43,12 @@ public:
bool QueryAbilityInfo(const OHOS::AAFwk::Want& want, AppExecFwk::AbilityInfo& abilityInfo); bool QueryAbilityInfo(const OHOS::AAFwk::Want& want, AppExecFwk::AbilityInfo& abilityInfo);
void ProcessConnectDied(const sptr<IRemoteObject>& connect); void ProcessConnectDied(const sptr<IRemoteObject>& connect);
int32_t GetBundleNameListFromBms(int32_t uid, std::vector<std::u16string>& u16BundleNameList); int32_t GetBundleNameListFromBms(int32_t uid, std::vector<std::u16string>& u16BundleNameList);
int32_t GetLocalMissionInfos(int32_t numMissions, std::vector<MissionInfo>& missionInfos);
int32_t GetBundleNameListFromBms(int32_t uid, std::vector<std::string>& bundleNameList); int32_t GetBundleNameListFromBms(int32_t uid, std::vector<std::string>& bundleNameList);
bool AllowMissionUid(int32_t uid);
int32_t RegisterMissionChange(bool willRegister);
int32_t GetOsdSwitch();
void OnOsdEventOccur(int32_t flag);
private: private:
void ProcessDeviceOffline(const std::string& deviceId); void ProcessDeviceOffline(const std::string& deviceId);

View File

@ -16,9 +16,11 @@
#ifndef OHOS_DISTRIBUTED_SCHED_INTERFACE_H #ifndef OHOS_DISTRIBUTED_SCHED_INTERFACE_H
#define OHOS_DISTRIBUTED_SCHED_INTERFACE_H #define OHOS_DISTRIBUTED_SCHED_INTERFACE_H
#include <vector>
#include "ability_info.h" #include "ability_info.h"
#include "caller_info.h" #include "caller_info.h"
#include "iremote_broker.h" #include "iremote_broker.h"
#include "mission/mission_info.h"
#include "ohos/aafwk/content/want.h" #include "ohos/aafwk/content/want.h"
namespace OHOS { namespace OHOS {
@ -35,21 +37,16 @@ public:
std::vector<std::string> groupIdList; std::vector<std::string> groupIdList;
}; };
virtual int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, virtual int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) = 0;
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) = 0;
virtual int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, virtual int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo,
const AccountInfo& accountInfo) = 0; const AccountInfo& accountInfo) = 0;
virtual int32_t StartContinuation(const OHOS::AAFwk::Want& want, virtual int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr<IRemoteObject>& abilityToken,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& abilityToken) = 0; int32_t callerUid) = 0;
virtual void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) = 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 NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) = 0;
virtual int32_t RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken, virtual int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const sptr<IRemoteObject>& continuationCallback) = 0; const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid) = 0;
virtual int32_t UnregisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback) = 0;
virtual int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect) = 0;
virtual int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) = 0; virtual int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) = 0;
virtual int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, virtual int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) = 0; const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) = 0;
@ -57,6 +54,23 @@ public:
int32_t uid, const std::string& sourceDeviceId) = 0; int32_t uid, const std::string& sourceDeviceId) = 0;
virtual int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) = 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<IRemoteObject>& obj) = 0;
virtual int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr<IRemoteObject>& obj) = 0;
virtual int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions,
std::vector<MissionInfo>& 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<MissionInfo>& missionInfos,
const CallerInfo& callerInfo) = 0;
virtual int32_t CheckSupportOsd(const std::string& deviceId) = 0;
virtual void GetCachedOsdSwitch(std::vector<std::u16string>& deviceIds, std::vector<int32_t>& 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<MissionInfo>& missionInfos) = 0;
virtual int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) = 0;
enum { enum {
START_REMOTE_ABILITY = 1, START_REMOTE_ABILITY = 1,
STOP_REMOTE_ABILITY = 3, STOP_REMOTE_ABILITY = 3,
@ -74,6 +88,24 @@ public:
CONTINUE_ABILITY = 16, CONTINUE_ABILITY = 16,
NOTIFY_PROCESS_DIED_FROM_REMOTE = 17, NOTIFY_PROCESS_DIED_FROM_REMOTE = 17,
GET_REMOTE_APPTHREAD = 35, 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 } // namespace DistributedSchedule

View File

@ -26,29 +26,41 @@ public:
explicit DistributedSchedProxy(const sptr<IRemoteObject>& impl) explicit DistributedSchedProxy(const sptr<IRemoteObject>& impl)
: IRemoteProxy<IDistributedSched>(impl) {} : IRemoteProxy<IDistributedSched>(impl) {}
~DistributedSchedProxy() {} ~DistributedSchedProxy() {}
int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) override;
int32_t requestCode) override;
int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo,
const AccountInfo& accountInfo) override; const AccountInfo& accountInfo) override;
int32_t StartContinuation(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& abilityToken) override; int32_t callerUid) override;
void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override; void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override;
int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override; int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override;
int32_t RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken, int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const sptr<IRemoteObject>& continuationCallback) override; const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid) override;
int32_t UnregisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback) override;
int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect) override;
int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) override; int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) override;
int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override;
int32_t DisconnectAbilityFromRemote(const sptr<IRemoteObject>& connect, int32_t DisconnectAbilityFromRemote(const sptr<IRemoteObject>& connect,
int32_t uid, const std::string& sourceDeviceId) override; int32_t uid, const std::string& sourceDeviceId) override;
int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) 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<IRemoteObject>& obj) override;
int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr<IRemoteObject>& obj) override;
int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions,
std::vector<MissionInfo>& 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<MissionInfo>& missionInfos,
const CallerInfo& callerInfo) override;
int32_t CheckSupportOsd(const std::string& deviceId) override;
void GetCachedOsdSwitch(std::vector<std::u16string>& deviceIds, std::vector<int32_t>& 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<MissionInfo>& missionInfos) override;
int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) override;
private: private:
bool CallerInfoMarshalling(const CallerInfo& callerInfo, MessageParcel& data);
static inline BrokerDelegator<DistributedSchedProxy> delegator_; static inline BrokerDelegator<DistributedSchedProxy> delegator_;
}; };
} // namespace DistributedSchedule } // namespace DistributedSchedule

View File

@ -25,6 +25,7 @@
#include "distributed_sched_continuation.h" #include "distributed_sched_continuation.h"
#include "iremote_object.h" #include "iremote_object.h"
#include "iremote_proxy.h" #include "iremote_proxy.h"
#include "mission/mission_info.h"
#include "nocopyable.h" #include "nocopyable.h"
#include "single_instance.h" #include "single_instance.h"
#include "system_ability.h" #include "system_ability.h"
@ -56,34 +57,46 @@ public:
~DistributedSchedService() = default; ~DistributedSchedService() = default;
void OnStart() override; void OnStart() override;
void OnStop() override; void OnStop() override;
int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) override;
int32_t requestCode) override;
int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo,
const AccountInfo& accountInfo) override; const AccountInfo& accountInfo) override;
int32_t StartContinuation(const OHOS::AAFwk::Want& want, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& abilityToken) override; int32_t callerUid) override;
void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override; void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override;
int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override; int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override;
int32_t RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken, int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const sptr<IRemoteObject>& continuationCallback) override; const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid) override;
int32_t UnregisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback) override;
int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect) override;
int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) override; int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) override;
int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override;
int32_t DisconnectAbilityFromRemote(const sptr<IRemoteObject>& connect, int32_t DisconnectAbilityFromRemote(const sptr<IRemoteObject>& connect,
int32_t uid, const std::string& sourceDeviceId) override; int32_t uid, const std::string& sourceDeviceId) override;
int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) override; int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) override;
int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions,
std::vector<MissionInfo>& 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<MissionInfo>& missionInfos,
const CallerInfo& callerInfo) override;
void ProcessConnectDied(const sptr<IRemoteObject>& connect); void ProcessConnectDied(const sptr<IRemoteObject>& connect);
void ProcessDeviceOffline(const std::string& deviceId); void ProcessDeviceOffline(const std::string& deviceId);
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override; int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
void DumpConnectInfo(std::string& info); void DumpConnectInfo(std::string& info);
void DumpSessionsLocked(const std::list<ConnectAbilitySession>& sessionsList, std::string& info); void DumpSessionsLocked(const std::list<ConnectAbilitySession>& sessionsList, std::string& info);
void DumpElementLocked(const std::list<AppExecFwk::ElementName>& elementsList, std::string& info); void DumpElementLocked(const std::list<AppExecFwk::ElementName>& elementsList, std::string& info);
int32_t CheckSupportOsd(const std::string& deviceId) override;
void GetCachedOsdSwitch(std::vector<std::u16string>& deviceIds, std::vector<int32_t>& values) override;
int32_t GetOsdSwitchValueFromRemote() override;
int32_t UpdateOsdSwitchValueFromRemote(int32_t switchVal, const std::string& sourceDeviceId) override;
std::unique_ptr<Snapshot> GetRemoteSnapshotInfo(const std::u16string& deviceId, int32_t missionId) override;
int32_t RegisterRemoteMissionListener(const std::u16string& devId, const sptr<IRemoteObject>& obj) override;
int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr<IRemoteObject>& obj) override;
int32_t PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo,
std::vector<MissionInfo>& missionInfos) override;
int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) override;
int32_t PrepareAndSyncMissions(const std::u16string& devId, bool fixConflict, int64_t tag) override;
private: private:
DistributedSchedService(); DistributedSchedService();
bool Init(); bool Init();
@ -105,7 +118,7 @@ private:
int32_t CheckDistributedConnectLocked(const CallerInfo& callerInfo) const; int32_t CheckDistributedConnectLocked(const CallerInfo& callerInfo) const;
void DecreaseConnectLocked(int32_t uid); void DecreaseConnectLocked(int32_t uid);
static int32_t GetUidLocked(const std::list<ConnectAbilitySession>& sessionList); static int32_t GetUidLocked(const std::list<ConnectAbilitySession>& sessionList);
int32_t TryConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, int32_t TryConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo); const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo);
std::shared_ptr<DSchedContinuation> dschedContinuation_; std::shared_ptr<DSchedContinuation> dschedContinuation_;

View File

@ -18,6 +18,7 @@
#include "distributed_sched_interface.h" #include "distributed_sched_interface.h"
#include "iremote_stub.h" #include "iremote_stub.h"
#include "mission/snapshot.h"
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
@ -27,6 +28,11 @@ public:
~DistributedSchedStub(); ~DistributedSchedStub();
int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, int32_t OnRemoteRequest(uint32_t code, MessageParcel& data,
MessageParcel& reply, MessageOption& option) override; MessageParcel& reply, MessageOption& option) override;
protected:
virtual std::unique_ptr<Snapshot> GetRemoteSnapshotInfo(const std::u16string& deviceId, int32_t missionId)
{
return nullptr;
}
private: private:
int32_t StartRemoteAbilityInner(MessageParcel& data, MessageParcel& reply); int32_t StartRemoteAbilityInner(MessageParcel& data, MessageParcel& reply);
@ -34,17 +40,32 @@ private:
int32_t StartContinuationInner(MessageParcel& data, MessageParcel& reply); int32_t StartContinuationInner(MessageParcel& data, MessageParcel& reply);
int32_t NotifyCompleteContinuationInner(MessageParcel& data, MessageParcel& reply); int32_t NotifyCompleteContinuationInner(MessageParcel& data, MessageParcel& reply);
int32_t NotifyContinuationResultFromRemoteInner(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(); bool CheckDmsRequestPermission();
int32_t ConnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply); int32_t ConnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply);
int32_t DisconnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply); int32_t DisconnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply);
int32_t ConnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply); int32_t ConnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply);
int32_t DisconnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply); int32_t DisconnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply);
int32_t NotifyProcessDiedFromRemoteInner(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(); bool CheckCallingUid();
int32_t NotifyOsdSwitchChangedInner(MessageParcel& data, MessageParcel& reply);
int32_t UpdateOsdSwitchValueFromRemoteInner(MessageParcel& data, MessageParcel& reply);
bool EnforceInterfaceToken(MessageParcel& data); bool EnforceInterfaceToken(MessageParcel& data);
bool CallerInfoUnmarshalling(CallerInfo& callerInfo, MessageParcel& data);
using DistributedSchedFunc = int32_t(DistributedSchedStub::*)(MessageParcel& data, MessageParcel& reply); using DistributedSchedFunc = int32_t(DistributedSchedStub::*)(MessageParcel& data, MessageParcel& reply);
std::map<uint32_t, DistributedSchedFunc> remoteFuncsMap_; std::map<uint32_t, DistributedSchedFunc> remoteFuncsMap_;
std::map<uint32_t, DistributedSchedFunc> localFuncsMap_; std::map<uint32_t, DistributedSchedFunc> localFuncsMap_;

View File

@ -16,6 +16,8 @@
#ifndef OHOS_DISTRIBUTED_DTBSCHEDMGR_DEVICE_INFO_INTERFACE_H #ifndef OHOS_DISTRIBUTED_DTBSCHEDMGR_DEVICE_INFO_INTERFACE_H
#define OHOS_DISTRIBUTED_DTBSCHEDMGR_DEVICE_INFO_INTERFACE_H #define OHOS_DISTRIBUTED_DTBSCHEDMGR_DEVICE_INFO_INTERFACE_H
#include <set>
#include "adapter/dnetwork_adapter.h" #include "adapter/dnetwork_adapter.h"
#include "deviceManager/dms_device_info.h" #include "deviceManager/dms_device_info.h"
#include "distributed_device_node_listener.h" #include "distributed_device_node_listener.h"
@ -42,17 +44,52 @@ public:
void DeviceOnlineNotify(const std::shared_ptr<DmsDeviceInfo> devInfo); void DeviceOnlineNotify(const std::shared_ptr<DmsDeviceInfo> devInfo);
void DeviceOfflineNotify(const std::string& deviceId); void DeviceOfflineNotify(const std::string& deviceId);
void OnDeviceInfoChanged(const std::string& deviceId, DeviceInfoType type); 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<DmsDeviceInfo>
*/
std::shared_ptr<DmsDeviceInfo> 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<std::string>& deviceIdSet);
private: private:
bool InitNodeIdManager(std::shared_ptr<DnetworkAdapter> dnetworkAdapter); bool InitNetworkIdManager(std::shared_ptr<DnetworkAdapter> dnetworkAdapter);
bool ConnectSoftbus(); bool ConnectSoftbus();
void ClearAllDevices();
bool WaitForDnetworkReady(); bool WaitForDnetworkReady();
bool GetLocalDeviceFromDnet(std::string& deviceId); bool GetLocalDeviceFromDnet(std::string& deviceId);
void RegisterUuidNetworkIdMap(const std::string& networkId);
std::shared_ptr<AppExecFwk::EventHandler> initHandler_; void UnregisterUuidNetworkIdMap(const std::string& networkId);
std::shared_ptr<AppExecFwk::EventHandler> nodeIdMgrHandler_; std::mutex deviceLock_;
std::shared_ptr<DistributedDeviceNodeListener> deviceNodeListener_; std::shared_ptr<DistributedDeviceNodeListener> deviceNodeListener_;
std::map<std::string, std::shared_ptr<DmsDeviceInfo>> remoteDevices_;
std::string deviceId_;
std::map<std::string, std::string> uuidNetworkIdMap_;
std::mutex uuidNetworkIdLock_;
std::shared_ptr<AppExecFwk::EventHandler> initHandler_;
std::shared_ptr<AppExecFwk::EventHandler> networkIdMgrHandler_;
}; };
} // namespace DistributedSchedule } // namespace DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -44,11 +44,14 @@ static constexpr OHOS::HiviewDFX::HiLogLabel DSCHED_SERVICE_LABEL = {LOG_CORE, 0
#undef HILOGI #undef HILOGI
#endif #endif
#define HILOGD(...) (void)OHOS::HiviewDFX::HiLog::Debug(DSCHED_SERVICE_LABEL, __VA_ARGS__) #define DMS_LOG(level, fmt, ...) HiviewDFX::HiLog::level(DSCHED_SERVICE_LABEL, \
#define HILOGE(...) (void)OHOS::HiviewDFX::HiLog::Error(DSCHED_SERVICE_LABEL, __VA_ARGS__) "%{public}s::%{public}s " fmt, TAG.c_str(), __FUNCTION__, ##__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 HILOGF(fmt, ...) DMS_LOG(Fatal, fmt, ##__VA_ARGS__)
#define HILOGW(...) (void)OHOS::HiviewDFX::HiLog::Warn(DSCHED_SERVICE_LABEL, __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 { enum {
/** /**
@ -206,9 +209,9 @@ enum {
*/ */
SEND_REQUEST_DEF_FAIL = 29360163, 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. * Result(29360165) for DMS can not register device state callback.
*/ */
@ -218,9 +221,9 @@ enum {
*/ */
UNREGISTER_DEVICE_STATE_CALLBACK_ERR = 29360166, 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. * Result(29360168) for DMS can not get dmsproxy handle.
*/ */
@ -264,47 +267,63 @@ enum {
/** /**
* Result(29360178) for osd function not support. * Result(29360178) for osd function not support.
*/ */
TASK_OSD_NOT_SUPPORTED = 29360178, MISSION_OSD_NOT_SUPPORTED = 29360178,
/** /**
* Result(29360179) for osd switch is off. * Result(29360179) for osd switch is off.
*/ */
TASK_OSD_NOT_ENABLED = 29360179, MISSION_OSD_NOT_ENABLED = 29360179,
/** /**
* Result(29360180) for osd switch is on. * Result(29360180) for osd switch is on.
*/ */
TASK_OSD_ENABLED = 29360180, MISSION_OSD_ENABLED = 29360180,
/** /**
* Result(29360181) for front app check failed. * Result(29360181) for front app check failed.
*/ */
CHECK_FRONT_APP_FAIL = 29360181, CHECK_FRONT_APP_FAIL = 29360181,
/** /*
* Result(29360182) for ble connected. * Result(29360184) for notify mission change listener failed.
*/ */
BLE_CONNECTED = 29360182, MISSION_NOTIFY_CHANGE_LISTENER_ERR = 29360184,
/**
* Result(29360183) for open p2p session failed.
*/
OPENP2PSESSION_FAILED = 29360183,
/**
* Result(29360184) for notify task change listener failed.
*/
TASK_NOTIFY_CHANGE_LISTENER_ERR = 29360184,
/** /**
* Result(29360185) for subscribe data storage change failed. * 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. * 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. * 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 DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -1,32 +1,34 @@
/* /*
* Copyright (c) 2021 Huawei Device Co., Ltd. * Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
#ifndef OHOS_DISTRIBUTED_CONTINUATION_CALLBACK_DEATH_RECIPIENT_H #ifndef DISTRIBUTED_DATA_CHANGE_LISTENER_H
#define OHOS_DISTRIBUTED_CONTINUATION_CALLBACK_DEATH_RECIPIENT_H #define DISTRIBUTED_DATA_CHANGE_LISTENER_H
#include "iremote_object.h" #include "kvstore_observer.h"
#include "change_notification.h"
namespace OHOS {
namespace DistributedSchedule { namespace OHOS {
class ContinuationCallbackDeathRecipient : public IRemoteObject::DeathRecipient { namespace DistributedSchedule {
public: class DistributedDataChangeListener : public DistributedKv::KvStoreObserver {
void OnRemoteDied(const wptr<IRemoteObject> &remote) override; public:
ContinuationCallbackDeathRecipient() = default; DistributedDataChangeListener() = default;
~ContinuationCallbackDeathRecipient() override = default; ~DistributedDataChangeListener() override = default;
};
} // namespace DistributedSchedule void OnChange(const DistributedKv::ChangeNotification &appChangeNotification) override;
} // namespace OHOS };
} // DistributedSchedule
#endif // OHOS_DISTRIBUTED_CONTINUATION_CALLBACK_DEATH_RECIPIENT_H } // OHOS
#endif // DISTRIBUTED_DATA_CHANGE_LISTENER_H

View File

@ -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 <atomic>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <set>
#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<std::string>& deviceVec, const DistributedKv::SyncMode& mode,
uint32_t syncCount);
void RetrySync(const std::vector<std::string>& 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<AppExecFwk::EventHandler> dmsDataStorageHandler_;
std::shared_ptr<DistributedKv::DistributedKvDataManager> appDataMgr_; // protected by initLock_
std::unique_ptr<DistributedKv::KvStore> appKvStorePtr_; // protected by initLock_
std::unique_ptr<DistributedDataChangeListener> appDistributedDataChangeListener_;
};
} // DistributedSchedule
} // OHOS
#endif // DISTRIBUTED_DATA_STORAGE_H

View File

@ -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 <set>
#include <string>
#include <vector>
#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<sptr<IRemoteObject>> listenerSet;
bool Emplace(sptr<IRemoteObject> listener)
{
auto pairRet = listenerSet.emplace(listener);
if (!pairRet.second) {
return false;
}
return true;
}
bool Find(sptr<IRemoteObject> listener)
{
auto iter = listenerSet.find(listener);
if (iter == listenerSet.end()) {
return false;
}
return true;
}
void Erase(sptr<IRemoteObject> 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<MissionInfo>& 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<Snapshot> 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<IRemoteObject>& obj);
int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr<IRemoteObject>& obj);
int32_t PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo, std::vector<MissionInfo>& 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<IRemoteObject>& remote);
void EnqueueCachedSnapshotInfo(const std::string& deviceId, int32_t missionId, std::unique_ptr<Snapshot> snapshot);
std::unique_ptr<Snapshot> DequeueCachedSnapshotInfo(const std::string& deviceId, int32_t missionId);
int32_t NotifyMissionsChangedToRemote(const std::vector<MissionInfo>& missionInfos);
int32_t NotifyMissionsChangedFromRemote(const CallerInfo& callerInfo, const std::vector<MissionInfo>& missionInfos);
int32_t CheckSupportOsd(const std::string& deviceId);
int32_t CheckOsdSwitch(const std::string& deviceId);
void GetCachedOsdSwitch(std::vector<std::u16string>& deviceIds, std::vector<int32_t>& 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<IRemoteObject>& remote);
void NotifyDmsProxyProcessDied();
void OnDnetDied();
private:
std::map<std::string, std::shared_ptr<AppExecFwk::EventHandler>> deviceHandle_;
mutable std::mutex remoteMissionInfosLock_;
std::map<std::string, std::vector<MissionInfo>> deviceMissionInfos_;
sptr<IDistributedSched> GetRemoteDms(const std::string& deviceId);
bool IsDeviceIdValidated(const std::string& deviceId);
std::shared_ptr<AppExecFwk::EventHandler> FetchDeviceHandler(const std::string& deviceId);
bool GenerateCallerInfo(CallerInfo& callerInfo);
void NotifyMissionsChangedToRemoteInner(const std::string& remoteUuid,
const std::vector<MissionInfo>& 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<IDistributedSched>& 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<MissionInfo>& missionInfos);
void RebornMissionCache(const std::string& deviceId, const std::vector<MissionInfo>& missionInfos);
void CleanMissionCache(const std::string& deviceId);
void UpdateSwitchValueToRemoteInner(std::set<std::string>& 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<IRemoteObject>& remote);
void OnRemoteDmsDied(const sptr<IRemoteObject>& remote);
void RetryRegisterMissionChange(int32_t retryTimes);
class ListenerDeathRecipient : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject>& remote) override;
};
sptr<ListenerDeathRecipient> listenerDeath_;
std::set<std::string> remoteSyncDeviceSet_;
std::mutex remoteSyncDeviceLock_;
std::map<std::string, std::unique_ptr<Snapshot>> cachedSnapshotInfos_;
std::map<std::u16string, ListenerInfo> listenDeviceMap_;
std::mutex listenDeviceLock_;
std::shared_ptr<DistributedDataStorage> distributedDataStorage_;
std::set<int32_t> allowMissionUids_;
std::mutex allowMissionUidsLock_;
bool isRegMissionChange_ = false;
class RemoteDmsDeathRecipient : public IRemoteObject::DeathRecipient {
public:
void OnRemoteDied(const wptr<IRemoteObject>& remote) override;
};
sptr<RemoteDmsDeathRecipient> remoteDmsRecipient_;
std::map<std::string, sptr<IDistributedSched>> remoteDmsMap_;
std::mutex remoteDmsLock_;
std::shared_ptr<AppExecFwk::EventHandler> missionHandler_;
std::shared_ptr<AppExecFwk::EventHandler> updateHandler_;
std::mutex osdSwitchLock_;
std::map<std::string, int32_t> osdSwitchValueMap_; // key is uuid
std::map<std::string, bool> connCapSupportOsdMap_; // key is networkId
};
}
}
#endif // DISTRIBUTEDSCHED_MISSION_MANAGER_H

View File

@ -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 <list>
#include "iremote_broker.h"
#include "mission/snapshot.h"
namespace OHOS {
namespace DistributedSchedule {
class MissionChangedNotify {
public:
static void NotifySnapshot(const sptr<IRemoteObject>& remoteObject, const std::u16string& deviceId,
int32_t missionId);
static void NotifyMissionsChanged(const sptr<IRemoteObject>& remoteObject, const std::u16string& deviceId);
static void NotifyNetDisconnect(const sptr<IRemoteObject>& remoteObject, const std::u16string& deviceId,
int32_t state);
static void NotifyOsdSwitchChanged(const sptr<IRemoteObject>& remoteObject, const std::u16string& deviceId,
bool isSwitchOn);
};
} // namespace DistributedSchedule
} // namespace OHOS
#endif /* SERVICES_DTBSCHEDMGR_INCLUDE_IMISSION_CHANGED_LISTENER_H */

View File

@ -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

View File

@ -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 <string>
#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<int32_t> combinedMissionIds;
int32_t windowMode = 0;
int32_t boundsLeft = 0;
int32_t boundsTop = 0;
int32_t boundsRight = 0;
int32_t boundsBottom = 0;
std::shared_ptr<AAFwk::Want> baseWant;
std::shared_ptr<AppExecFwk::ElementName> topAbility;
std::shared_ptr<AppExecFwk::ElementName> baseAbility;
std::shared_ptr<AppExecFwk::ElementName> 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<MissionInfo> &missionInfos);
static bool WriteMissionInfoVectorFromParcel(Parcel& parcel, const std::vector<MissionInfo> &missionInfos);
};
} // namespace DistributedSchedule
} // namespace OHOS
#endif // OHOS_DISTRIBUTED_MISSION_INFO_H

View File

@ -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 <string>
#include <vector>
#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<AbilityMissionInfo>& abilityMissionInfos,
std::vector<MissionInfo>& missionInfos);
static int32_t ConvertToAbilityMissionInfos(std::vector<MissionInfo>& missionInfos,
std::vector<AbilityMissionInfo>& abilityMissionInfos);
};
}
}
#endif // DISTRIBUTEDSCHED_MISSION_INFO_CONVERTER_H

View File

@ -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 <memory>
#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<Snapshot> Create(const std::vector<uint8_t>& data);
int64_t GetCreatedTime() const;
int64_t GetLastAccessTime() const;
void UpdateLastAccessTime(int64_t accessTime);
private:
static std::unique_ptr<Media::PixelMap> CreatePixelMap(const uint8_t* buffer, uint32_t bufferSize);
static std::unique_ptr<Snapshot> FillSnapShot(MessageParcel& data);
std::unique_ptr<Media::PixelMap> pixelMap_;
int32_t orientation_ = 0;
std::unique_ptr<Rect> 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<Rect> windowBounds_;
std::u16string applicationLabel_;
std::u16string activityLabel_;
std::vector<uint8_t> icon_;
std::u16string secApplicationLabel_;
std::u16string secActivityLabel_;
std::vector<uint8_t> 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 */

0
services/dtbschedmgr/include/parcel_helper.h Executable file → Normal file
View File

View File

@ -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<IRemoteObject>& 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

View File

@ -15,17 +15,15 @@
#include "ability_connection_wrapper_stub.h" #include "ability_connection_wrapper_stub.h"
#include "ability_connection_wrapper_proxy.h"
#include "dtbschedmgr_log.h" #include "dtbschedmgr_log.h"
#include "ipc_object_proxy.h"
#include "ipc_types.h" #include "ipc_types.h"
#include "parcel_helper.h"
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
using namespace AAFwk; using namespace AAFwk;
namespace { namespace {
const std::u16string CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.abilityshell.DistributedConnection"; const std::string TAG = "AbilityConnectionWrapperStub";
} }
AbilityConnectionWrapperStub::AbilityConnectionWrapperStub(sptr<IRemoteObject> connection) AbilityConnectionWrapperStub::AbilityConnectionWrapperStub(sptr<IRemoteObject> connection)
@ -52,7 +50,7 @@ int32_t AbilityConnectionWrapperStub::OnRemoteRequest(uint32_t code, MessageParc
int32_t resultCode = ERR_NONE; int32_t resultCode = ERR_NONE;
switch (code) { switch (code) {
case IAbilityConnection::ON_ABILITY_CONNECT_DONE: { case IAbilityConnection::ON_ABILITY_CONNECT_DONE: {
if (auto remoteObject = data.ReadParcelable<IRemoteObject>()) { if (auto remoteObject = data.ReadRemoteObject()) {
resultCode = data.ReadInt32(); resultCode = data.ReadInt32();
OnAbilityConnectDone(*element, remoteObject, resultCode); OnAbilityConnectDone(*element, remoteObject, resultCode);
return ERR_NONE; return ERR_NONE;
@ -75,35 +73,15 @@ int32_t AbilityConnectionWrapperStub::OnRemoteRequest(uint32_t code, MessageParc
void AbilityConnectionWrapperStub::OnAbilityConnectDone(const AppExecFwk::ElementName& element, void AbilityConnectionWrapperStub::OnAbilityConnectDone(const AppExecFwk::ElementName& element,
const sptr<IRemoteObject>& remoteObject, int32_t resultCode) const sptr<IRemoteObject>& remoteObject, int32_t resultCode)
{ {
HILOGD("AbilityConnectionWrapperStub::OnAbilityConnectDone called"); auto proxy = std::make_unique<AbilityConnectionWrapperProxy>(distributedConnection_);
MessageParcel data; proxy->OnAbilityConnectDone(element, remoteObject, resultCode);
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);
} }
void AbilityConnectionWrapperStub::OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, void AbilityConnectionWrapperStub::OnAbilityDisconnectDone(const AppExecFwk::ElementName& element,
int32_t resultCode) int32_t resultCode)
{ {
HILOGD("AbilityConnectionWrapperStub::OnAbilityDisconnectDone called"); auto proxy = std::make_unique<AbilityConnectionWrapperProxy>(distributedConnection_);
MessageParcel data; proxy->OnAbilityDisconnectDone(element, resultCode);
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);
} }
} // namespace DistributedSchedule } // namespace DistributedSchedule
} // namespace OHOS } // namespace OHOS

21
services/dtbschedmgr/src/adapter/dnetwork_adapter.cpp Executable file → Normal file
View File

@ -34,6 +34,7 @@ const std::string PKG_NAME = "DBinderBus_" + std::to_string(getpid());
constexpr int32_t NON_ANONYMIZED_LENGTH = 6; constexpr int32_t NON_ANONYMIZED_LENGTH = 6;
const std::string EMPTY_DEVICE_ID = ""; const std::string EMPTY_DEVICE_ID = "";
const std::string TAG = "DnetworkAdapter";
} }
std::shared_ptr<AppExecFwk::EventHandler> DnetworkAdapter::dnetworkHandler_; std::shared_ptr<AppExecFwk::EventHandler> DnetworkAdapter::dnetworkHandler_;
@ -106,7 +107,7 @@ bool DnetworkAdapter::AddDeviceChangeListener(const std::shared_ptr<DeviceListen
{ {
HILOGD("AddDeviceChangeListener called"); HILOGD("AddDeviceChangeListener called");
if (dnetworkHandler_ == nullptr) { if (dnetworkHandler_ == nullptr) {
HILOGE("DnetworkAdapter handler is null"); HILOGE("handler is null");
return false; return false;
} }
@ -121,7 +122,7 @@ bool DnetworkAdapter::AddDeviceChangeListener(const std::shared_ptr<DeviceListen
} }
auto registerTask = [this]() { auto registerTask = [this]() {
HILOGD("AddDeviceChangeListener register task..."); HILOGD("AddDeviceChangeListener register mission...");
int32_t retryTimes = 0; int32_t retryTimes = 0;
int32_t errCode = ERR_OK; int32_t errCode = ERR_OK;
while (retryTimes++ < RETRY_REGISTER_CALLBACK_TIMES) { while (retryTimes++ < RETRY_REGISTER_CALLBACK_TIMES) {
@ -167,30 +168,30 @@ std::shared_ptr<NodeBasicInfo> DnetworkAdapter::GetLocalBasicInfo()
auto info = std::make_shared<NodeBasicInfo>(); auto info = std::make_shared<NodeBasicInfo>();
int32_t errCode = GetLocalNodeDeviceInfo(PKG_NAME.c_str(), info.get()); int32_t errCode = GetLocalNodeDeviceInfo(PKG_NAME.c_str(), info.get());
if (errCode != ERR_OK) { if (errCode != ERR_OK) {
HILOGE("DnetworkAdapter::GetLocalBasicInfo errCode = %{public}d", errCode); HILOGE("GetLocalBasicInfo errCode = %{public}d", errCode);
return nullptr; return nullptr;
} }
return info; 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(); return std::string();
} }
char uuidOrUdid[DEVICE_ID_SIZE] = {0}; 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<uint8_t*>(uuidOrUdid), DEVICE_ID_SIZE); reinterpret_cast<uint8_t*>(uuidOrUdid), DEVICE_ID_SIZE);
return (ret == ERR_OK) ? std::string(uuidOrUdid) : std::string(); return (ret == ERR_OK) ? std::string(uuidOrUdid) : std::string();
} }

View File

@ -23,20 +23,22 @@
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
namespace {
const std::string TAG = "BundleManagerInternal";
}
IMPLEMENT_SINGLE_INSTANCE(BundleManagerInternal); IMPLEMENT_SINGLE_INSTANCE(BundleManagerInternal);
bool BundleManagerInternal::GetCallerAppIdFromBms(int32_t callingUid, std::string& appId) bool BundleManagerInternal::GetCallerAppIdFromBms(int32_t callingUid, std::string& appId)
{ {
std::vector<std::string> bundleNameList; std::vector<std::string> bundleNameList;
int32_t ret = DistributedSchedAdapter::GetInstance().GetBundleNameListFromBms(callingUid, bundleNameList); int32_t ret = DistributedSchedAdapter::GetInstance().GetBundleNameListFromBms(callingUid, bundleNameList);
if (ret != ERR_OK || bundleNameList.empty()) { if (ret != ERR_OK || bundleNameList.empty()) {
HILOGE("BundleManagerInternal::GetCallerAppIdFromBms error"); HILOGE("GetBundleNameListFromBms error");
return false; return false;
} }
auto bundleMgr = GetBundleManager(); auto bundleMgr = GetBundleManager();
if (bundleMgr == nullptr) { if (bundleMgr == nullptr) {
HILOGE("BundleManagerInternal::GetCallerAppIdFromBms failed to get bms"); HILOGE("failed to get bms");
return false; return false;
} }
@ -44,7 +46,7 @@ bool BundleManagerInternal::GetCallerAppIdFromBms(int32_t callingUid, std::strin
std::string identity = IPCSkeleton::ResetCallingIdentity(); std::string identity = IPCSkeleton::ResetCallingIdentity();
appId = bundleMgr->GetAppIdByBundleName(bundleNameList.front(), callingUid); appId = bundleMgr->GetAppIdByBundleName(bundleNameList.front(), callingUid);
IPCSkeleton::SetCallingIdentity(identity); IPCSkeleton::SetCallingIdentity(identity);
HILOGD("BundleManagerInternal::GetCallerAppIdFromBms appId:%s", appId.c_str()); HILOGD("appId:%s", appId.c_str());
return true; return true;
} }
@ -55,7 +57,7 @@ sptr<AppExecFwk::IBundleMgr> BundleManagerInternal::GetBundleManager()
return iface_cast<AppExecFwk::IBundleMgr>( return iface_cast<AppExecFwk::IBundleMgr>(
samgrClient->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID)); samgrClient->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID));
} else { } else {
HILOGE("DistributedSchedAdapter::GetBundleManager failed to get samgr"); HILOGE("failed to get samgr");
return nullptr; return nullptr;
} }
} }

5
services/dtbschedmgr/src/connect_death_recipient.cpp Executable file → Normal file
View File

@ -21,9 +21,12 @@
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
namespace {
const std::string TAG = "ConnectDeathRecipient";
}
void ConnectDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote) void ConnectDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{ {
HILOGI("ConnectDeathRecipient::OnRemoteDied called"); HILOGI("OnRemoteDied called");
DistributedSchedAdapter::GetInstance().ProcessConnectDied(remote.promote()); DistributedSchedAdapter::GetInstance().ProcessConnectDied(remote.promote());
} }
} // namespace DistributedSchedule } // namespace DistributedSchedule

View File

@ -21,6 +21,9 @@
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
namespace {
const std::string TAG = "DmsDeviceInfo";
}
const std::string& DmsDeviceInfo::GetDeviceName() const const std::string& DmsDeviceInfo::GetDeviceName() const
{ {
return deviceName_; return deviceName_;

View File

@ -21,10 +21,13 @@
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
namespace {
const std::string TAG = "DistributedDeviceNodeListener";
}
void DistributedDeviceNodeListener::OnDeviceOnline(const NodeBasicInfo* nodeBasicInfo) void DistributedDeviceNodeListener::OnDeviceOnline(const NodeBasicInfo* nodeBasicInfo)
{ {
if (nodeBasicInfo == nullptr) { if (nodeBasicInfo == nullptr) {
HILOGE("DistributedDeviceNodeListener::OnDeviceOnline null nodeBasicInfo"); HILOGE("OnDeviceOnline null nodeBasicInfo");
return; return;
} }
auto dmsDeviceInfo = std::make_shared<DmsDeviceInfo>( auto dmsDeviceInfo = std::make_shared<DmsDeviceInfo>(
@ -35,7 +38,7 @@ void DistributedDeviceNodeListener::OnDeviceOnline(const NodeBasicInfo* nodeBasi
void DistributedDeviceNodeListener::OnDeviceOffline(const NodeBasicInfo* nodeBasicInfo) void DistributedDeviceNodeListener::OnDeviceOffline(const NodeBasicInfo* nodeBasicInfo)
{ {
if (nodeBasicInfo == nullptr) { if (nodeBasicInfo == nullptr) {
HILOGE("DistributedDeviceNodeListener::OnDeviceOffline null nodeBasicInfo"); HILOGE("OnDeviceOffline null nodeBasicInfo");
return; return;
} }
DtbschedmgrDeviceInfoStorage::GetInstance().DeviceOfflineNotify(nodeBasicInfo->networkId); DtbschedmgrDeviceInfoStorage::GetInstance().DeviceOfflineNotify(nodeBasicInfo->networkId);

View File

@ -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<IRemoteObject::DeathRecipient>(new ContinuationCallbackDeathRecipient());
}
int32_t DistributedSchedAbilityShell::RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
if (abilityToken == nullptr || continuationCallback == nullptr) {
HILOGE("RegisterAbilityToken abilityToken or continuationCallback is null");
return INVALID_PARAMETERS_ERR;
}
std::lock_guard<std::mutex> 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<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
if (abilityToken == nullptr || continuationCallback == nullptr) {
HILOGE("UnregisterAbilityToken abilityToken or continuationCallback is null");
return INVALID_PARAMETERS_ERR;
}
std::lock_guard<std::mutex> autoLock(regAbilityLock_);
auto itAbility = regAbilityMap_.find(continuationCallback);
if (itAbility != regAbilityMap_.end()) {
std::list<sptr<IRemoteObject>>& 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<IRemoteObject> DistributedSchedAbilityShell::GetContinuationCallback(const sptr<IRemoteObject>& abilityToken)
{
if (abilityToken == nullptr) {
HILOGE("GetContinuationCallback abilityToken is null");
return nullptr;
}
std::lock_guard<std::mutex> autoLock(regAbilityLock_);
for (const auto& regAbility : regAbilityMap_) {
const std::list<sptr<IRemoteObject>>& tokenList = regAbility.second;
for (const auto& tokenItem : tokenList) {
if (tokenItem == abilityToken) {
// find abilityToken
return regAbility.first;
}
}
}
return nullptr;
}
void DistributedSchedAbilityShell::RemoveContinuationCallback(const sptr<IRemoteObject>& continuationCallback)
{
if (continuationCallback == nullptr) {
HILOGE("RemoveContinuationCallback continuationCallback is null");
return;
}
std::lock_guard<std::mutex> autoLock(regAbilityLock_);
continuationCallback->RemoveDeathRecipient(death_);
regAbilityMap_.erase(continuationCallback);
}
int32_t DistributedSchedAbilityShell::ScheduleCompleteContinuation(const sptr<IRemoteObject>& abilityToken,
int32_t isSuccess)
{
if (abilityToken == nullptr) {
HILOGE("ScheduleCompleteContinuation ability abilityToken is null");
return INVALID_PARAMETERS_ERR;
}
sptr<IRemoteObject> 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

61
services/dtbschedmgr/src/distributed_sched_adapter.cpp Executable file → Normal file
View File

@ -22,6 +22,8 @@
#include "ability_manager_client.h" #include "ability_manager_client.h"
#include "ipc_skeleton.h" #include "ipc_skeleton.h"
#include "ipc_types.h" #include "ipc_types.h"
#include "mission/distributed_sched_mission_manager.h"
#include "mission/mission_info_converter.h"
#include "parcel_helper.h" #include "parcel_helper.h"
#include "string_ex.h" #include "string_ex.h"
@ -34,6 +36,7 @@ using namespace AppExecFwk;
namespace { namespace {
// set a non-zero value on need later // set a non-zero value on need later
constexpr int64_t DEVICE_OFFLINE_DELAY_TIME = 0; constexpr int64_t DEVICE_OFFLINE_DELAY_TIME = 0;
const std::string TAG = "DistributedSchedAdapter";
} }
IMPLEMENT_SINGLE_INSTANCE(DistributedSchedAdapter); IMPLEMENT_SINGLE_INSTANCE(DistributedSchedAdapter);
@ -43,7 +46,7 @@ void DistributedSchedAdapter::Init()
if (dmsAdapterHandler_ == nullptr) { if (dmsAdapterHandler_ == nullptr) {
shared_ptr<EventRunner> runner = EventRunner::Create("dmsAdapter"); shared_ptr<EventRunner> runner = EventRunner::Create("dmsAdapter");
if (runner == nullptr) { if (runner == nullptr) {
HILOGE("DistributedSchedAdapter create runner failed"); HILOGE("create runner failed");
return; return;
} }
dmsAdapterHandler_ = make_shared<EventHandler>(runner); dmsAdapterHandler_ = make_shared<EventHandler>(runner);
@ -58,10 +61,10 @@ void DistributedSchedAdapter::UnInit()
int32_t DistributedSchedAdapter::ConnectAbility(const OHOS::AAFwk::Want& want, int32_t DistributedSchedAdapter::ConnectAbility(const OHOS::AAFwk::Want& want,
const sptr<IRemoteObject>& connect, const sptr<IRemoteObject>& callerToken) const sptr<IRemoteObject>& connect, const sptr<IRemoteObject>& callerToken)
{ {
HILOGD("DistributedSchedAdapter ConnectAbility"); HILOGD("ConnectAbility");
ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect();
if (errCode != ERR_OK) { 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; return errCode;
} }
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, 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<IRemoteObject>& connect) int32_t DistributedSchedAdapter::DisconnectAbility(const sptr<IRemoteObject>& connect)
{ {
HILOGD("DistributedSchedAdapter DisconnectAbility"); HILOGD("DisconnectAbility");
ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect();
if (errCode != ERR_OK) { 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; return errCode;
} }
ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility( ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(
@ -164,7 +167,7 @@ int32_t DistributedSchedAdapter::GetBundleNameListFromBms(int32_t uid,
vector<string> bundleNameList; vector<string> bundleNameList;
int32_t ret = GetBundleNameListFromBms(uid, bundleNameList); int32_t ret = GetBundleNameListFromBms(uid, bundleNameList);
if (ret != ERR_OK) { if (ret != ERR_OK) {
HILOGE("DistributedSchedAdapter::GetBundleNameListFromBms failed"); HILOGE("GetBundleNameListFromBms failed");
return ret; return ret;
} }
for (const string& bundleName : bundleNameList) { for (const string& bundleName : bundleNameList) {
@ -177,14 +180,54 @@ int32_t DistributedSchedAdapter::GetBundleNameListFromBms(int32_t uid, std::vect
{ {
auto bundleMgr = BundleManagerInternal::GetBundleManager(); auto bundleMgr = BundleManagerInternal::GetBundleManager();
if (bundleMgr == nullptr) { if (bundleMgr == nullptr) {
HILOGE("DistributedSchedAdapter::GetBundleNameListFromBms failed to get bms"); HILOGE("GetBundleNameListFromBms failed to get bms");
return OBJECT_NULL; return OBJECT_NULL;
} }
std::string identity = IPCSkeleton::ResetCallingIdentity(); std::string identity = IPCSkeleton::ResetCallingIdentity();
bool result = bundleMgr->GetBundlesForUid(uid, bundleNameList); bool result = bundleMgr->GetBundlesForUid(uid, bundleNameList);
IPCSkeleton::SetCallingIdentity(identity); IPCSkeleton::SetCallingIdentity(identity);
HILOGD("DistributedSchedAdapter::GetBundleNameListFromBms %{public}d", result); HILOGD("GetBundleNameListFromBms %{public}d", result);
return result ? ERR_OK : BUNDLE_MANAGER_SERVICE_ERR; return result ? ERR_OK : BUNDLE_MANAGER_SERVICE_ERR;
} }
int32_t DistributedSchedAdapter::GetLocalMissionInfos(int32_t numMissions, std::vector<MissionInfo>& missionInfos)
{
ErrCode errCode = AAFwk::AbilityManagerClient::GetInstance()->Connect();
if (errCode != ERR_OK) {
HILOGE("get ability server failed, errCode=%{public}d", errCode);
return errCode;
}
std::vector<AbilityMissionInfo> 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 DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -23,6 +23,7 @@ namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
namespace { namespace {
constexpr int64_t CONTINUATION_DELAY_TIME = 20000; constexpr int64_t CONTINUATION_DELAY_TIME = 20000;
const std::string TAG = "DSchedContinuation";
} }
void DSchedContinuation::Init(const FuncContinuationCallback& contCallback) void DSchedContinuation::Init(const FuncContinuationCallback& contCallback)
@ -34,17 +35,17 @@ void DSchedContinuation::Init(const FuncContinuationCallback& contCallback)
bool DSchedContinuation::PushAbilityToken(int32_t sessionId, const sptr<IRemoteObject>& abilityToken) bool DSchedContinuation::PushAbilityToken(int32_t sessionId, const sptr<IRemoteObject>& abilityToken)
{ {
if (abilityToken == nullptr) { if (abilityToken == nullptr) {
HILOGE("DSchedContinuation::PushAbilityToken abilityToken null!"); HILOGE("PushAbilityToken abilityToken null!");
return false; return false;
} }
if (sessionId <= 0) { if (sessionId <= 0) {
HILOGE("DSchedContinuation::PushAbilityToken sessionId invalid!"); HILOGE("PushAbilityToken sessionId invalid!");
return false; return false;
} }
if (continuationHandler_ == nullptr) { if (continuationHandler_ == nullptr) {
HILOGE("DSchedContinuation::PushAbilityToken not initialized!"); HILOGE("PushAbilityToken not initialized!");
return false; return false;
} }
@ -52,13 +53,13 @@ bool DSchedContinuation::PushAbilityToken(int32_t sessionId, const sptr<IRemoteO
bool ret = true; bool ret = true;
ret = continuationHandler_->SendEvent(sessionId, 0, CONTINUATION_DELAY_TIME); ret = continuationHandler_->SendEvent(sessionId, 0, CONTINUATION_DELAY_TIME);
if (!ret) { if (!ret) {
HILOGE("DSchedContinuation::PushAbilityToken SendEvent failed!"); HILOGE("PushAbilityToken SendEvent failed!");
return false; return false;
} }
auto iterSession = continuationMap_.find(sessionId); auto iterSession = continuationMap_.find(sessionId);
if (iterSession != continuationMap_.end()) { if (iterSession != continuationMap_.end()) {
HILOGE("DSchedContinuation::PushAbilityToken sessionId:%{public}d exist!", sessionId); HILOGE("PushAbilityToken sessionId:%{public}d exist!", sessionId);
return false; return false;
} }
(void)continuationMap_.emplace(sessionId, abilityToken); (void)continuationMap_.emplace(sessionId, abilityToken);
@ -68,14 +69,14 @@ bool DSchedContinuation::PushAbilityToken(int32_t sessionId, const sptr<IRemoteO
sptr<IRemoteObject> DSchedContinuation::PopAbilityToken(int32_t sessionId) sptr<IRemoteObject> DSchedContinuation::PopAbilityToken(int32_t sessionId)
{ {
if (sessionId <= 0) { if (sessionId <= 0) {
HILOGE("DSchedContinuation::PopAbilityToken sessionId invalid"); HILOGE("PopAbilityToken sessionId invalid");
return nullptr; return nullptr;
} }
lock_guard<mutex> autoLock(continuationLock_); lock_guard<mutex> autoLock(continuationLock_);
auto iter = continuationMap_.find(sessionId); auto iter = continuationMap_.find(sessionId);
if (iter == continuationMap_.end()) { if (iter == continuationMap_.end()) {
HILOGW("DSchedContinuation::PopAbilityToken not found sessionId:%{public}d", sessionId); HILOGW("PopAbilityToken not found sessionId:%{public}d", sessionId);
return nullptr; return nullptr;
} }
sptr<IRemoteObject> abilityToken = iter->second; sptr<IRemoteObject> abilityToken = iter->second;
@ -99,26 +100,26 @@ int32_t DSchedContinuation::GenerateSessionId()
void DSchedContinuation::ContinuationHandler::ProcessEvent(const InnerEvent::Pointer& event) void DSchedContinuation::ContinuationHandler::ProcessEvent(const InnerEvent::Pointer& event)
{ {
if (event == nullptr) { if (event == nullptr) {
HILOGE("ContinuationHandler::ProcessEvent event nullptr!"); HILOGE("ProcessEvent event nullptr!");
return; return;
} }
auto dSchedContinuation = continuationObj_.lock(); auto dSchedContinuation = continuationObj_.lock();
if (dSchedContinuation == nullptr) { if (dSchedContinuation == nullptr) {
HILOGE("ContinuationHandler::ProcessEvent continuation object failed!"); HILOGE("ProcessEvent continuation object failed!");
return; return;
} }
auto eventId = event->GetInnerEventId(); auto eventId = event->GetInnerEventId();
int32_t sessionId = static_cast<int32_t>(eventId); int32_t sessionId = static_cast<int32_t>(eventId);
if (sessionId <= 0) { if (sessionId <= 0) {
HILOGW("ContinuationHandler::ProcessEvent sessionId invalid!"); HILOGW("ProcessEvent sessionId invalid!");
return; return;
} }
auto abilityToken = dSchedContinuation->PopAbilityToken(sessionId); auto abilityToken = dSchedContinuation->PopAbilityToken(sessionId);
if (abilityToken == nullptr) { if (abilityToken == nullptr) {
HILOGW("ContinuationHandler::ProcessEvent abilityToken nullptr!"); HILOGW("ProcessEvent abilityToken nullptr!");
return; return;
} }

1
services/dtbschedmgr/src/distributed_sched_dumper.cpp Executable file → Normal file
View File

@ -25,6 +25,7 @@ namespace {
constexpr size_t MIN_ARGS_SIZE = 1; constexpr size_t MIN_ARGS_SIZE = 1;
const std::string ARGS_HELP = "-h"; const std::string ARGS_HELP = "-h";
const std::string ARGS_CONNECT_REMOTE_ABILITY = "-connect"; const std::string ARGS_CONNECT_REMOTE_ABILITY = "-connect";
const std::string TAG = "DistributedSchedDumper";
constexpr int32_t UID_ROOT = 0; constexpr int32_t UID_ROOT = 0;
} }

View File

@ -28,6 +28,7 @@ using namespace OHOS::Security;
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
namespace { namespace {
const std::string TAG = "DistributedSchedPermission";
constexpr int32_t ERROR_DUID = -1; constexpr int32_t ERROR_DUID = -1;
constexpr int32_t PERMISSION_GRANTED = 0; constexpr int32_t PERMISSION_GRANTED = 0;
} }
@ -39,13 +40,13 @@ bool DistributedSchedPermission::CheckCustomPermission(const AppExecFwk::Ability
{ {
const auto& permissions = abilityInfo.permissions; const auto& permissions = abilityInfo.permissions;
if (permissions.empty()) { if (permissions.empty()) {
HILOGI("CheckCustomPermission no need any permission, so granted!"); HILOGI("no need any permission, so granted!");
return true; return true;
} }
int32_t duid = callerInfo.duid; int32_t duid = callerInfo.duid;
if (callerInfo.callerType == CALLER_TYPE_HARMONY) { if (callerInfo.callerType == CALLER_TYPE_HARMONY) {
duid = AllocateDuid(callerInfo.uid, callerInfo.sourceDeviceId); 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) { if (duid < 0) {
HILOGE("CheckCustomPermission duid invalid!"); HILOGE("CheckCustomPermission duid invalid!");
@ -61,7 +62,7 @@ bool DistributedSchedPermission::CheckCustomPermission(const AppExecFwk::Ability
duid, permission.c_str()); duid, permission.c_str());
return true; 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()); duid, permission.c_str());
} }
return false; return false;
@ -76,7 +77,7 @@ int32_t DistributedSchedPermission::AllocateDuid(int32_t rUid, const std::string
int64_t begin = GetTickCount(); int64_t begin = GetTickCount();
auto duid = Permission::DistributedPermissionKit::AllocateDuid(deviceId, rUid); auto duid = Permission::DistributedPermissionKit::AllocateDuid(deviceId, rUid);
int64_t end = GetTickCount(); int64_t end = GetTickCount();
HILOGI("DistributedSchedPermission::AllocateDuid spend:%{public}" PRId64 " ms", (end - begin)); HILOGI("AllocateDuid spend:%{public}" PRId64 " ms", (end - begin));
return duid; return duid;
} }
@ -113,7 +114,7 @@ bool DistributedSchedPermission::getTargetAbility(const AAFwk::Want& want,
const AppExecFwk::AbilityInfo& abilityInfo, const std::string& localDeviceId, const AppExecFwk::AbilityInfo& abilityInfo, const std::string& localDeviceId,
AppExecFwk::AbilityInfo& targetAbility, const CallerInfo& callerInfo) const AppExecFwk::AbilityInfo& targetAbility, const CallerInfo& callerInfo) const
{ {
HILOGD("DistributedSchedPermission::getTargetAbility"); HILOGD("getTargetAbility");
bool result = DistributedSchedAdapter::GetInstance().QueryAbilityInfo(want, targetAbility); bool result = DistributedSchedAdapter::GetInstance().QueryAbilityInfo(want, targetAbility);
if (!result) { if (!result) {
HILOGE("getTargetAbility QueryAbilityInfo fail"); HILOGE("getTargetAbility QueryAbilityInfo fail");

View File

@ -27,11 +27,13 @@ using namespace std;
using namespace AAFwk; using namespace AAFwk;
namespace { namespace {
const std::string TAG = "DistributedSchedProxy";
const std::u16string DMS_PROXY_INTERFACE_TOKEN = u"ohos.distributedschedule.accessToken"; 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, int32_t DistributedSchedProxy::StartRemoteAbility(const OHOS::AAFwk::Want& want,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) int32_t callerUid, int32_t requestCode)
{ {
sptr<IRemoteObject> remote = Remote(); sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) { if (remote == nullptr) {
@ -42,7 +44,7 @@ int32_t DistributedSchedProxy::StartRemoteAbility(const OHOS::AAFwk::Want& want,
return ERR_FLATTEN_OBJECT; return ERR_FLATTEN_OBJECT;
} }
PARCEL_WRITE_HELPER(data, Parcelable, &want); PARCEL_WRITE_HELPER(data, Parcelable, &want);
PARCEL_WRITE_HELPER(data, Parcelable, &abilityInfo); PARCEL_WRITE_HELPER(data, Int32, callerUid);
PARCEL_WRITE_HELPER(data, Int32, requestCode); PARCEL_WRITE_HELPER(data, Int32, requestCode);
MessageParcel reply; MessageParcel reply;
PARCEL_TRANSACT_SYNC_RET_INT(remote, START_REMOTE_ABILITY, data, 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, int32_t DistributedSchedProxy::StartContinuation(const OHOS::AAFwk::Want& want,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& abilityToken) const sptr<IRemoteObject>& abilityToken, int32_t callerUid)
{ {
if (abilityToken == nullptr) { if (abilityToken == nullptr) {
HILOGE("StartContinuation abilityToken null!"); HILOGE("StartContinuation abilityToken null!");
@ -91,8 +93,8 @@ int32_t DistributedSchedProxy::StartContinuation(const OHOS::AAFwk::Want& want,
return ERR_FLATTEN_OBJECT; return ERR_FLATTEN_OBJECT;
} }
PARCEL_WRITE_HELPER(data, Parcelable, &want); PARCEL_WRITE_HELPER(data, Parcelable, &want);
PARCEL_WRITE_HELPER(data, Parcelable, &abilityInfo);
PARCEL_WRITE_HELPER(data, RemoteObject, abilityToken); PARCEL_WRITE_HELPER(data, RemoteObject, abilityToken);
PARCEL_WRITE_HELPER(data, Int32, callerUid);
MessageParcel reply; MessageParcel reply;
PARCEL_TRANSACT_SYNC_RET_INT(remote, START_CONTINUATION, data, 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); PARCEL_TRANSACT_SYNC_RET_INT(remote, NOTIFY_CONTINUATION_RESULT_FROM_REMOTE, data, reply);
} }
int32_t DistributedSchedProxy::RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
if (abilityToken == nullptr || continuationCallback == nullptr) {
HILOGE("RegisterAbilityToken paramter null!");
return ERR_NULL_OBJECT;
}
sptr<IRemoteObject> 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<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
if (abilityToken == nullptr || continuationCallback == nullptr) {
HILOGE("UnregisterAbilityToken paramter null!");
return ERR_NULL_OBJECT;
}
sptr<IRemoteObject> 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, int32_t DistributedSchedProxy::ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& connect) const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid)
{ {
if (connect == nullptr) { if (connect == nullptr) {
HILOGE("ConnectRemoteAbility connect is null"); HILOGE("ConnectRemoteAbility connect is null");
@ -194,8 +152,9 @@ int32_t DistributedSchedProxy::ConnectRemoteAbility(const OHOS::AAFwk::Want& wan
return ERR_FLATTEN_OBJECT; return ERR_FLATTEN_OBJECT;
} }
PARCEL_WRITE_HELPER(data, Parcelable, &want); PARCEL_WRITE_HELPER(data, Parcelable, &want);
PARCEL_WRITE_HELPER(data, Parcelable, &abilityInfo);
PARCEL_WRITE_HELPER(data, RemoteObject, connect); PARCEL_WRITE_HELPER(data, RemoteObject, connect);
PARCEL_WRITE_HELPER(data, Int32, callerUid);
PARCEL_WRITE_HELPER(data, Int32, callerPid);
MessageParcel reply; MessageParcel reply;
PARCEL_TRANSACT_SYNC_RET_INT(remote, CONNECT_REMOTE_ABILITY, data, 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; MessageParcel reply;
PARCEL_TRANSACT_SYNC_RET_INT(remote, NOTIFY_PROCESS_DIED_FROM_REMOTE, data, 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<IRemoteObject> 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<IRemoteObject>& obj)
{
return ERR_NONE;
}
int32_t DistributedSchedProxy::UnRegisterRemoteMissionListener(const std::u16string& devId,
const sptr<IRemoteObject>& obj)
{
return ERR_NONE;
}
int32_t DistributedSchedProxy::GetMissionInfos(const std::string& deviceId, int32_t numMissions,
std::vector<MissionInfo>& missionInfos)
{
HILOGI("called");
sptr<IRemoteObject> 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<MissionInfo>& missionInfos,
const CallerInfo& callerInfo)
{
HILOGI("NotifyMissionsChangedFromRemote is called");
sptr<IRemoteObject> 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<IRemoteObject> 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<std::u16string>& deviceIds, std::vector<int32_t>& values)
{
HILOGI("GetCachedOsdSwitch is called");
sptr<IRemoteObject> 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<IRemoteObject> 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<MissionInfo>& missionInfos)
{
HILOGI("called");
sptr<IRemoteObject> 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<IRemoteObject> 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<IRemoteObject> 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 DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -19,24 +19,24 @@
#include <unistd.h> #include <unistd.h>
#include "ability_connection_wrapper_stub.h" #include "ability_connection_wrapper_stub.h"
#include "ability_manager_client.h"
#include "adapter/dnetwork_adapter.h" #include "adapter/dnetwork_adapter.h"
#include "bundle/bundle_manager_internal.h" #include "bundle/bundle_manager_internal.h"
#include "connect_death_recipient.h" #include "connect_death_recipient.h"
#include "datetime_ex.h"
#include "distributed_sched_adapter.h" #include "distributed_sched_adapter.h"
#include "distributed_sched_ability_shell.h" #include "distributed_sched_dumper.h"
#include "distributed_sched_permission.h" #include "distributed_sched_permission.h"
#include "dtbschedmgr_device_info_storage.h" #include "dtbschedmgr_device_info_storage.h"
#include "dtbschedmgr_log.h" #include "dtbschedmgr_log.h"
#include "distributed_sched_dumper.h"
#include "ability_manager_client.h"
#include "datetime_ex.h"
#include "element_name.h" #include "element_name.h"
#include "file_ex.h"
#include "ipc_skeleton.h" #include "ipc_skeleton.h"
#include "iservice_registry.h" #include "iservice_registry.h"
#include "mission/distributed_sched_mission_manager.h"
#include "mission/mission_info.h"
#include "parcel_helper.h" #include "parcel_helper.h"
#include "string_ex.h" #include "string_ex.h"
#include "file_ex.h"
#include "system_ability_definition.h" #include "system_ability_definition.h"
namespace OHOS { namespace OHOS {
@ -45,8 +45,8 @@ using namespace AAFwk;
using namespace AppExecFwk; using namespace AppExecFwk;
namespace { namespace {
const std::string TAG = "DistributedSchedService";
const std::u16string CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.abilityshell.DistributedConnection"; const std::u16string CONNECTION_CALLBACK_INTERFACE_TOKEN = u"ohos.abilityshell.DistributedConnection";
constexpr int32_t BIND_CONNECT_RETRY_TIMES = 3; constexpr int32_t BIND_CONNECT_RETRY_TIMES = 3;
constexpr int32_t BIND_CONNECT_TIMEOUT = 500; // 500ms constexpr int32_t BIND_CONNECT_TIMEOUT = 500; // 500ms
constexpr int32_t MAX_DISTRIBUTED_CONNECT_NUM = 600; constexpr int32_t MAX_DISTRIBUTED_CONNECT_NUM = 600;
@ -74,23 +74,24 @@ void DistributedSchedService::OnStart()
}; };
dschedContinuation_ = std::make_shared<DSchedContinuation>(); dschedContinuation_ = std::make_shared<DSchedContinuation>();
dschedContinuation_->Init(continuationCallback); dschedContinuation_->Init(continuationCallback);
HILOGI("DistributedSchedService::OnStart start service success."); HILOGI("OnStart start service success.");
} }
bool DistributedSchedService::Init() bool DistributedSchedService::Init()
{ {
HILOGD("DistributedSchedService::Init ready to init."); HILOGD("Init ready to init.");
DistributedSchedMissionManager::GetInstance().Init();
bool ret = Publish(this); bool ret = Publish(this);
if (!ret) { if (!ret) {
HILOGE("DistributedSchedService::Init Publish failed!"); HILOGE("Init Publish failed!");
return false; return false;
} }
if (!DtbschedmgrDeviceInfoStorage::GetInstance().Init()) { 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(); DistributedSchedAdapter::GetInstance().Init();
DnetworkAdapter::GetInstance()->Init(); DnetworkAdapter::GetInstance()->Init();
connectDeathRecipient_ = sptr<IRemoteObject::DeathRecipient>(new ConnectDeathRecipient()); connectDeathRecipient_ = sptr<IRemoteObject::DeathRecipient>(new ConnectDeathRecipient());
@ -99,31 +100,35 @@ bool DistributedSchedService::Init()
void DistributedSchedService::OnStop() 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, 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 localDeviceId;
std::string deviceId = want.GetElement().GetDeviceID(); std::string deviceId = want.GetElement().GetDeviceID();
if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) { 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; return INVALID_PARAMETERS_ERR;
} }
sptr<IDistributedSched> remoteDms = GetRemoteDms(deviceId); sptr<IDistributedSched> remoteDms = GetRemoteDms(deviceId);
if (remoteDms == nullptr) { if (remoteDms == nullptr) {
HILOGE("StartRemoteAbility DMS get remoteDms failed"); HILOGE("get remoteDms failed");
return INVALID_PARAMETERS_ERR; return INVALID_PARAMETERS_ERR;
} }
AppExecFwk::AbilityInfo abilityInfo;
CallerInfo callerInfo; CallerInfo callerInfo;
callerInfo.uid = IPCSkeleton::GetCallingUid();
callerInfo.sourceDeviceId = localDeviceId; callerInfo.sourceDeviceId = localDeviceId;
callerInfo.callerType = CALLER_TYPE_HARMONY; callerInfo.uid = callerUid;
AccountInfo accountInfo; AccountInfo accountInfo;
HILOGI("[PerformanceTest] DistributedSchedService StartRemoteAbility transact begin"); HILOGI("[PerformanceTest] StartRemoteAbility transact begin");
int32_t result = remoteDms->StartAbilityFromRemote(want, abilityInfo, requestCode, callerInfo, accountInfo); int32_t result = remoteDms->StartAbilityFromRemote(want, abilityInfo, requestCode, callerInfo, accountInfo);
HILOGI("[PerformanceTest] DistributedSchedService StartRemoteAbility transact end"); HILOGI("[PerformanceTest] StartRemoteAbility transact end");
return result; return result;
} }
@ -135,31 +140,31 @@ int32_t DistributedSchedService::StartAbilityFromRemote(const OHOS::AAFwk::Want&
std::string deviceId = want.GetElement().GetDeviceID(); std::string deviceId = want.GetElement().GetDeviceID();
if (!GetLocalDeviceId(localDeviceId) || if (!GetLocalDeviceId(localDeviceId) ||
!CheckDeviceIdFromRemote(localDeviceId, deviceId, callerInfo.sourceDeviceId)) { !CheckDeviceIdFromRemote(localDeviceId, deviceId, callerInfo.sourceDeviceId)) {
HILOGE("StartAbilityFromRemote check deviceId failed"); HILOGE("check deviceId failed");
return INVALID_REMOTE_PARAMETERS_ERR; return INVALID_REMOTE_PARAMETERS_ERR;
} }
DistributedSchedPermission& permissionInstance = DistributedSchedPermission::GetInstance(); DistributedSchedPermission& permissionInstance = DistributedSchedPermission::GetInstance();
ErrCode err = permissionInstance.CheckDPermission(want, callerInfo, accountInfo, abilityInfo, deviceId); ErrCode err = permissionInstance.CheckDPermission(want, callerInfo, accountInfo, abilityInfo, deviceId);
if (err != ERR_OK) { if (err != ERR_OK) {
HILOGE("StartAbilityFromRemote CheckDPermission denied!!"); HILOGE("CheckDPermission denied!!");
return err; return err;
} }
err = AAFwk::AbilityManagerClient::GetInstance()->Connect(); err = AAFwk::AbilityManagerClient::GetInstance()->Connect();
if (err != ERR_OK) { if (err != ERR_OK) {
HILOGE("StartAbilityFromRemote connect ability server failed %{public}d", err); HILOGE("connect ability server failed %{public}d", err);
return err; return err;
} }
err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, requestCode); err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, requestCode);
if (err != ERR_OK) { if (err != ERR_OK) {
HILOGE("StartAbilityFromRemote is failed %{public}d", err); HILOGE("StartAbility failed %{public}d", err);
} }
return err; return err;
} }
int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want, int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& abilityToken) const sptr<IRemoteObject>& abilityToken, int32_t callerUid)
{ {
HILOGD("[PerformanceTest] DistributedSchedService StartContinuation begin"); HILOGD("[PerformanceTest] StartContinuation begin");
if (abilityToken == nullptr) { if (abilityToken == nullptr) {
HILOGE("StartContinuation abilityToken is null!"); HILOGE("StartContinuation abilityToken is null!");
return INVALID_REMOTE_PARAMETERS_ERR; return INVALID_REMOTE_PARAMETERS_ERR;
@ -169,7 +174,16 @@ int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want
HILOGE("StartContinuation want continuation flags invalid!"); HILOGE("StartContinuation want continuation flags invalid!");
return INVALID_REMOTE_PARAMETERS_ERR; 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; std::string devId;
if (!GetLocalDeviceId(devId)) { if (!GetLocalDeviceId(devId)) {
HILOGE("StartContinuation get local deviceId failed!"); 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("sessionId", sessionId);
newWant.SetParam("deviceId", devId); newWant.SetParam("deviceId", devId);
int32_t result = ERR_OK; int32_t result = ERR_OK;
result = StartRemoteAbility(newWant, abilityInfo, 0); result = StartRemoteAbility(newWant, callerUid, 0);
if (result != ERR_OK) { if (result != ERR_OK) {
HILOGE("DistributedSchedService:continue ability failed, errorCode = %{public}d", result); HILOGE("continue ability failed, errorCode = %{public}d", result);
return result; return result;
} }
@ -197,7 +211,7 @@ int32_t DistributedSchedService::StartContinuation(const OHOS::AAFwk::Want& want
HILOGW("StartContinuation PushAbilityToken failed!"); HILOGW("StartContinuation PushAbilityToken failed!");
return INVALID_REMOTE_PARAMETERS_ERR; return INVALID_REMOTE_PARAMETERS_ERR;
} }
HILOGD("[PerformanceTest] DistributedSchedService StartContinuation end"); HILOGD("[PerformanceTest] StartContinuation end");
return result; return result;
} }
@ -250,22 +264,6 @@ void DistributedSchedService::NotifyContinuationCallbackResult(const sptr<IRemot
HILOGE("NotifyContinuationCallbackResult abilityToken null!"); HILOGE("NotifyContinuationCallbackResult abilityToken null!");
return; return;
} }
int32_t result = DistributedSchedAbilityShell::GetInstance().ScheduleCompleteContinuation(
abilityToken, isSuccess);
HILOGD("NotifyContinuationCallbackResult ScheduleCompleteContinuation result:%{public}d", result);
}
int32_t DistributedSchedService::RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
return DistributedSchedAbilityShell::GetInstance().RegisterAbilityToken(abilityToken, continuationCallback);
}
int32_t DistributedSchedService::UnregisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
return DistributedSchedAbilityShell::GetInstance().UnregisterAbilityToken(abilityToken, continuationCallback);
} }
void DistributedSchedService::RemoteConnectAbilityMappingLocked(const sptr<IRemoteObject>& connect, void DistributedSchedService::RemoteConnectAbilityMappingLocked(const sptr<IRemoteObject>& connect,
@ -343,7 +341,7 @@ int32_t DistributedSchedService::GetUidLocked(const std::list<ConnectAbilitySess
} }
int32_t DistributedSchedService::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, int32_t DistributedSchedService::ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& connect) const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid)
{ {
std::string localDeviceId; std::string localDeviceId;
std::string remoteDeviceId = want.GetElement().GetDeviceID(); std::string remoteDeviceId = want.GetElement().GetDeviceID();
@ -351,11 +349,13 @@ int32_t DistributedSchedService::ConnectRemoteAbility(const OHOS::AAFwk::Want& w
HILOGE("ConnectRemoteAbility check deviceId failed"); HILOGE("ConnectRemoteAbility check deviceId failed");
return INVALID_PARAMETERS_ERR; return INVALID_PARAMETERS_ERR;
} }
if (IPCSkeleton::GetCallingUid() != SYSTEM_UID) {
HILOGE("ConnectRemoteAbility check uid failed");
return INVALID_PARAMETERS_ERR;
}
std::lock_guard<std::mutex> autoLock(distributedLock_); std::lock_guard<std::mutex> autoLock(distributedLock_);
CallerInfo callerInfo = { CallerInfo callerInfo = { callerUid, callerPid, CALLER_TYPE_HARMONY, localDeviceId };
IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid(), CALLER_TYPE_HARMONY, localDeviceId
};
int32_t checkResult = CheckDistributedConnectLocked(callerInfo); int32_t checkResult = CheckDistributedConnectLocked(callerInfo);
if (checkResult != ERR_OK) { if (checkResult != ERR_OK) {
return checkResult; return checkResult;
@ -372,18 +372,19 @@ int32_t DistributedSchedService::ConnectRemoteAbility(const OHOS::AAFwk::Want& w
return INVALID_PARAMETERS_ERR; return INVALID_PARAMETERS_ERR;
} }
HILOGD("[PerformanceTest] DistributedSchedService::ConnectRemoteAbility begin"); HILOGD("[PerformanceTest] ConnectRemoteAbility begin");
int32_t result = TryConnectRemoteAbility(want, abilityInfo, connect, callerInfo); int32_t result = TryConnectRemoteAbility(want, connect, callerInfo);
if (result != ERR_OK) { if (result != ERR_OK) {
HILOGE("ConnectRemoteAbility result is %{public}d", result); HILOGE("ConnectRemoteAbility result is %{public}d", result);
} }
HILOGD("[PerformanceTest] DistributedSchedService::ConnectRemoteAbility end"); HILOGD("[PerformanceTest] ConnectRemoteAbility end");
return result; return result;
} }
int32_t DistributedSchedService::TryConnectRemoteAbility(const OHOS::AAFwk::Want& want, int32_t DistributedSchedService::TryConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo) const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo)
{ {
AppExecFwk::AbilityInfo abilityInfo;
AccountInfo accountInfo; AccountInfo accountInfo;
std::string remoteDeviceId = want.GetElement().GetDeviceID(); std::string remoteDeviceId = want.GetElement().GetDeviceID();
sptr<IDistributedSched> remoteDms = GetRemoteDms(remoteDeviceId); sptr<IDistributedSched> remoteDms = GetRemoteDms(remoteDeviceId);
@ -428,9 +429,9 @@ sptr<IDistributedSched> DistributedSchedService::GetRemoteDms(const std::string&
HILOGE("GetRemoteDms failed to connect to systemAbilityMgr!"); HILOGE("GetRemoteDms failed to connect to systemAbilityMgr!");
return nullptr; return nullptr;
} }
HILOGD("[PerformanceTest] DistributedSchedService GetRemoteDms begin"); HILOGD("[PerformanceTest] GetRemoteDms begin");
auto object = samgr->CheckSystemAbility(DISTRIBUTED_SCHED_SA_ID, remoteDeviceId); auto object = samgr->CheckSystemAbility(DISTRIBUTED_SCHED_SA_ID, remoteDeviceId);
HILOGD("[PerformanceTest] DistributedSchedService GetRemoteDms end"); HILOGD("[PerformanceTest] GetRemoteDms end");
if (object == nullptr) { if (object == nullptr) {
HILOGE("GetRemoteDms failed to get remote DistributedSched %{private}s", remoteDeviceId.c_str()); HILOGE("GetRemoteDms failed to get remote DistributedSched %{private}s", remoteDeviceId.c_str());
return nullptr; return nullptr;
@ -519,7 +520,7 @@ int32_t DistributedSchedService::ConnectAbilityFromRemote(const OHOS::AAFwk::Wan
} }
} }
int32_t errCode = DistributedSchedAdapter::GetInstance().ConnectAbility(want, callbackWrapper, this); int32_t errCode = DistributedSchedAdapter::GetInstance().ConnectAbility(want, callbackWrapper, this);
HILOGD("[PerformanceTest] DistributedSchedService ConnectAbilityFromRemote end"); HILOGD("[PerformanceTest] ConnectAbilityFromRemote end");
return errCode; return errCode;
} }
@ -562,7 +563,7 @@ int32_t DistributedSchedService::DisconnectRemoteAbility(const sptr<IRemoteObjec
DecreaseConnectLocked(uid); DecreaseConnectLocked(uid);
connect->RemoveDeathRecipient(connectDeathRecipient_); connect->RemoveDeathRecipient(connectDeathRecipient_);
distributedConnectAbilityMap_.erase(it); distributedConnectAbilityMap_.erase(it);
HILOGI("remove connect sucess"); HILOGI("remove connection success");
return ERR_OK; return ERR_OK;
} }
return NO_CONNECT_CALLBACK_ERR; return NO_CONNECT_CALLBACK_ERR;
@ -576,7 +577,7 @@ int32_t DistributedSchedService::DisconnectAbilityFromRemote(const sptr<IRemoteO
return INVALID_REMOTE_PARAMETERS_ERR; return INVALID_REMOTE_PARAMETERS_ERR;
} }
HILOGD("[PerformanceTest] DistributedSchedService::DisconnectAbilityFromRemote begin"); HILOGD("[PerformanceTest] DisconnectAbilityFromRemote begin");
std::string localDeviceId; std::string localDeviceId;
AppExecFwk::AbilityInfo abilityInfo; AppExecFwk::AbilityInfo abilityInfo;
if (!GetLocalDeviceId(localDeviceId) || localDeviceId.empty() || if (!GetLocalDeviceId(localDeviceId) || localDeviceId.empty() ||
@ -600,13 +601,13 @@ int32_t DistributedSchedService::DisconnectAbilityFromRemote(const sptr<IRemoteO
} }
} }
int32_t result = DistributedSchedAdapter::GetInstance().DisconnectAbility(callbackWrapper); int32_t result = DistributedSchedAdapter::GetInstance().DisconnectAbility(callbackWrapper);
HILOGD("[PerformanceTest] DistributedSchedService::DisconnectAbilityFromRemote end"); HILOGD("[PerformanceTest] DisconnectAbilityFromRemote end");
return result; return result;
} }
int32_t DistributedSchedService::NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) int32_t DistributedSchedService::NotifyProcessDiedFromRemote(const CallerInfo& callerInfo)
{ {
HILOGI("DistributedSchedService::NotifyProcessDiedFromRemote called"); HILOGI("NotifyProcessDiedFromRemote called");
int32_t errCode = ERR_OK; int32_t errCode = ERR_OK;
{ {
std::lock_guard<std::mutex> autoLock(distributedLock_); std::lock_guard<std::mutex> autoLock(distributedLock_);
@ -632,7 +633,7 @@ int32_t DistributedSchedService::NotifyProcessDiedFromRemote(const CallerInfo& c
void DistributedSchedService::ProcessDeviceOffline(const std::string& deviceId) void DistributedSchedService::ProcessDeviceOffline(const std::string& deviceId)
{ {
HILOGI("DistributedSchedService::ProcessDeviceOffline called"); HILOGI("ProcessDeviceOffline called");
std::string localDeviceId; std::string localDeviceId;
if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) { if (!GetLocalDeviceId(localDeviceId) || !CheckDeviceId(localDeviceId, deviceId)) {
HILOGE("ProcessDeviceOffline check deviceId failed"); HILOGE("ProcessDeviceOffline check deviceId failed");
@ -859,5 +860,88 @@ void DistributedSchedService::DumpElementLocked(const std::list<AppExecFwk::Elem
info += element.GetAbilityName(); info += element.GetAbilityName();
} }
} }
int32_t DistributedSchedService::GetMissionInfos(const std::string& deviceId, int32_t numMissions,
std::vector<MissionInfo>& missionInfos)
{
return DistributedSchedMissionManager::GetInstance().GetMissionInfos(deviceId, numMissions, missionInfos);
}
int32_t DistributedSchedService::NotifyMissionsChangedFromRemote(const std::vector<MissionInfo>& missionInfos,
const CallerInfo& callerInfo)
{
return DistributedSchedMissionManager::GetInstance()
.NotifyMissionsChangedFromRemote(callerInfo, missionInfos);
}
std::unique_ptr<Snapshot> 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<std::u16string>& deviceIds, std::vector<int32_t>& 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<IRemoteObject>& obj)
{
return DistributedSchedMissionManager::GetInstance().RegisterRemoteMissionListener(devId, obj);
}
int32_t DistributedSchedService::UnRegisterRemoteMissionListener(const std::u16string& devId,
const sptr<IRemoteObject>& obj)
{
return DistributedSchedMissionManager::GetInstance().UnRegisterRemoteMissionListener(devId, obj);
}
int32_t DistributedSchedService::PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo,
std::vector<MissionInfo>& 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 DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -16,13 +16,15 @@
#include "distributed_sched_stub.h" #include "distributed_sched_stub.h"
#include "ability_info.h" #include "ability_info.h"
#include "adapter/dnetwork_adapter.h"
#include "caller_info.h" #include "caller_info.h"
#include "distributed_sched_ability_shell.h"
#include "dtbschedmgr_log.h"
#include "datetime_ex.h" #include "datetime_ex.h"
#include "dtbschedmgr_log.h"
#include "dtbschedmgr_device_info_storage.h"
#include "image_source.h"
#include "ipc_skeleton.h" #include "ipc_skeleton.h"
#include "message_parcel.h" #include "message_parcel.h"
#include "mission/distributed_sched_mission_manager.h"
#include "parcel_helper.h" #include "parcel_helper.h"
namespace OHOS { namespace OHOS {
@ -33,6 +35,7 @@ using namespace AppExecFwk;
namespace { namespace {
constexpr int32_t HID_HAP = 10000; /* first hap user */ 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"; 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_REMOTE_ABILITY] = &DistributedSchedStub::StartRemoteAbilityInner;
localFuncsMap_[START_CONTINUATION] = &DistributedSchedStub::StartContinuationInner; localFuncsMap_[START_CONTINUATION] = &DistributedSchedStub::StartContinuationInner;
localFuncsMap_[NOTIFY_COMPLETE_CONTINUATION] = &DistributedSchedStub::NotifyCompleteContinuationInner; 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_[CONNECT_REMOTE_ABILITY] = &DistributedSchedStub::ConnectRemoteAbilityInner;
localFuncsMap_[DISCONNECT_REMOTE_ABILITY] = &DistributedSchedStub::DisconnectRemoteAbilityInner; 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_[START_ABILITY_FROM_REMOTE] = &DistributedSchedStub::StartAbilityFromRemoteInner;
remoteFuncsMap_[NOTIFY_CONTINUATION_RESULT_FROM_REMOTE] = remoteFuncsMap_[NOTIFY_CONTINUATION_RESULT_FROM_REMOTE] =
@ -52,6 +65,14 @@ DistributedSchedStub::DistributedSchedStub()
remoteFuncsMap_[CONNECT_ABILITY_FROM_REMOTE] = &DistributedSchedStub::ConnectAbilityFromRemoteInner; remoteFuncsMap_[CONNECT_ABILITY_FROM_REMOTE] = &DistributedSchedStub::ConnectAbilityFromRemoteInner;
remoteFuncsMap_[DISCONNECT_ABILITY_FROM_REMOTE] = &DistributedSchedStub::DisconnectAbilityFromRemoteInner; remoteFuncsMap_[DISCONNECT_ABILITY_FROM_REMOTE] = &DistributedSchedStub::DisconnectAbilityFromRemoteInner;
remoteFuncsMap_[NOTIFY_PROCESS_DIED_FROM_REMOTE] = &DistributedSchedStub::NotifyProcessDiedFromRemoteInner; 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() DistributedSchedStub::~DistributedSchedStub()
@ -64,7 +85,7 @@ int32_t DistributedSchedStub::OnRemoteRequest(uint32_t code,
MessageParcel& data, MessageParcel& reply, MessageOption& option) MessageParcel& data, MessageParcel& reply, MessageOption& option)
{ {
bool IsLocalCalling = IPCSkeleton::IsLocalCalling(); 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); code, option.GetFlags(), IsLocalCalling);
const auto& funcsMap = IsLocalCalling ? localFuncsMap_ : remoteFuncsMap_; const auto& funcsMap = IsLocalCalling ? localFuncsMap_ : remoteFuncsMap_;
@ -72,7 +93,7 @@ int32_t DistributedSchedStub::OnRemoteRequest(uint32_t code,
if (iter != funcsMap.end()) { if (iter != funcsMap.end()) {
auto func = iter->second; auto func = iter->second;
if (!EnforceInterfaceToken(data)) { if (!EnforceInterfaceToken(data)) {
HILOGW("DistributedSchedStub::OnRemoteRequest interface token check failed!"); HILOGW("OnRemoteRequest interface token check failed!");
return DMS_PERMISSION_DENIED; return DMS_PERMISSION_DENIED;
} }
if (func != nullptr) { 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); return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
} }
@ -88,18 +109,16 @@ int32_t DistributedSchedStub::StartRemoteAbilityInner(MessageParcel& data, Messa
{ {
shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>()); shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>());
if (want == nullptr) { if (want == nullptr) {
HILOGW("DistributedSchedStub:: START_ABILITY want readParcelable failed!"); HILOGW("START_ABILITY want readParcelable failed!");
return ERR_NULL_OBJECT;
}
unique_ptr<AbilityInfo> spAbilityInfo(data.ReadParcelable<AbilityInfo>());
if (spAbilityInfo == nullptr) {
HILOGW("DistributedSchedStub: StartRemoteAbilityInner AbilityInfo readParcelable failed!");
return ERR_NULL_OBJECT; return ERR_NULL_OBJECT;
} }
int32_t callerUid = 0;
PARCEL_READ_HELPER(data, Int32, callerUid);
HILOGI("get callerUid = %{public}d", callerUid);
int32_t requestCode = 0; int32_t requestCode = 0;
PARCEL_READ_HELPER(data, Int32, requestCode); PARCEL_READ_HELPER(data, Int32, requestCode);
int32_t result = StartRemoteAbility(*want, *spAbilityInfo, requestCode); int32_t result = StartRemoteAbility(*want, callerUid, requestCode);
HILOGI("DistributedSchedStub:: StartRemoteAbilityInner result = %{public}d", result); HILOGI("StartRemoteAbilityInner result = %{public}d", result);
PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result);
} }
@ -107,12 +126,12 @@ int32_t DistributedSchedStub::StartAbilityFromRemoteInner(MessageParcel& data, M
{ {
shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>()); shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>());
if (want == nullptr) { if (want == nullptr) {
HILOGW("DistributedSchedStub:: StartAbilityFromRemoteInner want readParcelable failed!"); HILOGW("want readParcelable failed!");
return ERR_NULL_OBJECT; return ERR_NULL_OBJECT;
} }
unique_ptr<CompatibleAbilityInfo> cmpAbilityInfo(data.ReadParcelable<CompatibleAbilityInfo>()); unique_ptr<CompatibleAbilityInfo> cmpAbilityInfo(data.ReadParcelable<CompatibleAbilityInfo>());
if (cmpAbilityInfo == nullptr) { if (cmpAbilityInfo == nullptr) {
HILOGW("DistributedSchedStub: StartAbilityFromRemoteInner AbilityInfo readParcelable failed!"); HILOGW("AbilityInfo readParcelable failed!");
return ERR_NULL_OBJECT; return ERR_NULL_OBJECT;
} }
AbilityInfo abilityInfo; AbilityInfo abilityInfo;
@ -131,7 +150,7 @@ int32_t DistributedSchedStub::StartAbilityFromRemoteInner(MessageParcel& data, M
PARCEL_READ_HELPER(data, StringVector, &accountInfo.groupIdList); PARCEL_READ_HELPER(data, StringVector, &accountInfo.groupIdList);
callerInfo.callerAppId = data.ReadString(); callerInfo.callerAppId = data.ReadString();
int32_t result = StartAbilityFromRemote(*want, abilityInfo, requestCode, callerInfo, accountInfo); 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); PARCEL_WRITE_HELPER(reply, Int32, result);
int64_t end = GetTickCount(); int64_t end = GetTickCount();
PARCEL_WRITE_HELPER(reply, Int64, end - begin); PARCEL_WRITE_HELPER(reply, Int64, end - begin);
@ -144,17 +163,13 @@ int32_t DistributedSchedStub::StartContinuationInner(MessageParcel& data, Messag
{ {
shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>()); shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>());
if (want == nullptr) { if (want == nullptr) {
HILOGW("DistributedSchedStub: StartContinuationInner want readParcelable failed!"); HILOGW("want readParcelable failed!");
return ERR_NULL_OBJECT;
}
unique_ptr<AbilityInfo> spAbilityInfo(data.ReadParcelable<AbilityInfo>());
if (spAbilityInfo == nullptr) {
HILOGW("DistributedSchedStub: StartContinuationInner AbilityInfo readParcelable failed!");
return ERR_NULL_OBJECT; return ERR_NULL_OBJECT;
} }
sptr<IRemoteObject> abilityToken = data.ReadRemoteObject(); sptr<IRemoteObject> abilityToken = data.ReadRemoteObject();
int32_t result = StartContinuation(*want, *spAbilityInfo, abilityToken); int32_t callerUid = data.ReadInt32();
HILOGI("DistributedSchedStub: StartContinuationInner result = %{public}d", result); int32_t result = StartContinuation(*want, abilityToken, callerUid);
HILOGI("result = %{public}d", result);
PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result);
} }
@ -163,7 +178,7 @@ int32_t DistributedSchedStub::NotifyCompleteContinuationInner(MessageParcel& dat
{ {
u16string devId = data.ReadString16(); u16string devId = data.ReadString16();
if (devId.empty()) { if (devId.empty()) {
HILOGE("DistributedSchedStub: NotifyCompleteContinuationInner devId empty!"); HILOGE("devId is empty!");
return INVALID_PARAMETERS_ERR; return INVALID_PARAMETERS_ERR;
} }
int32_t sessionId = 0; int32_t sessionId = 0;
@ -178,7 +193,7 @@ int32_t DistributedSchedStub::NotifyContinuationResultFromRemoteInner(MessagePar
[[maybe_unused]] MessageParcel& reply) [[maybe_unused]] MessageParcel& reply)
{ {
if (!CheckCallingUid()) { if (!CheckCallingUid()) {
HILOGW("DistributedSchedStub: NotifyContinuationResultFromRemoteInner request DENIED!"); HILOGW("request DENIED!");
return DMS_PERMISSION_DENIED; return DMS_PERMISSION_DENIED;
} }
@ -189,39 +204,22 @@ int32_t DistributedSchedStub::NotifyContinuationResultFromRemoteInner(MessagePar
return NotifyContinuationResultFromRemote(sessionId, continuationResult); return NotifyContinuationResultFromRemote(sessionId, continuationResult);
} }
int32_t DistributedSchedStub::RegisterAbilityTokenInner(MessageParcel& data, MessageParcel& reply)
{
sptr<IRemoteObject> abilityToken = data.ReadRemoteObject();
sptr<IRemoteObject> 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<IRemoteObject> abilityToken = data.ReadRemoteObject();
sptr<IRemoteObject> 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) int32_t DistributedSchedStub::ConnectRemoteAbilityInner(MessageParcel& data, MessageParcel& reply)
{ {
shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>()); shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>());
if (want == nullptr) { if (want == nullptr) {
HILOGW("DistributedSchedStub::ConnectRemoteAbilityInner want readParcelable failed!"); HILOGW("want readParcelable failed!");
return ERR_NULL_OBJECT;
}
unique_ptr<AppExecFwk::AbilityInfo> abilityInfo(data.ReadParcelable<AppExecFwk::AbilityInfo>());
if (abilityInfo == nullptr) {
HILOGW("DistributedSchedStub::ConnectRemoteAbilityInner abilityInfo readParcelable failed!");
return ERR_NULL_OBJECT; return ERR_NULL_OBJECT;
} }
sptr<IRemoteObject> connect = data.ReadRemoteObject(); sptr<IRemoteObject> connect = data.ReadRemoteObject();
int32_t result = ConnectRemoteAbility(*want, *abilityInfo, connect); int32_t callerUid = 0;
HILOGI("DistributedSchedStub::ConnectRemoteAbilityInner result = %{public}d", result); 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); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result);
} }
@ -229,25 +227,25 @@ int32_t DistributedSchedStub::DisconnectRemoteAbilityInner(MessageParcel& data,
{ {
sptr<IRemoteObject> connect = data.ReadRemoteObject(); sptr<IRemoteObject> connect = data.ReadRemoteObject();
int32_t result = DisconnectRemoteAbility(connect); int32_t result = DisconnectRemoteAbility(connect);
HILOGI("DistributedSchedStub::DisconnectRemoteAbilityInner result = %{public}d", result); HILOGI("result = %{public}d", result);
PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result);
} }
int32_t DistributedSchedStub::ConnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply) int32_t DistributedSchedStub::ConnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply)
{ {
if (!CheckCallingUid()) { if (!CheckCallingUid()) {
HILOGW("DistributedSchedStub::ConnectAbilityFromRemoteInner request DENIED!"); HILOGW("request DENIED!");
return DMS_PERMISSION_DENIED; return DMS_PERMISSION_DENIED;
} }
shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>()); shared_ptr<AAFwk::Want> want(data.ReadParcelable<AAFwk::Want>());
if (want == nullptr) { if (want == nullptr) {
HILOGW("DistributedSchedStub::ConnectAbilityFromRemoteInner want readParcelable failed!"); HILOGW("want readParcelable failed!");
return ERR_NULL_OBJECT; return ERR_NULL_OBJECT;
} }
unique_ptr<CompatibleAbilityInfo> cmpAbilityInfo(data.ReadParcelable<CompatibleAbilityInfo>()); unique_ptr<CompatibleAbilityInfo> cmpAbilityInfo(data.ReadParcelable<CompatibleAbilityInfo>());
if (cmpAbilityInfo == nullptr) { if (cmpAbilityInfo == nullptr) {
HILOGW("DistributedSchedStub::ConnectAbilityFromRemoteInner abilityInfo readParcelable failed!"); HILOGW("abilityInfo readParcelable failed!");
return ERR_NULL_OBJECT; return ERR_NULL_OBJECT;
} }
AbilityInfo abilityInfo; AbilityInfo abilityInfo;
@ -266,7 +264,7 @@ int32_t DistributedSchedStub::ConnectAbilityFromRemoteInner(MessageParcel& data,
std::string deviceId = abilityInfo.deviceId; std::string deviceId = abilityInfo.deviceId;
int64_t begin = GetTickCount(); int64_t begin = GetTickCount();
int32_t result = ConnectAbilityFromRemote(*want, abilityInfo, connect, callerInfo, accountInfo); 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(); int64_t end = GetTickCount();
PARCEL_WRITE_HELPER(reply, Int32, result); PARCEL_WRITE_HELPER(reply, Int32, result);
PARCEL_WRITE_HELPER(reply, Int64, end - begin); 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) int32_t DistributedSchedStub::DisconnectAbilityFromRemoteInner(MessageParcel& data, MessageParcel& reply)
{ {
if (!CheckCallingUid()) { if (!CheckCallingUid()) {
HILOGW("DistributedSchedStub::DisconnectAbilityFromRemoteInner request DENIED!"); HILOGW("request DENIED!");
return DMS_PERMISSION_DENIED; return DMS_PERMISSION_DENIED;
} }
@ -288,14 +286,14 @@ int32_t DistributedSchedStub::DisconnectAbilityFromRemoteInner(MessageParcel& da
string sourceDeviceId; string sourceDeviceId;
PARCEL_READ_HELPER(data, String, sourceDeviceId); PARCEL_READ_HELPER(data, String, sourceDeviceId);
int32_t result = DisconnectAbilityFromRemote(connect, uid, 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); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result);
} }
int32_t DistributedSchedStub::NotifyProcessDiedFromRemoteInner(MessageParcel& data, MessageParcel& reply) int32_t DistributedSchedStub::NotifyProcessDiedFromRemoteInner(MessageParcel& data, MessageParcel& reply)
{ {
if (!CheckCallingUid()) { if (!CheckCallingUid()) {
HILOGW("DistributedSchedStub::NotifyProcessDiedFromRemoteInner request DENIED!"); HILOGW("request DENIED!");
return DMS_PERMISSION_DENIED; return DMS_PERMISSION_DENIED;
} }
@ -311,7 +309,7 @@ int32_t DistributedSchedStub::NotifyProcessDiedFromRemoteInner(MessageParcel& da
callerInfo.sourceDeviceId = sourceDeviceId; callerInfo.sourceDeviceId = sourceDeviceId;
callerInfo.callerType = CALLER_TYPE_HARMONY; callerInfo.callerType = CALLER_TYPE_HARMONY;
int32_t result = NotifyProcessDiedFromRemote(callerInfo); int32_t result = NotifyProcessDiedFromRemote(callerInfo);
HILOGI("DistributedSchedStub::NotifyProcessDiedFromRemoteInner result %{public}d", result); HILOGI("result %{public}d", result);
PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result); PARCEL_WRITE_REPLY_NOERROR(reply, Int32, result);
} }
@ -327,5 +325,278 @@ bool DistributedSchedStub::EnforceInterfaceToken(MessageParcel& data)
u16string interfaceToken = data.ReadInterfaceToken(); u16string interfaceToken = data.ReadInterfaceToken();
return interfaceToken == DMS_STUB_INTERFACE_TOKEN; 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<MissionInfo> 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> 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<IRemoteObject> 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<MissionInfo> 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<IRemoteObject> 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<std::u16string> deviceIds;
std::vector<int32_t> 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<MissionInfo> 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<MissionInfo> 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 DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -25,17 +25,18 @@
#include "ipc_object_proxy.h" #include "ipc_object_proxy.h"
#include "ipc_skeleton.h" #include "ipc_skeleton.h"
#include "iservice_registry.h" #include "iservice_registry.h"
#include "mission/distributed_sched_mission_manager.h"
#include "system_ability_definition.h" #include "system_ability_definition.h"
using namespace std;
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
using namespace std::chrono_literals; using namespace std::chrono_literals;
namespace { namespace {
constexpr int32_t RETRY_TIMES = 30; 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; constexpr int32_t CONNECT_SOFTBUS_RETRY_TIMES = 60;
const std::string TAG = "DtbschedmgrDeviceInfoStorage";
} }
IMPLEMENT_SINGLE_INSTANCE(DtbschedmgrDeviceInfoStorage); IMPLEMENT_SINGLE_INSTANCE(DtbschedmgrDeviceInfoStorage);
@ -48,17 +49,18 @@ bool DtbschedmgrDeviceInfoStorage::Init()
} }
auto func = [this]() { auto func = [this]() {
HILOGI("DtbschedmgrDeviceInfoStorage begin connect softbus"); HILOGI("begin connect softbus");
for (int32_t retryTimes = 0; retryTimes <= CONNECT_SOFTBUS_RETRY_TIMES; retryTimes++) { for (int32_t retryTimes = 0; retryTimes <= CONNECT_SOFTBUS_RETRY_TIMES; retryTimes++) {
if (ConnectSoftbus()) { if (ConnectSoftbus()) {
return; return;
} }
HILOGE("DtbschedmgrDeviceInfoStorage retry connect softbus %{public}d times", retryTimes); HILOGE("retry connect softbus %{public}d times", retryTimes);
std::this_thread::sleep_for(1s); std::this_thread::sleep_for(1s);
} }
HILOGE("connect softbus 60times * 30s, error!!");
}; };
if (!initHandler_->PostTask(func)) { if (!initHandler_->PostTask(func)) {
HILOGE("DtbschedmgrDeviceInfoStorage::Init handler postTask failed"); HILOGE("Init handler postTask failed");
return false; return false;
} }
return true; return true;
@ -66,35 +68,36 @@ bool DtbschedmgrDeviceInfoStorage::Init()
bool DtbschedmgrDeviceInfoStorage::ConnectSoftbus() bool DtbschedmgrDeviceInfoStorage::ConnectSoftbus()
{ {
ClearAllDevices();
bool isReady = WaitForDnetworkReady(); bool isReady = WaitForDnetworkReady();
if (!isReady) { if (!isReady) {
HILOGE("DtbschedmgrDeviceInfoStorage::ConnectSoftbus wait Dnetwork failed!"); HILOGE("ConnectSoftbus wait Dnetwork failed!");
return false; return false;
} }
std::shared_ptr<DnetworkAdapter> dnetworkAdapter = DnetworkAdapter::GetInstance(); std::shared_ptr<DnetworkAdapter> dnetworkAdapter = DnetworkAdapter::GetInstance();
if (dnetworkAdapter == nullptr) { if (dnetworkAdapter == nullptr) {
HILOGE("DtbschedmgrDeviceInfoStorage DnetworkAdapter::GetInstance() null"); HILOGE("DnetworkAdapter::GetInstance() null");
return false; return false;
} }
if (!InitNodeIdManager(dnetworkAdapter)) { if (!InitNetworkIdManager(dnetworkAdapter)) {
HILOGE("DtbschedmgrDeviceInfoStorage::InitNodeIdManager failed"); HILOGE("InitNetworkIdManager failed");
return false; return false;
} }
HILOGI("DtbschedmgrDeviceInfoStorage::ConnectSoftbus success"); HILOGI("ConnectSoftbus success");
return true; return true;
} }
bool DtbschedmgrDeviceInfoStorage::InitNodeIdManager(std::shared_ptr<DnetworkAdapter> dnetworkAdapter) bool DtbschedmgrDeviceInfoStorage::InitNetworkIdManager(std::shared_ptr<DnetworkAdapter> dnetworkAdapter)
{ {
if (nodeIdMgrHandler_ == nullptr) { if (networkIdMgrHandler_ == nullptr) {
auto runner = AppExecFwk::EventRunner::Create("DmsNodeIdManager"); auto runner = AppExecFwk::EventRunner::Create("DmsNetworkIdManager");
nodeIdMgrHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner); networkIdMgrHandler_ = std::make_shared<AppExecFwk::EventHandler>(runner);
} }
deviceNodeListener_ = std::make_shared<DistributedDeviceNodeListener>(); deviceNodeListener_ = std::make_shared<DistributedDeviceNodeListener>();
if (!dnetworkAdapter->AddDeviceChangeListener(deviceNodeListener_)) { if (!dnetworkAdapter->AddDeviceChangeListener(deviceNodeListener_)) {
HILOGE("DtbschedmgrDeviceInfoStorage::AddDeviceChangeListener failed");
deviceNodeListener_ = nullptr; deviceNodeListener_ = nullptr;
HILOGE("AddDeviceChangeListener failed!");
return false; return false;
} }
return true; return true;
@ -102,9 +105,10 @@ bool DtbschedmgrDeviceInfoStorage::InitNodeIdManager(std::shared_ptr<DnetworkAda
void DtbschedmgrDeviceInfoStorage::Stop() void DtbschedmgrDeviceInfoStorage::Stop()
{ {
ClearAllDevices();
if (deviceNodeListener_ != nullptr) { if (deviceNodeListener_ != nullptr) {
DnetworkAdapter::GetInstance()->RemoveDeviceChangeListener(deviceNodeListener_); DnetworkAdapter::GetInstance()->RemoveDeviceChangeListener(deviceNodeListener_);
deviceNodeListener_= nullptr; deviceNodeListener_ = nullptr;
} }
} }
@ -125,16 +129,43 @@ bool DtbschedmgrDeviceInfoStorage::WaitForDnetworkReady()
return true; return true;
} }
} }
HILOGI("DtbschedmgrDeviceInfoStorage::Waiting for dnentwork service..."); HILOGI("Waiting for dnentwork service...");
std::this_thread::sleep_for(1s); std::this_thread::sleep_for(1s);
if (--retryTimeout <= 0) { if (--retryTimeout <= 0) {
HILOGI("DtbschedmgrDeviceInfoStorage::Waiting for dnentwork service timeout(30)s"); HILOGI("Waiting for dnentwork service timeout(30)s");
return false; return false;
} }
} while (true); } while (true);
return false; return false;
} }
void DtbschedmgrDeviceInfoStorage::RegisterUuidNetworkIdMap(const std::string& networkId)
{
std::string uuid = DnetworkAdapter::GetInstance()->GetUuidByNetworkId(networkId);
{
std::lock_guard<std::mutex> autoLock(uuidNetworkIdLock_);
uuidNetworkIdMap_[uuid] = networkId;
}
}
void DtbschedmgrDeviceInfoStorage::UnregisterUuidNetworkIdMap(const std::string& networkId)
{
std::string uuid = DnetworkAdapter::GetInstance()->GetUuidByNetworkId(networkId);
{
std::lock_guard<std::mutex> autoLock(uuidNetworkIdLock_);
uuidNetworkIdMap_.erase(uuid);
}
}
void DtbschedmgrDeviceInfoStorage::GetDeviceIdSet(std::set<std::string>& deviceIdSet)
{
deviceIdSet.clear();
lock_guard<mutex> autoLock(deviceLock_);
for (const auto& device : remoteDevices_) {
deviceIdSet.emplace(device.first);
}
}
bool DtbschedmgrDeviceInfoStorage::GetLocalDeviceId(std::string& deviceId) bool DtbschedmgrDeviceInfoStorage::GetLocalDeviceId(std::string& deviceId)
{ {
return GetLocalDeviceFromDnet(deviceId); return GetLocalDeviceFromDnet(deviceId);
@ -144,82 +175,143 @@ bool DtbschedmgrDeviceInfoStorage::GetLocalDeviceFromDnet(std::string& deviceId)
{ {
auto dnetworkAdapter = DnetworkAdapter::GetInstance(); auto dnetworkAdapter = DnetworkAdapter::GetInstance();
if (dnetworkAdapter == nullptr) { if (dnetworkAdapter == nullptr) {
HILOGE("DtbschedmgrDeviceInfoStorage::GetLocalDeviceFromDnet dnetworkAdapter null"); HILOGE("GetLocalDeviceFromDnet dnetworkAdapter null");
return false; return false;
} }
std::shared_ptr<NodeBasicInfo> localNode = dnetworkAdapter->GetLocalBasicInfo(); std::shared_ptr<NodeBasicInfo> localNode = dnetworkAdapter->GetLocalBasicInfo();
if (localNode != nullptr) { if (localNode != nullptr) {
deviceId = localNode->networkId; deviceId = localNode->networkId;
HILOGI("get local deviceId from DnetworkAdapter, deviceId = %{public}s", HILOGI("get local deviceId from DnetworkAdapter, deviceId = %{public}s",
AnonymizeDeviceId(deviceId).c_str()); DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str());
return true; return true;
} }
HILOGE("DtbschedmgrDeviceInfoStorage::GetLocalDeviceFromDnet localNode null"); HILOGE("GetLocalDeviceFromDnet localNode null");
return false; return false;
} }
std::string DtbschedmgrDeviceInfoStorage::AnonymizeDeviceId(const std::string& deviceId) void DtbschedmgrDeviceInfoStorage::ClearAllDevices()
{ {
if (deviceId.length() < NON_ANONYMIZE_LENGTH) { lock_guard<mutex> autoLock(deviceLock_);
return EMPTY_DEVICE_ID; remoteDevices_.clear();
}
std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
anonDeviceId.append("******");
return anonDeviceId;
} }
std::shared_ptr<DmsDeviceInfo> DtbschedmgrDeviceInfoStorage::GetDeviceInfoById(const string& deviceId)
{
lock_guard<mutex> 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<std::mutex> 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<std::mutex> autoLock(uuidNetworkIdLock_);
auto iter = uuidNetworkIdMap_.find(uuid);
if (iter != uuidNetworkIdMap_.end()) {
return iter->second;
}
return "";
}
}
void DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify(const std::shared_ptr<DmsDeviceInfo> devInfo) void DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify(const std::shared_ptr<DmsDeviceInfo> devInfo)
{ {
if (devInfo == nullptr) { if (devInfo == nullptr) {
HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify devInfo null"); HILOGE("DeviceOnlineNotify devInfo null");
return; return;
} }
std::string devId = devInfo->GetDeviceId(); std::string devId = devInfo->GetDeviceId();
HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify deviceId = %{public}s", HILOGI("DeviceOnlineNotify deviceId = %{public}s",
AnonymizeDeviceId(devId).c_str()); DnetworkAdapter::AnonymizeDeviceId(devId).c_str());
if (nodeIdMgrHandler_ == nullptr) { if (networkIdMgrHandler_ == nullptr) {
HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify nodeIdMgrHandler null"); HILOGE("DeviceOnlineNotify networkIdMgrHandler null");
return; return;
} }
auto nodeOnline = [this, devInfo]() { auto nodeOnline = [this, devInfo]() {
HILOGI("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify called");
std::string deviceId = devInfo->GetDeviceId(); 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); DistributedSchedAdapter::GetInstance().DeviceOnline(deviceId);
DistributedSchedMissionManager::GetInstance().UpdateConnCapSupportOsd(deviceId);
DistributedSchedMissionManager::GetInstance().DeviceOnlineNotify(deviceId);
{
lock_guard<mutex> autoLock(deviceLock_);
remoteDevices_[deviceId] = devInfo;
}
DistributedSchedMissionManager::GetInstance().UpdateSwitchValueToRemote();
}; };
if (!nodeIdMgrHandler_->PostTask(nodeOnline)) { if (!networkIdMgrHandler_->PostTask(nodeOnline)) {
HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOnlineNotify handler postTask failed"); HILOGE("DeviceOnlineNotify handler postTask failed");
} }
} }
void DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify(const std::string& deviceId) void DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify(const std::string& deviceId)
{ {
if (deviceId.empty()) { if (deviceId.empty()) {
HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify deviceId empty"); HILOGE("DeviceOfflineNotify deviceId empty");
return; return;
} }
if (nodeIdMgrHandler_ == nullptr) { HILOGI("DeviceOfflineNotify deviceId = %{public}s",
HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify nodeIdMgrHandler null"); DnetworkAdapter::AnonymizeDeviceId(deviceId).c_str());
if (networkIdMgrHandler_ == nullptr) {
HILOGE("DeviceOfflineNotify networkIdMgrHandler null");
return; return;
} }
auto nodeOffline = [this, deviceId]() { 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); DistributedSchedAdapter::GetInstance().DeviceOffline(deviceId);
DistributedSchedMissionManager::GetInstance().DeviceOfflineNotify(deviceId);
UnregisterUuidNetworkIdMap(deviceId);
lock_guard<mutex> autoLock(deviceLock_);
remoteDevices_.erase(deviceId);
}; };
if (!nodeIdMgrHandler_->PostTask(nodeOffline)) { if (!networkIdMgrHandler_->PostTask(nodeOffline)) {
HILOGE("DtbschedmgrDeviceInfoStorage::DeviceOfflineNotify handler postTask failed"); HILOGE("DeviceOfflineNotify handler postTask failed");
} }
} }
void DtbschedmgrDeviceInfoStorage::OnDeviceInfoChanged(const std::string& deviceId, DeviceInfoType type) void DtbschedmgrDeviceInfoStorage::OnDeviceInfoChanged(const std::string& deviceId, DeviceInfoType type)
{ {
HILOGI("DtbschedmgrDeviceInfoStorage::OnDeviceInfoChanged called"); HILOGI("OnDeviceInfoChanged called");
} }
void DnetServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote) void DnetServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
{ {
HILOGI("DnetServiceDeathRecipient::OnRemoteDied dnetwork service died"); HILOGI("OnRemoteDied dnetwork service died");
DtbschedmgrDeviceInfoStorage::GetInstance().Init(); DtbschedmgrDeviceInfoStorage::GetInstance().Init();
} }
} }
} }

View File

@ -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 <cinttypes>
#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<KeyInfo> ParseInfo(const std::string& strKey)
{
std::vector<string> 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>();
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<Entry> inserts = appChangeNotification.GetInsertEntries();
for (const auto& entry : inserts) {
unique_ptr<KeyInfo> 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<Entry> deletes = appChangeNotification.GetDeleteEntries();
for (const auto& entry : deletes) {
unique_ptr<KeyInfo> 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<Entry> updates = appChangeNotification.GetUpdateEntries();
for (const auto& entry : updates) {
unique_ptr<KeyInfo> 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

View File

@ -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 <unistd.h>
#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<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create("dmsDataStorageHandler");
dmsDataStorageHandler_ = make_shared<AppExecFwk::EventHandler>(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<shared_mutex> 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<string>& deviceVec, const SyncMode& mode, uint32_t syncCount)
{
return true;
}
void DistributedDataStorage::RetrySync(const vector<string>& 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

File diff suppressed because it is too large Load Diff

View File

@ -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<IRemoteObject>& 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<IRemoteObject>& 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<IRemoteObject>& 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<IRemoteObject>& 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

View File

@ -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<AAFwk::Want>());
topAbility.reset(parcel.ReadParcelable<AppExecFwk::ElementName>());
baseAbility.reset(parcel.ReadParcelable<AppExecFwk::ElementName>());
reservedAbility.reset(parcel.ReadParcelable<AppExecFwk::ElementName>());
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<MissionInfo> &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<size_t>(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<MissionInfo>();
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<MissionInfo> &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

View File

@ -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<AbilityMissionInfo>& abilityMissionInfos,
std::vector<MissionInfo>& 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<AAFwk::Want> spWant = make_shared<AAFwk::Want>(iter->baseWant);
missionInfo.baseWant = spWant;
shared_ptr<AppExecFwk::ElementName> spTopAbility = make_shared<AppExecFwk::ElementName>(iter->topAbility);
missionInfo.topAbility = spTopAbility;
shared_ptr<AppExecFwk::ElementName> spBaseAbility = make_shared<AppExecFwk::ElementName>(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<MissionInfo>& missionInfos,
std::vector<AbilityMissionInfo>& 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;
}
}
}

View File

@ -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> 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> rect(data.ReadParcelable<Rect>());
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<Rect> windowBounds(data.ReadParcelable<Rect>());
std::u16string applicationLabel = data.ReadString16();
std::u16string activityLabel = data.ReadString16();
std::vector<uint8_t> icon;
PARCEL_READ_HELPER_RET(data, UInt8Vector, &icon, nullptr);
std::u16string secApplicationLabel = data.ReadString16();
std::u16string secActivityLabel = data.ReadString16();
std::vector<uint8_t> secIcon;
PARCEL_READ_HELPER_RET(data, UInt8Vector, &secIcon, nullptr);
std::u16string sourceDeviceTips = data.ReadString16();
unique_ptr<Snapshot> snapShot = make_unique<Snapshot>();
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<PixelMap> 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 = 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> 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> Snapshot::Create(const vector<uint8_t>& 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<const uint32_t *>(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> 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<const uint32_t *>(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> 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<int32_t>(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;
}
}
}

27
services/dtbschedmgr/test/BUILD.gn Executable file → Normal file
View File

@ -38,8 +38,10 @@ dsched_deps = [
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//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/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//foundation/multimedia/image_standard/interfaces/innerkits:image_native",
"//utils/native/base:utils", "//utils/native/base:utils",
] ]
@ -56,14 +58,13 @@ dsched_public_deps = [
] ]
dtbschedmgr_sources = [ dtbschedmgr_sources = [
"${distributed_service}/dtbschedmgr/src/ability_connection_wrapper_proxy.cpp",
"${distributed_service}/dtbschedmgr/src/ability_connection_wrapper_stub.cpp", "${distributed_service}/dtbschedmgr/src/ability_connection_wrapper_stub.cpp",
"${distributed_service}/dtbschedmgr/src/adapter/dnetwork_adapter.cpp", "${distributed_service}/dtbschedmgr/src/adapter/dnetwork_adapter.cpp",
"${distributed_service}/dtbschedmgr/src/bundle/bundle_manager_internal.cpp", "${distributed_service}/dtbschedmgr/src/bundle/bundle_manager_internal.cpp",
"${distributed_service}/dtbschedmgr/src/connect_death_recipient.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/deviceManager/dms_device_info.cpp",
"${distributed_service}/dtbschedmgr/src/distributed_device_node_listener.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_adapter.cpp",
"${distributed_service}/dtbschedmgr/src/distributed_sched_continuation.cpp", "${distributed_service}/dtbschedmgr/src/distributed_sched_continuation.cpp",
"${distributed_service}/dtbschedmgr/src/distributed_sched_dumper.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_service.cpp",
"${distributed_service}/dtbschedmgr/src/distributed_sched_stub.cpp", "${distributed_service}/dtbschedmgr/src/distributed_sched_stub.cpp",
"${distributed_service}/dtbschedmgr/src/dtbschedmgr_device_info_storage.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") { ohos_unittest("distributedschedsvrtest") {
@ -92,7 +100,6 @@ ohos_unittest("dschedcontinuetest") {
module_out_path = module_output_path module_out_path = module_output_path
sources = [ sources = [
"unittest/distributed_sched_ability_shell_test.cpp",
"unittest/distributed_sched_continuation_test.cpp", "unittest/distributed_sched_continuation_test.cpp",
"unittest/mock_distributed_sched.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") { group("unittest") {
testonly = true testonly = true
deps = [ deps = [
":distributedschedsvrtest", ":distributedschedsvrtest",
":dschedconnecttest", ":dschedconnecttest",
":dschedcontinuetest", ":dschedcontinuetest",
":dschedmissionmanagertest",
":dschedpermissiontest", ":dschedpermissiontest",
] ]
} }

View File

@ -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/'
}
}
}

View File

@ -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'
}

View File

@ -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
}
}
]
}
}

View File

@ -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')
},
}

View File

@ -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%')
}
}

View File

@ -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);
}
}

View File

@ -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%')
}
}

View File

@ -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);
}
};

View File

@ -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 = [];
}
}

View File

@ -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"
}
]
}

View File

@ -0,0 +1 @@
include ':entry'

View File

@ -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/'
}
}
}

View File

@ -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'
}

View File

@ -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
}
}
]
}
}

View File

@ -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");
}
};

View File

@ -0,0 +1,11 @@
{
"strings": {
"hello": "Hello",
"world": "World",
"page": "Second Page",
"next": "Next Page",
"back": "Back"
},
"Files": {
}
}

View File

@ -0,0 +1,11 @@
{
"strings": {
"hello": "您好",
"world": "世界",
"page": "第二页",
"next": "下一页",
"back": "返回"
},
"Files": {
}
}

View File

@ -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;
}

View File

@ -0,0 +1,20 @@
<!--/*
* 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.
*/-->
<div class="container" onswipe="touchMove">
<text class="title">
{{ $t('strings.hello') }} {{ title }}
</text>
</div>

View File

@ -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');
}
}

View File

@ -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);
}
};

View File

@ -0,0 +1,11 @@
{
"strings": {
"hello": "Hello",
"world": "World",
"page": "Second Page",
"next": "Next Page",
"back": "Back"
},
"Files": {
}
}

View File

@ -0,0 +1,11 @@
{
"strings": {
"hello": "您好",
"world": "世界",
"page": "第二页",
"next": "下一页",
"back": "返回"
},
"Files": {
}
}

View File

@ -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) {
}

View File

@ -0,0 +1,78 @@
<!--/*
* 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.
*/-->
<div class="container">
<button class="btn" type = "capsule" value="StartLocalAbility" onclick="onStartLocalAbilityClick" > </button>
<button class="btn" type = "capsule" value="StartRemoteAbility" onclick="onStartAbilityClick" > </button>
<button class="btn" type = "capsule" value="ContinueLocalAbility" onclick="onContinueLocalAbilityClicked" > </button>
<button class="btn" type = "capsule" value="ContinueAbility" onclick="onContinueAbilityClicked" > </button>
<button class="btn" type = "capsule" value="ConnectLocalService" onclick="ConnectLocalService" > </button>
<button class="btn" type = "capsule" value="ConnectRemoteService" onclick="onConnectRemoteServiceClicked" > </button>
<button class="btn" type = "capsule" value="DisConnectService" onclick="DisConnectService"> </button>
<dialog id="dialogForStartAbility" class="dialog-main" oncancel="cancelDialog">
<div class="dialog-div">
<text class="dialog_title_text">选择设备</text>
<list class="dialog_device_list" divider="true">
<list-item for="{{ deviceList }}" class="device_list_item">
<label class="device_item_title" target="{{ $item.id }}">{{ $item.name }}</label>
<input class="device_item_radio" type="radio" checked="{{ $item.id === 'localhost' }}"
id="{{ $item.id }}"
name="radioSample" value="{{ $item.id }}"
onchange="onRadioChangeForStart({{ $item.id }})"></input>
</list-item>
</list>
<div class="inner-btn">
<button class="dialog_cancel_button" type="text" value="取消" onclick="onDismissDialogForStartClicked"></button>
</div>
</div>
</dialog>
<dialog id="dialogForContinueAbility" class="dialog-main" oncancel="cancelDialog">
<div class="dialog-div">
<text class="dialog_title_text">选择设备</text>
<list class="dialog_device_list" divider="true">
<list-item for="{{ deviceList }}" class="device_list_item">
<label class="device_item_title" target="{{ $item.id }}">{{ $item.name }}</label>
<input class="device_item_radio" type="radio" checked="{{ $item.id === 'localhost' }}"
id="{{ $item.id }}"
name="radioSample" value="{{ $item.id }}"
onchange="onRadioChangeForContinue({{ $item.id }})"></input>
</list-item>
</list>
<div class="inner-btn">
<button class="dialog_cancel_button" type="text" value="取消" onclick="onDismissDialogForContinueClicked"></button>
</div>
</div>
</dialog>
<dialog id="dialogForConnectService" class="dialog-main" oncancel="cancelDialog">
<div class="dialog-div">
<text class="dialog_title_text">选择设备</text>
<list class="dialog_device_list" divider="true">
<list-item for="{{ deviceList }}" class="device_list_item">
<label class="device_item_title" target="{{ $item.id }}">{{ $item.name }}</label>
<input class="device_item_radio" type="radio" checked="{{ $item.id === 'localhost' }}"
id="{{ $item.id }}"
name="radioSample" value="{{ $item.id }}"
onchange="onRadioChangeForConnect({{ $item.id }})"></input>
</list-item>
</list>
<div class="inner-btn">
<button class="dialog_cancel_button" type="text" value="取消" onclick="onDismissDialogForConnectClicked"></button>
</div>
</div>
</dialog>
</div>

View File

@ -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;
},
};

View File

@ -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);
}
};

View File

@ -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 = [];
}
}

View File

@ -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"
}
]
}

View File

@ -0,0 +1 @@
include ':entry'

View File

@ -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<IDistributedSched> proxy_;
protected:
sptr<IDistributedSched> GetDms();
};
void DistributedSchedAbilityShellTest::SetUpTestCase()
{
}
void DistributedSchedAbilityShellTest::TearDownTestCase()
{
}
void DistributedSchedAbilityShellTest::SetUp()
{
}
void DistributedSchedAbilityShellTest::TearDown()
{
}
sptr<IDistributedSched> 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<IDistributedSched>(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<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> token1 = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(ERR_OK), result);
EXPECT_EQ(static_cast<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> token1 = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback1 = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(ERR_OK), result);
EXPECT_EQ(static_cast<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> token1 = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<MockDistributedSched> 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<int>(ERR_OK), result);
EXPECT_EQ(static_cast<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> 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<int>(REG_REPEAT_ABILITY_TOKEN_ERR), result1);
sptr<MockDistributedSched> 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<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(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<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(ERR_OK), result);
/**
* @tc.steps: step2. unregister ability token with token and callback
* @tc.expected: step2. return NO_APP_THREAD_ERR.
*/
sptr<MockDistributedSched> continuationCallback1 = new MockDistributedSched();
int result1 = proxy->UnregisterAbilityToken(token, continuationCallback1);
DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl;
EXPECT_EQ(static_cast<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<int>(ERR_OK), result);
/**
* @tc.steps: step2. unregister ability token with token and callback
* @tc.expected: step2. return NO_ABILITY_TOKEN_ERR.
*/
sptr<MockDistributedSched> token1 = new MockDistributedSched();
int result1 = proxy->UnregisterAbilityToken(token1, continuationCallback);
DTEST_LOG << "DistributedSchedAbilityShellTest result1: "<< result1 << std::endl;
EXPECT_EQ(static_cast<int>(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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> continuationCallback = new MockDistributedSched();
sptr<IDistributedSched> 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<MockDistributedSched> token = new MockDistributedSched();
sptr<MockDistributedSched> 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<int>(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<MockDistributedSched> continuationCallback = new MockDistributedSched();
/**
* @tc.steps: step1. add death recipient for continuation callback
*/
sptr<IRemoteObject::DeathRecipient>(new ContinuationCallbackDeathRecipient())->OnRemoteDied(continuationCallback);
DTEST_LOG << "DistributedSchedAbilityShellTest ContinuationCallbackAddDeathRecipient001 end" << std::endl;
}
} // DistributedSchedule
} // namespace OHOS

View File

@ -46,6 +46,20 @@ public:
int32_t resultCode) override; int32_t resultCode) override;
}; };
class AbilityConnectionWrapperStubTest : public AAFwk::AbilityConnectionStub {
public:
explicit AbilityConnectionWrapperStubTest(sptr<IRemoteObject> connection) : distributedConnection_(connection) {}
~AbilityConnectionWrapperStubTest() = default;
void OnAbilityConnectDone(const AppExecFwk::ElementName& element,
const sptr<IRemoteObject>& remoteObject, int32_t resultCode) override;
void OnAbilityDisconnectDone(const AppExecFwk::ElementName& element,
int32_t resultCode) override;
private:
sptr<IRemoteObject> distributedConnection_;
};
class DistributedSchedConnectTest : public testing::Test { class DistributedSchedConnectTest : public testing::Test {
public: public:
static void SetUpTestCase(); static void SetUpTestCase();
@ -54,8 +68,15 @@ public:
void TearDown(); void TearDown();
void AddSession(const sptr<IRemoteObject>& connect, const std::string& localDeviceId, void AddSession(const sptr<IRemoteObject>& connect, const std::string& localDeviceId,
const std::string& remoteDeviceId, const AAFwk::Want& want); const std::string& remoteDeviceId, const AAFwk::Want& want) const;
void RemoveSession(const sptr<IRemoteObject>& connect); void RemoveSession(const sptr<IRemoteObject>& connect) const;
void AddConnectInfo(const sptr<IRemoteObject>& connect, const std::string& localDeviceId,
const std::string& remoteDeviceId) const;
void RemoveConnectInfo(const sptr<IRemoteObject>& connect) const;
void AddConnectCount(int32_t uid) const;
void DecreaseConnectCount(int32_t uid) const;
}; };
void AbilityConnectCallbackTest::OnAbilityConnectDone(const AppExecFwk::ElementName& element, 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<IRemoteObject>& remoteObject, int32_t resultCode)
{
}
void AbilityConnectionWrapperStubTest::OnAbilityDisconnectDone(const AppExecFwk::ElementName& element,
int32_t resultCode)
{
}
void DistributedSchedConnectTest::SetUpTestCase() void DistributedSchedConnectTest::SetUpTestCase()
{ {
} }
@ -85,7 +116,7 @@ void DistributedSchedConnectTest::TearDown()
} }
void DistributedSchedConnectTest::AddSession(const sptr<IRemoteObject>& connect, void DistributedSchedConnectTest::AddSession(const sptr<IRemoteObject>& 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) { if (connect == nullptr) {
return; return;
@ -101,7 +132,7 @@ void DistributedSchedConnectTest::AddSession(const sptr<IRemoteObject>& connect,
remoteDeviceId, want.GetElement(), callerInfo, TargetComponent::HARMONY_COMPONENT); remoteDeviceId, want.GetElement(), callerInfo, TargetComponent::HARMONY_COMPONENT);
} }
void DistributedSchedConnectTest::RemoveSession(const sptr<IRemoteObject>& connect) void DistributedSchedConnectTest::RemoveSession(const sptr<IRemoteObject>& connect) const
{ {
if (connect == nullptr) { if (connect == nullptr) {
return; return;
@ -111,6 +142,54 @@ void DistributedSchedConnectTest::RemoveSession(const sptr<IRemoteObject>& conne
DistributedSchedService::GetInstance().distributedConnectAbilityMap_.erase(connect); DistributedSchedService::GetInstance().distributedConnectAbilityMap_.erase(connect);
} }
void DistributedSchedConnectTest::AddConnectInfo(const sptr<IRemoteObject>& connect,
const std::string& localDeviceId, const std::string& remoteDeviceId) const
{
if (connect == nullptr) {
return;
}
std::lock_guard<std::mutex> autoLock(DistributedSchedService::GetInstance().distributedLock_);
CallerInfo callerInfo;
callerInfo.uid = IPCSkeleton::GetCallingUid();
callerInfo.pid = IPCSkeleton::GetCallingPid();
callerInfo.sourceDeviceId = localDeviceId;
callerInfo.callerType = CALLER_TYPE_HARMONY;
sptr<IRemoteObject> callbackWrapper = new AbilityConnectionWrapperStubTest(connect);
ConnectInfo connectInfo {callerInfo, callbackWrapper};
DistributedSchedService::GetInstance().connectAbilityMap_.emplace(connect, connectInfo);
}
void DistributedSchedConnectTest::RemoveConnectInfo(const sptr<IRemoteObject>& connect) const
{
if (connect == nullptr) {
return;
}
std::lock_guard<std::mutex> 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.name: DumpConnectInfo_001
* @tc.desc: dump connect ability info by call Dump * @tc.desc: dump connect ability info by call Dump
@ -236,6 +315,81 @@ HWTEST_F(DistributedSchedConnectTest, ProcessConnectDied002, TestSize.Level0)
RemoveSession(connect); 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<AbilityConnectCallbackTest> 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<uint32_t>(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<AbilityConnectCallbackTest> connect = new AbilityConnectCallbackTest();
AddConnectInfo(connect, "123_local_device_id", "123_remote_device_id");
{
std::lock_guard<std::mutex> autoLock(distributedLock);
EXPECT_EQ(connectAbilityMap.size(), static_cast<size_t>(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<std::mutex> autoLock(distributedLock);
EXPECT_EQ(connectAbilityMap.size(), static_cast<size_t>(0));
}
RemoveConnectInfo(connect);
}
/** /**
* @tc.name: ProcessDeviceOffline001 * @tc.name: ProcessDeviceOffline001
* @tc.desc: process device offline with only one connection * @tc.desc: process device offline with only one connection
@ -340,6 +494,79 @@ HWTEST_F(DistributedSchedConnectTest, ProcessDeviceOffline003, TestSize.Level0)
RemoveSession(connect); 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<AbilityConnectCallbackTest> 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<uint32_t>(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<AbilityConnectCallbackTest> connect = new AbilityConnectCallbackTest();
AddConnectInfo(connect, "123_local_device_id", "123_remote_device_id");
{
std::lock_guard<std::mutex> autoLock(distributedLock);
EXPECT_EQ(connectAbilityMap.size(), static_cast<size_t>(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<std::mutex> autoLock(distributedLock);
EXPECT_EQ(connectAbilityMap.size(), static_cast<size_t>(0));
}
RemoveConnectInfo(connect);
}
/** /**
* @tc.name: DisconnectRemoteAbility001 * @tc.name: DisconnectRemoteAbility001
* @tc.desc: disconnect remote ability * @tc.desc: disconnect remote ability
@ -370,5 +597,42 @@ HWTEST_F(DistributedSchedConnectTest, DisconnectRemoteAbility001, TestSize.Level
RemoveSession(connect); 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<AbilityConnectCallbackTest> 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<uint32_t>(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);
}
} }
} }

View File

@ -77,23 +77,14 @@ std::shared_ptr<Want> DSchedContinuationTest::MockWant(const string& bundleName,
return spWant; return spWant;
} }
std::shared_ptr<AbilityInfo> DSchedContinuationTest::MockAbilityInfo(const string& bundleName, const string& ability,
const string& devId)
{
shared_ptr<AbilityInfo> spAbility = make_shared<AbilityInfo>();
spAbility->bundleName = bundleName;
spAbility->deviceId = devId;
return spAbility;
}
int32_t DSchedContinuationTest::StartContinuation(const sptr<IRemoteObject>& abilityToken, int32_t flags) int32_t DSchedContinuationTest::StartContinuation(const sptr<IRemoteObject>& abilityToken, int32_t flags)
{ {
string bundleName = "bundleName"; string bundleName = "bundleName";
string abilityName = "abilityName"; string abilityName = "abilityName";
string devId = "devId"; string devId = "devId";
shared_ptr<Want> spWant = MockWant(bundleName, abilityName, flags); shared_ptr<Want> spWant = MockWant(bundleName, abilityName, flags);
shared_ptr<AbilityInfo> spAbility = MockAbilityInfo(bundleName, abilityName, devId); int callerUid = 0;
return DistributedSchedService::GetInstance().StartContinuation(*spWant, *spAbility, abilityToken); return DistributedSchedService::GetInstance().StartContinuation(*spWant, abilityToken, callerUid);
} }
/** /**

View File

@ -115,8 +115,7 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_001, TestSize.Level1)
* @tc.expected: step1. StartRemoteAbility return INVALID_PARAMETERS_ERR * @tc.expected: step1. StartRemoteAbility return INVALID_PARAMETERS_ERR
*/ */
AAFwk::Want want; AAFwk::Want want;
AppExecFwk::AbilityInfo abilityInfo; int result1 = proxy->StartRemoteAbility(want, 0, 0);
int result1 = proxy->StartRemoteAbility(want, abilityInfo, 0);
DTEST_LOG << "result1:" << result1 << std::endl; DTEST_LOG << "result1:" << result1 << std::endl;
/** /**
* @tc.steps: step2. StartRemoteAbility with empty want's deviceId * @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", AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
want.SetElement(element); want.SetElement(element);
int result2 = proxy->StartRemoteAbility(want, abilityInfo, 0); int result2 = proxy->StartRemoteAbility(want, 0, 0);
DTEST_LOG << "result2:" << result2 << std::endl; DTEST_LOG << "result2:" << result2 << std::endl;
EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result1); EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result1);
@ -153,15 +152,14 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_002, TestSize.Level0)
AppExecFwk::ElementName element("123456", "com.ohos.distributedmusicplayer", AppExecFwk::ElementName element("123456", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
want.SetElement(element); want.SetElement(element);
AppExecFwk::AbilityInfo abilityInfo; int result1 = DistributedSchedService::GetInstance().StartRemoteAbility(want, 0, 0);
int result1 = DistributedSchedService::GetInstance().StartRemoteAbility(want, abilityInfo, 0);
DTEST_LOG << "result:" << result1 << std::endl; DTEST_LOG << "result:" << result1 << std::endl;
std::string deviceId; std::string deviceId;
DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(deviceId); DtbschedmgrDeviceInfoStorage::GetInstance().GetLocalDeviceId(deviceId);
AppExecFwk::ElementName element1(deviceId, "com.ohos.distributedmusicplayer", AppExecFwk::ElementName element1(deviceId, "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
want.SetElement(element1); 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; DTEST_LOG << "result:" << result2 << std::endl;
EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result1); EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result1);
EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result2); EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result2);
@ -184,10 +182,7 @@ HWTEST_F(DistributedSchedServiceTest, StartRemoteAbility_003, TestSize.Level0)
AppExecFwk::ElementName element("123456", "com.ohos.distributedmusicplayer", AppExecFwk::ElementName element("123456", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
want.SetElement(element); want.SetElement(element);
AppExecFwk::AbilityInfo abilityInfo; int result = DistributedSchedService::GetInstance().StartRemoteAbility(want, 0, 0);
GetAbilityInfo("com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility",
"com.ohos.distributedmusicplayer", "192.168.43.101", abilityInfo);
int result = DistributedSchedService::GetInstance().StartRemoteAbility(want, abilityInfo, 0);
DTEST_LOG << "result:" << result << std::endl; DTEST_LOG << "result:" << result << std::endl;
EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result); EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result);
DTEST_LOG << "DistributedSchedServiceTest StartRemoteAbility_003 end" << std::endl; 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", AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
want.SetElement(element); want.SetElement(element);
AppExecFwk::AbilityInfo abilityInfo; int result = proxy->StartRemoteAbility(want, 0, 0);
GetAbilityInfo("com.ohos.distributedmusicplayer", "com.ohos.distributedmusicplayer.MainAbility",
"com.ohos.distributedmusicplayer", "192.168.43.101", abilityInfo);
int result = proxy->StartRemoteAbility(want, abilityInfo, 0);
DTEST_LOG << "result:" << result << std::endl; DTEST_LOG << "result:" << result << std::endl;
EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result); EXPECT_EQ(static_cast<int>(INVALID_PARAMETERS_ERR), result);
DTEST_LOG << "DistributedSchedServiceTest StartRemoteAbility_004 end" << std::endl; DTEST_LOG << "DistributedSchedServiceTest StartRemoteAbility_004 end" << std::endl;
@ -274,9 +266,7 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_002, TestSize.Level
if (proxy == nullptr) { if (proxy == nullptr) {
return; return;
} }
/**
* @tc.steps: step1. set want and abilityInfo
*/
AAFwk::Want want; AAFwk::Want want;
AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
@ -288,16 +278,10 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_002, TestSize.Level
callerInfo.uid = 0; callerInfo.uid = 0;
callerInfo.sourceDeviceId = "255.255.255.255"; callerInfo.sourceDeviceId = "255.255.255.255";
IDistributedSched::AccountInfo accountInfo; 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); int result1 = proxy->StartAbilityFromRemote(want, abilityInfo, 0, callerInfo, accountInfo);
DTEST_LOG << "result1 is" << result1 << std::endl; 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", AppExecFwk::ElementName element2("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbilityService"); "com.ohos.distributedmusicplayer.MainAbilityService");
want.SetElement(element2); want.SetElement(element2);
@ -354,9 +338,7 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_004, TestSize.Level
{ {
DTEST_LOG << "DistributedSchedServiceTest StartAbilityFromRemote_004 start" << std::endl; DTEST_LOG << "DistributedSchedServiceTest StartAbilityFromRemote_004 start" << std::endl;
sptr<IDistributedSched> proxy = GetDms(); sptr<IDistributedSched> proxy = GetDms();
/**
* @tc.steps: step1. set want and abilityInfo
*/
AAFwk::Want want; AAFwk::Want want;
AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
@ -368,17 +350,11 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_004, TestSize.Level
callerInfo.uid = 0; callerInfo.uid = 0;
callerInfo.sourceDeviceId = "255.255.255.255"; callerInfo.sourceDeviceId = "255.255.255.255";
IDistributedSched::AccountInfo accountInfo; 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, int result1 = DistributedSchedService::GetInstance().StartAbilityFromRemote(want,
abilityInfo, 0, callerInfo, accountInfo); abilityInfo, 0, callerInfo, accountInfo);
DTEST_LOG << "result1:" << result1 << std::endl; 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", AppExecFwk::ElementName element2("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbilityService"); "com.ohos.distributedmusicplayer.MainAbilityService");
want.SetElement(element2); want.SetElement(element2);
@ -401,9 +377,7 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_005, TestSize.Level
{ {
DTEST_LOG << "DistributedSchedServiceTest StartAbilityFromRemote_005 start" << std::endl; DTEST_LOG << "DistributedSchedServiceTest StartAbilityFromRemote_005 start" << std::endl;
sptr<IDistributedSched> proxy = GetDms(); sptr<IDistributedSched> proxy = GetDms();
/**
* @tc.steps: step1. set want and abilityInfo
*/
AAFwk::Want want; AAFwk::Want want;
AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer", AppExecFwk::ElementName element("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbility"); "com.ohos.distributedmusicplayer.MainAbility");
@ -417,17 +391,11 @@ HWTEST_F(DistributedSchedServiceTest, StartAbilityFromRemote_005, TestSize.Level
IDistributedSched::AccountInfo accountInfo; IDistributedSched::AccountInfo accountInfo;
accountInfo.accountType = 1; accountInfo.accountType = 1;
accountInfo.groupIdList.push_back("123456"); 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, int result1 = DistributedSchedService::GetInstance().StartAbilityFromRemote(want,
abilityInfo, 0, callerInfo, accountInfo); abilityInfo, 0, callerInfo, accountInfo);
DTEST_LOG << "result1:" << result1 << std::endl; 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", AppExecFwk::ElementName element2("", "com.ohos.distributedmusicplayer",
"com.ohos.distributedmusicplayer.MainAbilityService"); "com.ohos.distributedmusicplayer.MainAbilityService");
want.SetElement(element2); want.SetElement(element2);

View File

@ -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<IDistributedSched> 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<IDistributedSched>(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<MissionInfo> 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<IDistributedSched> proxy = GetDms();
if (proxy == nullptr) {
return;
}
std::vector<MissionInfo> 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<IDistributedSched> proxy = GetDms();
if (proxy == nullptr) {
return;
}
std::vector<MissionInfo> 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<MissionInfo> 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<MissionInfo> 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

View File

@ -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<IDistributedSched> proxy_;
sptr<IDistributedSched> GetDms();
};
} // namespace DistributedSchedule
} // namespace OHOS
#endif /* SERVICES_DTBSCHEDMGR_TEST_UNITTEST_MISSION_DMS_MISSION_MANAGER_TEST_H */

View File

@ -24,7 +24,7 @@ using namespace OHOS::AppExecFwk;
namespace OHOS { namespace OHOS {
namespace DistributedSchedule { namespace DistributedSchedule {
int32_t MockDistributedSched::StartRemoteAbility(const OHOS::AAFwk::Want& want, 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; return 0;
} }
@ -36,8 +36,8 @@ int32_t MockDistributedSched::StartAbilityFromRemote(const OHOS::AAFwk::Want& wa
return 0; return 0;
} }
int32_t MockDistributedSched::StartContinuation(const OHOS::AAFwk::Want& want, int32_t MockDistributedSched::StartContinuation(const OHOS::AAFwk::Want& want, const sptr<IRemoteObject>& abilityToken,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& abilityToken) int32_t callerUid)
{ {
return 0; return 0;
} }
@ -53,20 +53,8 @@ int32_t MockDistributedSched::NotifyContinuationResultFromRemote(int32_t session
return 0; return 0;
} }
int32_t MockDistributedSched::RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
return 0;
}
int32_t MockDistributedSched::UnregisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback)
{
return 0;
}
int32_t MockDistributedSched::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, int32_t MockDistributedSched::ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& connect) const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid)
{ {
return 0; return 0;
} }
@ -93,5 +81,78 @@ int32_t MockDistributedSched::NotifyProcessDiedFromRemote(const CallerInfo& call
{ {
return 0; 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<IRemoteObject>& obj)
{
return ERR_NONE;
}
int32_t MockDistributedSched::UnRegisterRemoteMissionListener(const std::u16string& devId,
const sptr<IRemoteObject>& 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<MissionInfo>& 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<std::u16string>& deviceIds,
std::vector<int32_t>& values)
{
return;
}
int32_t MockDistributedSched::GetOsdSwitchValueFromRemote()
{
return ERR_NONE;
}
int32_t MockDistributedSched::GetMissionInfos(const std::string& deviceId, int32_t numMissions,
std::vector<MissionInfo>& missionInfos)
{
return ERR_NONE;
}
int32_t MockDistributedSched::PrepareAndSyncMissionsFromRemote(const CallerInfo& callerInfo,
std::vector<MissionInfo>& 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 DistributedSchedule
} // namespace OHOS } // namespace OHOS

View File

@ -28,27 +28,39 @@ public:
} }
~MockDistributedSched() = default; ~MockDistributedSched() = default;
int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode) override;
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode) override;
int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want, int32_t StartAbilityFromRemote(const OHOS::AAFwk::Want& want,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo, const OHOS::AppExecFwk::AbilityInfo& abilityInfo, int32_t requestCode, const CallerInfo& callerInfo,
const AccountInfo& accountInfo) override; const AccountInfo& accountInfo) override;
int32_t StartContinuation(const OHOS::AAFwk::Want& want, int32_t StartContinuation(const OHOS::AAFwk::Want& want, const sptr<IRemoteObject>& abilityToken,
const OHOS::AppExecFwk::AbilityInfo& abilityInfo, const sptr<IRemoteObject>& abilityToken) override; int32_t callerUid) override;
void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override; void NotifyCompleteContinuation(const std::u16string& devId, int32_t sessionId, bool isSuccess) override;
int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override; int32_t NotifyContinuationResultFromRemote(int32_t sessionId, bool isSuccess) override;
int32_t RegisterAbilityToken(const sptr<IRemoteObject>& abilityToken, int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want,
const sptr<IRemoteObject>& continuationCallback) override; const sptr<IRemoteObject>& connect, int32_t callerUid, int32_t callerPid) override;
int32_t UnregisterAbilityToken(const sptr<IRemoteObject>& abilityToken,
const sptr<IRemoteObject>& continuationCallback) override;
int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect) override;
int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) override; int32_t DisconnectRemoteAbility(const sptr<IRemoteObject>& connect) override;
int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo, int32_t ConnectAbilityFromRemote(const OHOS::AAFwk::Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override; const sptr<IRemoteObject>& connect, const CallerInfo& callerInfo, const AccountInfo& accountInfo) override;
int32_t DisconnectAbilityFromRemote(const sptr<IRemoteObject>& connect, int32_t DisconnectAbilityFromRemote(const sptr<IRemoteObject>& connect,
int32_t uid, const std::string& sourceDeviceId) override; int32_t uid, const std::string& sourceDeviceId) override;
int32_t NotifyProcessDiedFromRemote(const CallerInfo& callerInfo) 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<IRemoteObject>& obj) override;
int32_t UnRegisterRemoteMissionListener(const std::u16string& devId, const sptr<IRemoteObject>& obj) override;
int32_t GetMissionInfos(const std::string& deviceId, int32_t numMissions,
std::vector<MissionInfo>& 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<MissionInfo>& missionInfos,
const CallerInfo& callerInfo) override;
int32_t CheckSupportOsd(const std::string& deviceId) override;
void GetCachedOsdSwitch(std::vector<std::u16string>& deviceIds, std::vector<int32_t>& 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<MissionInfo>& missionInfos) override;
int32_t UnRegisterMissionListenerFromRemote(const CallerInfo& callerInfo) override;
private: private:
bool expectedTrue_ = false; bool expectedTrue_ = false;
}; };